@asmlift/core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +22 -16
  2. package/package.json +1 -1
  3. package/src/backend/c.ts +1 -0
  4. package/src/backend/cfamily.ts +238 -167
  5. package/src/backend/cpp.ts +1 -0
  6. package/src/backend/pascal.ts +26 -12
  7. package/src/contracts.ts +194 -39
  8. package/src/declare.ts +41 -4
  9. package/src/frontend/mips.ts +11 -0
  10. package/src/frontend/ppc.ts +43 -7
  11. package/src/frontend/ssa.ts +404 -29
  12. package/src/frontend/thumb.ts +2176 -686
  13. package/src/ir/alias.ts +54 -0
  14. package/src/ir/bits.ts +75 -0
  15. package/src/ir/core.ts +337 -2
  16. package/src/ir/opcodes.ts +140 -21
  17. package/src/ir/parse.ts +19 -2
  18. package/src/ir/print.ts +27 -2
  19. package/src/ir/simplify.ts +190 -3
  20. package/src/ir/struct-names.ts +42 -0
  21. package/src/ir/verify.ts +43 -49
  22. package/src/l3/address.ts +62 -0
  23. package/src/l3/argbase.ts +2 -1
  24. package/src/l3/ast.ts +464 -57
  25. package/src/l3/basecse.ts +664 -76
  26. package/src/l3/coalesce.ts +429 -43
  27. package/src/l3/dce.ts +31 -9
  28. package/src/l3/gates.ts +21 -0
  29. package/src/l3/hoist.ts +293 -14
  30. package/src/l3/homesplit.ts +285 -0
  31. package/src/l3/initfirst.ts +301 -0
  32. package/src/l3/inlinebase.ts +193 -0
  33. package/src/l3/mentions.ts +113 -0
  34. package/src/l3/mulfirst.ts +42 -0
  35. package/src/l3/nearbase.ts +152 -0
  36. package/src/l3/offmember.ts +371 -0
  37. package/src/l3/parkfirst.ts +96 -0
  38. package/src/l3/pollguard.ts +154 -0
  39. package/src/l3/ptrfield.ts +227 -0
  40. package/src/l3/regspell.ts +110 -85
  41. package/src/l3/reindex.ts +715 -78
  42. package/src/l3/scopebase.ts +644 -218
  43. package/src/l3/sinkinit.ts +40 -0
  44. package/src/l3/slotorder.ts +123 -0
  45. package/src/l3/storage.ts +48 -0
  46. package/src/l3/symbol-refs.ts +41 -8
  47. package/src/l3/tailmerge.ts +15 -0
  48. package/src/l3/typing.ts +198 -9
  49. package/src/l3/unmerge.ts +263 -0
  50. package/src/l3/unreduce.ts +971 -0
  51. package/src/l3/volatileptr.ts +207 -0
  52. package/src/l3/volatileval.ts +130 -0
  53. package/src/l3/volstore.ts +229 -0
  54. package/src/l3/zerosub.ts +62 -0
  55. package/src/pattern/engine.ts +236 -13
  56. package/src/pipeline.ts +157 -56
  57. package/src/proto.ts +112 -14
  58. package/src/raise/arrays.ts +6 -1
  59. package/src/raise/divpow2.ts +2 -2
  60. package/src/raise/globalshape.ts +1038 -0
  61. package/src/raise/gvn.ts +33 -18
  62. package/src/raise/latch.ts +126 -0
  63. package/src/raise/memberarrays.ts +594 -0
  64. package/src/raise/narrow.ts +124 -0
  65. package/src/raise/narrowlocal.ts +556 -0
  66. package/src/raise/paramwidth.ts +179 -0
  67. package/src/raise/pre-recovery.ts +97 -14
  68. package/src/raise/recover.ts +56 -23
  69. package/src/raise/retsink.ts +210 -10
  70. package/src/raise/shortcircuit.ts +474 -74
  71. package/src/raise/struct-arrays.ts +19 -2
  72. package/src/raise/structs.ts +33 -3
  73. package/src/rank-axes.ts +630 -0
  74. package/src/rank-declare.ts +256 -0
  75. package/src/rank.ts +1723 -272
  76. package/src/structure/analysis.ts +1392 -141
  77. package/src/structure/bitfields.ts +332 -0
  78. package/src/structure/globalaccess.ts +274 -0
  79. package/src/structure/hazards.ts +411 -20
  80. package/src/structure/loops.ts +2 -49
  81. package/src/structure/namecoalesce.ts +435 -0
  82. package/src/structure/structure.ts +2678 -526
  83. package/src/structure/switch-recover.ts +616 -144
  84. package/src/symbols.ts +62 -1
  85. package/src/target.ts +367 -24
  86. package/src/trace.ts +111 -32
package/src/l3/gates.ts CHANGED
@@ -42,6 +42,27 @@ export function without<Ctx>(gates: readonly Gate<Ctx>[], id: string): readonly
42
42
  return gates.filter((g) => g.id !== id);
43
43
  }
44
44
 
45
+ // NO `just(table, ids)` SELECTOR, deliberately. Selecting rule OBJECTS by id shares the predicate
46
+ // AND the `sound` claim AND the `guardedBy` guard, and a second consumer of a rule wants only the
47
+ // first of the three: a rule that is sound for a declaration is a heuristic for a generated
48
+ // candidate, and the guard the contract test then checks ablates the rule against the OTHER
49
+ // consumer. What a second consumer shares is a PREDICATE — an ordinary function — and what it owns
50
+ // is its own rule objects. `ORDER_SHAPE_GATES` (raise/globalshape.ts) is the worked example, with
51
+ // the over-admission id-selection would carry.
52
+
53
+ /** `without` for SHIPPED code. A test may ablate any gate — that is how `guardedBy` differential
54
+ * tests work — but a pass that re-runs itself with an ablated table as a ranked candidate may
55
+ * only drop a HEURISTIC: ablating a `sound: true` gate would ship semantically wrong candidates,
56
+ * and on a nonmatch row the best-scoring source is shown to the user. A derived table is a
57
+ * top-level const, so the throw fires at import — the mistake cannot ship. */
58
+ export function ablateHeuristic<Ctx>(gates: readonly Gate<Ctx>[], id: string): readonly Gate<Ctx>[] {
59
+ const g = gates.find((x) => x.id === id);
60
+ if (g?.sound) {
61
+ throw new Error(`gate '${id}' is sound — a shipped ablation of it emits wrong candidates`);
62
+ }
63
+ return without(gates, id);
64
+ }
65
+
45
66
  /** Structural defects in a gate table — the part checkable without running the pass. Returns
46
67
  * findings rather than throwing, so core stays free of a test-framework import. */
47
68
  export function gateTableDefects<Ctx>(gates: readonly Gate<Ctx>[]): string[] {
package/src/l3/hoist.ts CHANGED
@@ -1,16 +1,20 @@
1
- // L3 — the naming MECHANISM shared by every pass that hoists a value into a fresh local.
1
+ // L3 — the MECHANISMS a pass needs to place a hoisted local: how a fresh name is chosen, where the
2
+ // leading run of base inits starts and ends, and where in the body that run goes.
2
3
  //
3
- // Two passes name bases today (`basecse.ts` hoists a REUSED base; `argbase.ts` names a call's
4
- // argument bases), and they differ in POLICY which bases are eligible, and when it is worth
5
- // doing but not in how a name is chosen. That half was copied, and the copy silently lost a
6
- // safety guard: basecse added the callee-name exclusion in its own audit precisely so a hoist
7
- // local could not shadow a called function, and the second implementation did not have it. A third
8
- // hoisting pass would lose it again, so the mechanism lives here and the policy stays with each
9
- // caller.
4
+ // Their users differ. Every pass that mints a local takes `nameAllocator` (or `takenNames`, to
5
+ // number its own); the three that touch basecse's leading init run read the rest basecse and
6
+ // nearbase mint into it, sinkinit moves statements out of it, and all three have to agree on where
7
+ // it stops and how a body carrying it is rebuilt. What stays with each caller is ELIGIBILITY:
8
+ // which values become a local at all, and when it is worth doing. WHERE the run goes is
9
+ // `placeBaseLocals`'s `placement` argument, and that argument is two questions rather than one
10
+ // see `HoistPlacement` and `BaseInitPlacement`. Everything lives in one file because each half was
11
+ // a per-caller copy once and every copy drifted from its original.
10
12
  import type { Expr, SFn, Stmt } from './ast';
11
- import { mapExprChildren, stmtChildren, stmtExprs } from './ast';
13
+ import { exprChildren, mapStmtLists, stmtChildren, stmtExprs, stmtLists } from './ast';
14
+ import { localMentions } from './mentions';
12
15
 
13
- /** Every identifier a hoist name must not collide with, anywhere in `sfn`.
16
+ /** Every identifier a MINTED name must not collide with, anywhere in `sfn` — the hoists below,
17
+ * and reindex's induction names.
14
18
  *
15
19
  * Wider than "the declared locals" on purpose, and each addition is a real collision:
16
20
  * - params and locals, obviously;
@@ -18,7 +22,7 @@ import { mapExprChildren, stmtChildren, stmtExprs } from './ast';
18
22
  * silently redirects every later mention of it;
19
23
  * - every CALL TARGET — a local named like a callee shadows the function;
20
24
  * - every assignment target, which includes names no declaration list carries. */
21
- function takenNames(sfn: SFn): Set<string> {
25
+ export function takenNames(sfn: SFn): Set<string> {
22
26
  const taken = new Set<string>([...sfn.params.map((p) => p.name), ...sfn.locals.map((l) => l.name)]);
23
27
  const visit = (e: Expr): void => {
24
28
  if (e.k === 'var' || e.k === 'addr') {
@@ -27,10 +31,9 @@ function takenNames(sfn: SFn): Set<string> {
27
31
  if (e.k === 'call') {
28
32
  taken.add(e.fn);
29
33
  }
30
- mapExprChildren(e, (c) => {
34
+ for (const c of exprChildren(e)) {
31
35
  visit(c);
32
- return c;
33
- });
36
+ }
34
37
  };
35
38
  const walk = (stmts: Stmt[]): void => {
36
39
  for (const s of stmts) {
@@ -63,3 +66,279 @@ export function nameAllocator(sfn: SFn): () => string {
63
66
  return nm;
64
67
  };
65
68
  }
69
+
70
+ export type BaseInit = Extract<Stmt, { k: 'assign' }>;
71
+
72
+ /** Whether `s` is a BASE INIT: a ptr-cast of an `addr`/`const` leaf assigned into a declared
73
+ * NON-VOLATILE local. It reads nothing and writes its own plain cell, which is what makes the run
74
+ * of them re-orderable and each of them movable. The volatile exclusion is load-bearing — two
75
+ * writes to `volatile` locals are observably ordered, so one at the head simply ends the run. */
76
+ function isBaseInit(s: Stmt, plainLocals: ReadonlySet<string>): s is BaseInit {
77
+ return (
78
+ s.k === 'assign' &&
79
+ plainLocals.has(s.name) &&
80
+ s.value.k === 'cast' &&
81
+ s.value.to.kind === 'ptr' &&
82
+ (s.value.e.k === 'addr' || s.value.e.k === 'const')
83
+ );
84
+ }
85
+
86
+ /** `body` split at the end of its LEADING run of base inits — the run `placeBaseLocals` places. */
87
+ function splitLeadingBaseInits(sfn: SFn, body: readonly Stmt[]): { inits: BaseInit[]; rest: Stmt[] } {
88
+ const plain = new Set(sfn.locals.filter((l) => !l.volatile).map((l) => l.name));
89
+ let n = 0;
90
+ while (n < body.length && isBaseInit(body[n], plain)) {
91
+ n++;
92
+ }
93
+ return { inits: body.slice(0, n) as BaseInit[], rest: body.slice(n) };
94
+ }
95
+
96
+ /** For each local, the index of the first TOP-LEVEL statement of `rest` that mentions it, absent
97
+ * when none does. `mentions.ts`'s notion of a mention, so `&p` counts: an init must precede the
98
+ * address being taken as surely as it must precede a read. */
99
+ function firstUseIn(sfn: SFn, rest: readonly Stmt[]): Map<string, number> {
100
+ const out = new Map<string, number>();
101
+ for (const [name, m] of localMentions({ ...sfn, body: [...rest] })) {
102
+ if (m.firstAt !== null) {
103
+ out.set(name, m.firstAt);
104
+ }
105
+ }
106
+ return out;
107
+ }
108
+
109
+ /** Does `s` mention `name` in its OWN expressions or as its assignment target — nothing nested?
110
+ * `mentions.ts`'s notion of a mention (`&p` counts), asked of one statement rather than of a
111
+ * top-level index. */
112
+ function mentionsHere(s: Stmt, name: string): boolean {
113
+ if (s.k === 'assign' && s.name === name) {
114
+ return true;
115
+ }
116
+ let found = false;
117
+ const visit = (e: Expr): void => {
118
+ if ((e.k === 'var' || e.k === 'addr') && e.name === name) {
119
+ found = true;
120
+ }
121
+ for (const c of exprChildren(e)) {
122
+ visit(c);
123
+ }
124
+ };
125
+ stmtExprs(s).forEach(visit);
126
+ return found;
127
+ }
128
+
129
+ /** …and the same question of the whole subtree. */
130
+ function mentionsStmt(s: Stmt, name: string): boolean {
131
+ return mentionsHere(s, name) || stmtChildren(s).some((c) => mentionsStmt(c, name));
132
+ }
133
+
134
+ /** `{ list, at }` for a top-level first-use index, or null when there is none — the `first-use`
135
+ * answer in the shape the `scope` one comes back in. */
136
+ function mapTo(list: Stmt[], at: number | undefined): { list: Stmt[]; at: number } | null {
137
+ return at === undefined ? null : { list, at };
138
+ }
139
+
140
+ /** How many times each statement appears in `list`. */
141
+ function tally(list: readonly Stmt[]): Map<Stmt, number> {
142
+ const out = new Map<Stmt, number>();
143
+ for (const s of list) {
144
+ out.set(s, (out.get(s) ?? 0) + 1);
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /** The innermost statement list holding EVERY mention of `name`, and the index in it of the first
150
+ * statement that mentions it. This is `firstUseIn` continued downward, and it descends only on
151
+ * three facts: exactly one statement of this list mentions the name, that statement mentions it
152
+ * nowhere OUTSIDE the lists it opens (its own condition, or a `for`'s `init`/`inc` — which are
153
+ * statements no list holds), and exactly one of those lists holds it. Any of the three failing
154
+ * means a nested list does not hold every mention, so this list is as deep as the init may go.
155
+ * Stopping at the top level reproduces `first-use` exactly, which is what lets `scope` be a
156
+ * placement rather than a second policy.
157
+ *
158
+ * DOMINATION IS THE DESCENT'S OWN INVARIANT: every mention is at or after the returned index
159
+ * within the returned list, so the init reaches all of them — including from inside a loop body,
160
+ * where it simply re-assigns the same link-time constant. `hoistBaseLocals` still CHECKS it
161
+ * (`assertHoistsDominate`), because an argument is not a check.
162
+ *
163
+ * A LOOP BODY IS ALSO A LIST NO SHIPPED CANDIDATE CAN REACH, which is a stronger statement than
164
+ * the safety argument above and the one that keeps re-assigning a base per iteration out of
165
+ * published C. Every gate table any caller pairs with `scope` keeps `BASECSE_GATES`' `loop` rule —
166
+ * `ORDERBASE_GATES`, the only roster table at this placement, ablates `cast-base` and `single-use`
167
+ * and nothing else — so a base with ANY use inside a loop is refused before a placement is
168
+ * consulted. Both halves are pinned in test/sinkinit.test.ts: neither table admits one, and where
169
+ * the mechanism is handed such a base directly the tree it emits still dominates. Loop-body bases
170
+ * are `l3/scopebase.ts`'s, which plans its own local rather than moving this run. */
171
+ function scopeSite(list: Stmt[], name: string): { list: Stmt[]; at: number } | null {
172
+ const idxs = list.flatMap((s, i) => (mentionsStmt(s, name) ? [i] : []));
173
+ if (idxs.length === 0) {
174
+ return null;
175
+ }
176
+ const here = { list, at: idxs[0] };
177
+ if (idxs.length > 1) {
178
+ return here;
179
+ }
180
+ const s = list[idxs[0]];
181
+ const lists = stmtLists(s);
182
+ const inner = lists.filter((l) => l.some((x) => mentionsStmt(x, name)));
183
+ if (inner.length !== 1) {
184
+ return here;
185
+ }
186
+ // A MULTISET difference, not a set one: `stmtChildren` yields a `for`'s `init` and `inc` beside
187
+ // its body, and one `Stmt` object may sit at two tree positions. Subtracting by identity would
188
+ // read a shared `init` as opened and miss the mention it makes before the body ever runs.
189
+ const opened = tally(lists.flat());
190
+ const outside =
191
+ mentionsHere(s, name) ||
192
+ [...tally(stmtChildren(s))].some(([c, n]) => n > (opened.get(c) ?? 0) && mentionsStmt(c, name));
193
+ return outside ? here : (scopeSite(inner[0], name) ?? here);
194
+ }
195
+
196
+ /** WHERE a run of base inits sits, once this file has put it in FIRST-USE order — the order the
197
+ * compiler loads the pool words in (`l3/basecse.ts`'s `collect`), so it is the order a reference
198
+ * spelling that named these bases would have.
199
+ *
200
+ * `head` keeps the whole ordered run at the top of the body.
201
+ * `first-use` then moves each init down to immediately before the statement that first mentions
202
+ * it, which is where a base reached ONCE was loaded and which keeps a base first touched halfway
203
+ * down the body out of the live range above it.
204
+ * `scope` reads that same query one nesting level at a time: an init whose every mention lives
205
+ * inside ONE nested list goes inside that list, at the first mention there. `first-use` stops at
206
+ * the top-level statement — a base used only inside an `if` arm still has its pool word loaded
207
+ * above the branch — and on agbcc, whose statement order survives into the object, the two are
208
+ * different bytes. Where no nested list holds every mention this IS `first-use`, which is what
209
+ * makes it a placement rather than a second policy.
210
+ *
211
+ * These three are the axis a roster admission may state (rank.ts) and the only values
212
+ * `hoistBaseLocals` accepts. */
213
+ export type HoistPlacement = 'head' | 'first-use' | 'scope';
214
+
215
+ /** `HoistPlacement` plus the ABSTENTION: `prepend` puts the minted inits above a run that keeps
216
+ * the order it arrived in, consulting neither the first-use query nor the sort. A third VALUE and
217
+ * not a third position, passed only by `l3/nearbase.ts`, whose header carries the argument for it.
218
+ *
219
+ * `hoistBaseLocals` may NOT be handed this: prepending there spells a newly minted base's pool
220
+ * load above locals the compiler loads first (`l3/basecse.ts`'s own header), so the two passes
221
+ * take different types rather than the same type and a comment. */
222
+ export type BaseInitPlacement = HoistPlacement | 'prepend';
223
+
224
+ /** `sfn.body` rebuilt with `minted` added to its leading base-init run and the whole run placed
225
+ * per `placement`, plus which inits ended up away from the head.
226
+ *
227
+ * `sfn` is both the statements and the DECLARATION ENVIRONMENT the first-use and mention queries
228
+ * resolve against, so a caller that mints must pass a shell that already declares the new names
229
+ * AND carries the rewritten body. One argument rather than two is the point: a shell whose
230
+ * declarations and statements disagree is not expressible here.
231
+ *
232
+ * ONE ORDER, THEN THE POLICY. Under both `HoistPlacement` values the run is put in FIRST-USE
233
+ * order before `placement` is consulted — pool-load order, and what makes the two COMPOSABLE
234
+ * rather than merely adjacent: `first-use` applied to a `head` result is `first-use` applied to
235
+ * the input, so `/livebase/sinkinit` (a hoist at the head that a second pass then sinks) and
236
+ * `/basefold/sinkinit` (one hoist placed at first use) are the same transform and the `/sinkinit`
237
+ * suffix names one thing wherever it appears. Order the run only on the `head` branch and they
238
+ * part company on the inits that CANNOT move, which is the half of the run whose order the
239
+ * compiler still reads. Pinned in test/sinkinit.test.ts. `prepend` opts out of all of it.
240
+ *
241
+ * Ties keep list order — existing inits before minted ones, and two inits assigning the SAME
242
+ * local in their original sequence, which a stable sort is what guarantees: they write one cell,
243
+ * so their order is the only thing that says which value it ends up holding. Two that SINK to the
244
+ * same statement keep it too, which is what the splice loop's second sort key is for.
245
+ *
246
+ * Under `first-use`, an init then moves down if the function assigns its local exactly ONCE (the
247
+ * move would otherwise cross that other write), something in the remaining body mentions it, and
248
+ * it is not already sitting at the first such statement.
249
+ *
250
+ * IT REPORTS THE MOTION rather than its size, and its callers judge those lists instead of arguing
251
+ * about them. `moved` names every init that left the leading run; `nested` is the subset that
252
+ * landed in a list OTHER than the top-level one, which only `scope` can produce.
253
+ *
254
+ * `nested` empty under `scope` means the placement DEGENERATED — every init went exactly where
255
+ * `first-use` would have put it, so the emitted tree is that placement's spelling under a second
256
+ * name. A caller offering placements as candidates has to know, or it enumerates one spelling
257
+ * twice (l3/basecse.ts's `hoistBaseLocals`). */
258
+ export function placeBaseLocals(
259
+ sfn: SFn,
260
+ minted: readonly BaseInit[],
261
+ placement: BaseInitPlacement,
262
+ ): { body: Stmt[]; moved: readonly string[]; nested: readonly string[] } {
263
+ const still = { moved: [], nested: [] };
264
+ const body = sfn.body;
265
+ const { inits: head, rest } = splitLeadingBaseInits(sfn, body);
266
+ if (head.length + minted.length === 0) {
267
+ return { body: [...body], ...still };
268
+ }
269
+ if (placement === 'prepend') {
270
+ return { body: [...minted, ...head, ...rest], ...still };
271
+ }
272
+ const firstUse = firstUseIn(sfn, rest);
273
+ const at = (s: BaseInit): number => firstUse.get(s.name) ?? rest.length;
274
+ const all = [...head, ...minted].sort((a, b) => at(a) - at(b));
275
+ if (placement === 'head') {
276
+ return { body: [...all, ...rest], ...still };
277
+ }
278
+ const whole = localMentions({ ...sfn, body: [...all, ...rest] });
279
+ const stay: BaseInit[] = [];
280
+ const sunk: { site: Stmt[]; at: number; init: BaseInit; i: number }[] = [];
281
+ for (const [i, init] of all.entries()) {
282
+ // Assigned exactly once, or the move would cross the other write.
283
+ const site =
284
+ whole.get(init.name)?.assigns === 1
285
+ ? placement === 'scope'
286
+ ? scopeSite(rest, init.name)
287
+ : mapTo(rest, firstUse.get(init.name))
288
+ : null;
289
+ // Nothing mentions it, or it is already sitting at the first statement of the top-level list:
290
+ // there is no move to make and the init stays in the leading run.
291
+ if (site === null || (site.list === rest && site.at === 0)) {
292
+ stay.push(init);
293
+ } else {
294
+ sunk.push({ site: site.list, at: site.at, init, i });
295
+ }
296
+ }
297
+ // Rebuild `rest` around the sink sites, matching each list by IDENTITY against the tree the sites
298
+ // were computed on — so the walk emits a fresh list only along the path to a site and hands every
299
+ // other statement back unchanged.
300
+ const bySite = new Map<Stmt[], typeof sunk>();
301
+ for (const s of sunk) {
302
+ bySite.set(s.site, [...(bySite.get(s.site) ?? []), s]);
303
+ }
304
+ const rebuild = (list: Stmt[]): Stmt[] => {
305
+ const here = bySite.get(list);
306
+ // CONSUMED: one `Stmt[]` object sitting at two tree positions takes the init at the FIRST of
307
+ // them, never at both, where a second splice would write the same local twice. `scopeSite`
308
+ // cannot return such a list — sharing means two statements mention the local, which stops the
309
+ // descent at their common list — so this restates that invariant where breaking it would be
310
+ // silent. Nothing in the L3 contract forbids the sharing itself (l3/scopebase.ts records a
311
+ // producer that shares an expression node).
312
+ bySite.delete(list);
313
+ let changed = here !== undefined;
314
+ const mapped = list.map((s) => {
315
+ let inner = false;
316
+ const out = mapStmtLists(s, (l) => {
317
+ const r = rebuild(l);
318
+ inner ||= r !== l;
319
+ return r;
320
+ });
321
+ changed ||= inner;
322
+ return inner ? out : s;
323
+ });
324
+ if (!changed) {
325
+ return list;
326
+ }
327
+ // Descending by target index, so an earlier insertion does not shift the position a later one
328
+ // was computed against — and descending among the inits SHARING a target too, because splicing
329
+ // each at the same index puts the last one spliced on top. Without that second key a run that
330
+ // sinks together comes out REVERSED, which is the one order this function exists to avoid: it
331
+ // is pool-load order the sort above is spelling, and `head` would have kept it.
332
+ for (const { at: to, init } of [...(here ?? [])].sort((a, b) => b.at - a.at || b.i - a.i)) {
333
+ mapped.splice(to, 0, init);
334
+ }
335
+ return mapped;
336
+ };
337
+ // `site !== rest` is the whole nesting question: every site is a list of the tree the sites were
338
+ // computed on, and the top-level one is `rest` by identity.
339
+ return {
340
+ body: [...stay, ...rebuild(rest)],
341
+ moved: sunk.map((s) => s.init.name),
342
+ nested: sunk.filter((s) => s.site !== rest).map((s) => s.init.name),
343
+ };
344
+ }
@@ -0,0 +1,285 @@
1
+ // The `/livebase-block × /regionbase` PAIRING (rank.ts `/livebase-block/homesplit`): one base kept
2
+ // at the function head and a SECOND base split into one local per region, in the same function.
3
+ //
4
+ // WHY IT IS NOT REACHABLE FROM EITHER LEVER. Both are whole-FUNCTION policies over the bases they
5
+ // bind: `hoistBaseLocals` homes every key its table admits at one placement, and
6
+ // `hoistScopedBases` splits every key its region rule admits. A function whose two bases want
7
+ // OPPOSITE answers is spelled by neither. `synthetic:dmapoll` is that function and its endpoint is
8
+ // compiled rather than argued: with both bases at function scope agbcc scores 11, with both split
9
+ // per region 18, with neither hoisted 69 — and 0 only where the two policies apply to DIFFERENT
10
+ // bases (the lattice in apps/benchmark/dataset/synthetic.ts).
11
+ //
12
+ // A PIPE, NEVER A MERGE, and that is the whole safety argument for the names. `hoistBaseLocals`
13
+ // runs FIRST with one key withheld; every key it homes now reads through a pointer LOCAL, which
14
+ // `SCOPEBASE_ELIGIBILITY`'s `shadowed-or-nonarray-base` refuses outright, so no key the head hoist
15
+ // claimed reaches the second pass at all. What that pass DOES see is the withheld key together with
16
+ // every base the caller's table never bound, and it splits those too — `splitHomeBases` counts the
17
+ // withheld key's own entries and nothing else. `nameAllocator` (l3/hoist.ts) re-derives its taken
18
+ // names from the tree it is handed, so the second pass cannot re-mint the first's. Merging two runs
19
+ // over ONE input is the shape that would collide, and nothing here does it.
20
+ //
21
+ // WHICH KEY IS WITHHELD IS NOT DERIVABLE, so every admitted key is offered as its own candidate,
22
+ // LABELLED WITH THAT KEY, and the differ referees — the same posture `/scopebase` and `/regionbase`
23
+ // take toward each other. The label carries `homeSplitTag(key)` because a candidate label is an
24
+ // IDENTITY: `bench diff` and docs/ranked-repro.md compare candidates by it, so one label over two
25
+ // withholds would hide a program swap from both. The withhold itself is DATA: one rejection
26
+ // prepended to the caller's own admission table, in the `Gate<BaseKey>` type that table already
27
+ // has, so `firstRejection` attributes a refusal to it, `without` ablates it, and the composed table
28
+ // is on `gate-contract.test.ts`'s roster like any other.
29
+ //
30
+ // EXACTLY ONE KEY IS WITHHELD, and the arity is a claim rather than an oversight. A two-key withhold
31
+ // exists only where the caller's table binds three — `homesplit-fan-cap` admits no more — and there
32
+ // it is the three further pairs, each carrying the three respells rank.ts derives from one pipe:
33
+ // NINE more candidates per axis point on those functions alone, before any shape product, and no
34
+ // row asks for one. `l3/volatileptr.ts`'s `volatileSubsetCandidates` enumerates every proper subset
35
+ // under the same cap; it does that because a row demanded each of them. Widen this the same way,
36
+ // on a row.
37
+ //
38
+ // SEMANTICS ARE PRESERVED BY CONSTRUCTION — both halves only re-spell where the address of a global
39
+ // is materialized, and each half's own contracts (`placeBaseLocals`' ordering, `assertHoistsDominate`
40
+ // on the region plan) still run. What the pairing can get WRONG is bytes, and one qualifier.
41
+ import { addrConst, inRange } from './address';
42
+ import type { Expr, SFn, Stmt } from './ast';
43
+ import { exprChildren, stmtExprs, stmtLists } from './ast';
44
+ import { type BaseKey, baseSites, hoistBaseLocals, leafId, parseBaseKey } from './basecse';
45
+ import { type Gate, firstRejection } from './gates';
46
+ import type { HoistPlacement } from './hoist';
47
+ import { applyScopedBasePlan, planScopedBases, scopedBaseKey } from './scopebase';
48
+ import { volatileEligibleValue } from './volatileptr';
49
+
50
+ /** `gates` with `key` refused. The withhold goes FIRST so `firstRejection` attributes a refusal to
51
+ * it rather than to whichever inherited rule would also have fired. */
52
+ export const withholdingKey = (gates: readonly Gate<BaseKey>[], key: string): readonly Gate<BaseKey>[] => [
53
+ {
54
+ id: 'withheld-key',
55
+ why: 'this key is the one the region rule is to split, so the head hoist must not claim it',
56
+ sound: false,
57
+ rejects: (c) => c.key === key,
58
+ },
59
+ ...gates,
60
+ ];
61
+
62
+ /** The withheld key as a LABEL token: `c:67109076 4 true` → `0x40000d4.4s`. Width and signedness
63
+ * ride because they are part of the key — two keys over one address are two different spellings.
64
+ *
65
+ * PARSED BY THE KEY'S PRODUCER (`l3/basecse.ts`'s `parseBaseKey`, beside `keyOf`), because a base
66
+ * id is not one space-free word and a local split here gets it wrong in both directions. `baseId`
67
+ * spells a CAST base as `a:gEnigmaBerries <Elem5*>` — one space, and it is the grammar's own
68
+ * separator rather than the type's. Split from the FRONT, the type reads as the width and the
69
+ * width as the signedness; split from the END, the `a:` form comes out right and the `c:` form
70
+ * runs `Number` over `67109076 <u16*>`, tagging every cast over a numeric base `0xNaN` and
71
+ * collapsing distinct keys onto one label. No shipped table admits a cast base outside
72
+ * `/orderbase`, and `/orderbase` carries `pairings: false`, so no such key reaches this function
73
+ * today — but a candidate LABEL is an identity (`bench diff` and docs/ranked-repro.md compare
74
+ * candidates by it), and one roster line is all that stands between the two. The sibling half of
75
+ * the same hazard is already guarded in `splitHomeBases`, which translates a cast base to no
76
+ * region key and declines. */
77
+ export function homeSplitTag(key: string): string {
78
+ const { leaf, castType, width, signed } = parseBaseKey(key);
79
+ const base = leaf.startsWith('c:') ? `0x${Number(leaf.slice(2)).toString(16)}` : leaf.slice(leaf.indexOf(':') + 1);
80
+ // The cast's element type stays in the token — it is part of the key's identity, since two casts
81
+ // over one symbol are two locals that stride differently. Whitespace is squeezed defensively
82
+ // rather than because any type spells one: a label is one whitespace-free word everywhere it is
83
+ // read, and that has to hold whatever `typeToString` grows.
84
+ const type = castType === null ? '' : `<${castType}>`;
85
+ return `${`${base}${type}`.replace(/\s+/g, '')}.${width}${signed ? 's' : 'u'}`;
86
+ }
87
+
88
+ /** The FUNCTION-level half of the admission: how many keys the caller's table binds on this tree.
89
+ * Nothing about one withheld key, which is why it is decided once (see `homeSplitWithholds`). */
90
+ export interface HomeSplitFanCtx {
91
+ /** how many keys the caller's admission table binds — the pairing needs at least two */
92
+ readonly hoistableKeys: number;
93
+ }
94
+
95
+ /** The two rules that read the tree's KEY COUNT and nothing else, which is why they are asked once
96
+ * per (tree, table) rather than per candidate: inside the pipe they would cost a head hoist, a
97
+ * region plan, a rewrite and a census to report a fact the caller holds before any of it. */
98
+ export const HOMESPLIT_FAN_GATES: readonly Gate<HomeSplitFanCtx>[] = [
99
+ {
100
+ id: 'homesplit-degenerate',
101
+ why: 'withholding the only hoistable key is `/regionbase`, and withholding none is `/livebase-block`',
102
+ sound: false,
103
+ rejects: (c) => c.hoistableKeys < 2,
104
+ },
105
+ {
106
+ id: 'homesplit-fan-cap',
107
+ why: 'one candidate per hoistable key, times the volatile products — the whole cost of the axis',
108
+ sound: false,
109
+ rejects: (c) => c.hoistableKeys > 3,
110
+ },
111
+ ];
112
+
113
+ /** One candidate PAIRING, as the per-key admission rules see it. */
114
+ export interface HomeSplitCtx {
115
+ /** the region rule gives the withheld key two or more locals */
116
+ readonly withheldSplits: boolean;
117
+ /** the withheld key's head home would have been a `/volatile`-qualified local at a DEVICE
118
+ * address, and the piped tree leaves a READ of that base inline */
119
+ readonly inlineDeviceRead: boolean;
120
+ }
121
+
122
+ /** The pairing's PER-KEY admission. NONE is sound, and none is owed a `sound: true`: withholding a
123
+ * key from the head hoist and splitting it per region names the SAME ADDRESS in a different place
124
+ * (`keyOf` folds width and signedness into the key), the two rules that decide MEANING already
125
+ * live in `SCOPEBASE_ELIGIBILITY`, and a plan over a SUBSET of the keys admits nothing the
126
+ * all-keys plan did not. What these rules decide is bytes, fan, and one qualifier.
127
+ *
128
+ * `homesplit-drops-device-volatile` is the one that protects a row rather than the fan.
129
+ * `/volatile` (l3/volatileptr.ts) qualifies MINTED POINTER LOCALS and `/vol-store` (l3/volstore.ts)
130
+ * a STORE at a fixed device address; a device READ left inline is reached by neither. Withholding
131
+ * a key is exactly what can leave one there — the head hoist would have homed it into a local
132
+ * `/volatile` covers — so the pairing declines rather than publish a spelling that silently drops
133
+ * a qualifier the spelling it replaces CARRIED.
134
+ *
135
+ * WHETHER IT CARRIED ONE IS `/volatile`'s OWN QUESTION, so it is asked of that model
136
+ * (`volatileEligibleValue`) rather than re-derived here from the base's node kind or its address.
137
+ * The difference is the arm the benchmark runs on: under a symbol map an absolute pool constant
138
+ * lifts to a `gaddr`, and `/volatile` VETOES a local fed `&gSym` because the symbol map owns a
139
+ * declared global's volatility. On a named base the head home this rule protects is therefore
140
+ * unqualified too — nothing is dropped, and refusing there would delete a spelling to protect a
141
+ * qualifier NEITHER side carries. The address is a second question, asked only of a base the
142
+ * qualifier could have reached. */
143
+ export const HOMESPLIT_GATES: readonly Gate<HomeSplitCtx>[] = [
144
+ {
145
+ id: 'homesplit-no-region',
146
+ why: 'a withheld key the region rule declines to split leaves the spelling the primary carries',
147
+ sound: false,
148
+ rejects: (c) => !c.withheldSplits,
149
+ },
150
+ {
151
+ id: 'homesplit-drops-device-volatile',
152
+ why: 'a device read left inline is qualified by neither /volatile nor /vol-store',
153
+ sound: false,
154
+ rejects: (c) => c.inlineDeviceRead,
155
+ },
156
+ ];
157
+
158
+ /** The keys this tree offers as withholds — one candidate each, or none at all. The caller asks
159
+ * ONCE per (tree, admission table) and loops over the answer.
160
+ *
161
+ * IT IS A KEY-COUNT FACT AND NEVER A SYMBOL-MAP ONE. The keys are not spelled here: they arrive
162
+ * from `l3/basecse.ts`, whose `leafId`/`keyOf` render a leaf base as `c:<const>` wherever it is
163
+ * not a named `a:<sym>`, and `homeSplitTag` above prints that half as `0x…`. (This module's own
164
+ * `leafBaseId`, BELOW, is a different reader — it identifies bases inside
165
+ * `baseReads`/`splitHomeBases` and never produces the argument.) So a tree lifted with NO map
166
+ * reaches this door on plain addresses: enumerated map-less, `EntityHitReaction` in the klonoa
167
+ * `code_1` checkout yields 512 `/homesplit` candidates over 512 distinct sources, keyed
168
+ * `0x3004c20.1u` and `0x40000d4.4s` — TWO numeric keys. "No map, so this product cannot fire" is
169
+ * therefore a fact about whichever function was censused, not about the arm, and a skip built on
170
+ * it deletes live candidates. */
171
+ export function homeSplitWithholds(
172
+ keys: readonly string[],
173
+ admission: readonly Gate<HomeSplitFanCtx>[] = HOMESPLIT_FAN_GATES,
174
+ ): readonly string[] {
175
+ return firstRejection(admission, { hoistableKeys: keys.length }) === null ? keys : [];
176
+ }
177
+
178
+ export interface HomeSplitOpts {
179
+ /** the caller's own admission table — `/livebase-block`'s on the roster row that pairs */
180
+ readonly gates: readonly Gate<BaseKey>[];
181
+ readonly placement: HoistPlacement;
182
+ /** the key withheld from the head hoist, in `l3/basecse.ts` vocabulary */
183
+ readonly key: string;
184
+ readonly deviceRegisters?: readonly [number, number];
185
+ readonly admission?: readonly Gate<HomeSplitCtx>[];
186
+ }
187
+
188
+ /** A leaf deref base's identity, ignoring the access width — `l3/basecse.ts`'s spelling of it,
189
+ * taken from that module rather than re-spelled here, and `null` for every other base kind. */
190
+ const leafBaseId = (b: Expr): string | null => (b.k === 'const' || b.k === 'addr' ? leafId(b) : null);
191
+
192
+ /** Every leaf-based READ in the tree, by base identity — an access reached anywhere but as a
193
+ * store's own lvalue. A store's lvalue is what `/vol-store` can still qualify; nothing else is. */
194
+ function baseReads(body: Stmt[], out: Set<string>): void {
195
+ const visit = (e: Expr): void => {
196
+ if (e.k === 'index') {
197
+ const id = leafBaseId(e.base);
198
+ if (id !== null) {
199
+ out.add(id);
200
+ }
201
+ }
202
+ exprChildren(e).forEach(visit);
203
+ };
204
+ const walk = (s: Stmt): void => {
205
+ for (const e of stmtExprs(s)) {
206
+ // a store's LVALUE is the one position `/vol-store` reaches, so it is not a read
207
+ if (s.k === 'store' && e === s.lval) {
208
+ exprChildren(e).forEach(visit);
209
+ continue;
210
+ }
211
+ visit(e);
212
+ }
213
+ if (s.k === 'for') {
214
+ // `init` and `inc` are STATEMENTS, reached by neither `stmtExprs` nor `stmtLists` — the same
215
+ // walker asymmetry `l3/scopebase.ts`'s `collect` calls out. A read missed here is a device
216
+ // read the rule below cannot see.
217
+ walk(s.init);
218
+ walk(s.inc);
219
+ }
220
+ for (const child of stmtLists(s)) {
221
+ child.forEach(walk);
222
+ }
223
+ };
224
+ body.forEach(walk);
225
+ }
226
+
227
+ /**
228
+ * The pairing for ONE withheld key: the tree with every OTHER admitted base homed at `placement`,
229
+ * and the withheld one split per region. `homed` is the intermediate — the caller re-checks the
230
+ * placement differential across the pipe with it. Null when a rule refuses, or when either half
231
+ * declines.
232
+ */
233
+ export function splitHomeBases(sfn: SFn, opts: HomeSplitOpts): { homed: SFn; split: SFn } | null {
234
+ const gates = opts.admission ?? HOMESPLIT_GATES;
235
+ // `null` only at `placement: 'scope'` (l3/basecse.ts), and no PAIRING roster row sits at that
236
+ // placement today — so this is a guard rather than a path.
237
+ const homed = hoistBaseLocals(sfn, withholdingKey(opts.gates, opts.key), opts.placement);
238
+ if (homed === null) {
239
+ return null;
240
+ }
241
+ // The withheld key in the REGION pass's vocabulary. The two passes key on the same address but
242
+ // spell an `addr` base's identity differently, so the translation is explicit — a string compare
243
+ // across them would silently never match for an `addr` base. A CAST base (an array-of-struct
244
+ // element's `(struct S *)&gSym`) has no spelling in the region pass at all — its `LeafBase` is
245
+ // the leaf kinds only — so it translates to nothing and the pairing declines, which is the same
246
+ // answer the region planner would have given.
247
+ const meta = baseSites(sfn).get(opts.key);
248
+ const scoped = meta && meta.base.k !== 'cast' ? scopedBaseKey(meta.base, meta.width, meta.signed) : null;
249
+ // ONE plan, then its applier — the count below and the rewrite read the same decision rather than
250
+ // two runs of the planner that a future rule could make disagree.
251
+ const plan = planScopedBases(homed, { regions: 'per-region' });
252
+ const split = plan.entries.filter((e) => e.key === scoped).length;
253
+ const out = applyScopedBasePlan(homed, plan);
254
+ // Judged on the SPLIT tree, which is the only one that answers the question: an access the region
255
+ // rule repoints into a minted local is one `/volatile` covers, and on `homed` it is still inline.
256
+ const reads = new Set<string>();
257
+ baseReads((out ?? homed).body, reads);
258
+ const base = meta?.base ?? null;
259
+ const id = base ? leafBaseId(base) : null;
260
+ if (
261
+ firstRejection(gates, {
262
+ withheldSplits: split >= 2,
263
+ inlineDeviceRead:
264
+ id !== null &&
265
+ base !== null &&
266
+ volatileEligibleValue(base) &&
267
+ inRange(addrConst(base), opts.deviceRegisters) &&
268
+ reads.has(id),
269
+ }) !== null
270
+ ) {
271
+ return null;
272
+ }
273
+ if (out === null) {
274
+ if (split >= 2) {
275
+ // `homesplit-no-region` admitted two or more entries for the withheld key, so the plan is
276
+ // neither empty nor compound and the applier cannot decline. Loud rather than silent.
277
+ throw new Error(`homesplit: the region plan splits ${opts.key} ${split} ways and the applier declined`);
278
+ }
279
+ // With that rule ABLATED (`without(HOMESPLIT_GATES, …)`) its premise is gone, and an ablation
280
+ // that converts a decline into a throw prices the rule at every dropped candidate instead of
281
+ // at the spelling it keeps out. A decline is the honest answer on that path.
282
+ return null;
283
+ }
284
+ return { homed, split: out };
285
+ }