@asmlift/core 0.4.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 (87) 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 -164
  5. package/src/backend/cpp.ts +1 -0
  6. package/src/backend/pascal.ts +26 -12
  7. package/src/contracts.ts +341 -22
  8. package/src/declare.ts +41 -4
  9. package/src/frontend/mips.ts +24 -6
  10. package/src/frontend/opaque.ts +31 -18
  11. package/src/frontend/ppc.ts +54 -7
  12. package/src/frontend/ssa.ts +632 -13
  13. package/src/frontend/thumb.ts +2786 -286
  14. package/src/ir/alias.ts +129 -0
  15. package/src/ir/bits.ts +75 -0
  16. package/src/ir/core.ts +337 -2
  17. package/src/ir/opcodes.ts +156 -27
  18. package/src/ir/parse.ts +19 -2
  19. package/src/ir/print.ts +27 -2
  20. package/src/ir/simplify.ts +190 -3
  21. package/src/ir/struct-names.ts +42 -0
  22. package/src/ir/verify.ts +43 -49
  23. package/src/l3/address.ts +62 -0
  24. package/src/l3/argbase.ts +8 -2
  25. package/src/l3/ast.ts +464 -49
  26. package/src/l3/basecse.ts +709 -88
  27. package/src/l3/coalesce.ts +521 -66
  28. package/src/l3/dce.ts +54 -19
  29. package/src/l3/gates.ts +88 -0
  30. package/src/l3/hoist.ts +293 -14
  31. package/src/l3/homesplit.ts +285 -0
  32. package/src/l3/initfirst.ts +301 -0
  33. package/src/l3/inlinebase.ts +193 -0
  34. package/src/l3/mentions.ts +113 -0
  35. package/src/l3/mulfirst.ts +42 -0
  36. package/src/l3/nearbase.ts +152 -0
  37. package/src/l3/offmember.ts +371 -0
  38. package/src/l3/parkfirst.ts +96 -0
  39. package/src/l3/pollguard.ts +154 -0
  40. package/src/l3/ptrfield.ts +227 -0
  41. package/src/l3/regspell.ts +110 -85
  42. package/src/l3/reindex.ts +715 -78
  43. package/src/l3/scopebase.ts +649 -219
  44. package/src/l3/sinkinit.ts +40 -0
  45. package/src/l3/slotorder.ts +123 -0
  46. package/src/l3/storage.ts +48 -0
  47. package/src/l3/symbol-refs.ts +41 -8
  48. package/src/l3/tailmerge.ts +23 -4
  49. package/src/l3/typing.ts +198 -9
  50. package/src/l3/unmerge.ts +263 -0
  51. package/src/l3/unreduce.ts +971 -0
  52. package/src/l3/volatileptr.ts +207 -0
  53. package/src/l3/volatileval.ts +130 -0
  54. package/src/l3/volstore.ts +229 -0
  55. package/src/l3/zerosub.ts +62 -0
  56. package/src/pattern/engine.ts +236 -13
  57. package/src/pipeline.ts +206 -49
  58. package/src/proto.ts +112 -14
  59. package/src/raise/arrays.ts +6 -1
  60. package/src/raise/divpow2.ts +4 -3
  61. package/src/raise/globalshape.ts +1038 -0
  62. package/src/raise/gvn.ts +44 -19
  63. package/src/raise/latch.ts +126 -0
  64. package/src/raise/memberarrays.ts +594 -0
  65. package/src/raise/narrow.ts +124 -0
  66. package/src/raise/narrowlocal.ts +556 -0
  67. package/src/raise/paramwidth.ts +179 -0
  68. package/src/raise/pre-recovery.ts +101 -16
  69. package/src/raise/recover.ts +56 -23
  70. package/src/raise/retsink.ts +215 -14
  71. package/src/raise/shortcircuit.ts +477 -79
  72. package/src/raise/struct-arrays.ts +21 -3
  73. package/src/raise/structs.ts +61 -3
  74. package/src/rank-axes.ts +630 -0
  75. package/src/rank-declare.ts +256 -0
  76. package/src/rank.ts +1726 -251
  77. package/src/structure/analysis.ts +1516 -220
  78. package/src/structure/bitfields.ts +332 -0
  79. package/src/structure/globalaccess.ts +274 -0
  80. package/src/structure/hazards.ts +411 -20
  81. package/src/structure/loops.ts +2 -49
  82. package/src/structure/namecoalesce.ts +435 -0
  83. package/src/structure/structure.ts +2850 -533
  84. package/src/structure/switch-recover.ts +688 -147
  85. package/src/symbols.ts +62 -1
  86. package/src/target.ts +367 -24
  87. package/src/trace.ts +111 -32
@@ -1,11 +1,29 @@
1
1
  // asmlift structurer — the ANALYSIS phase. Pure derivation over the lifted fn — nothing here
2
2
  // mutates the IR or depends on naming/emission state:
3
3
  // • use-site registry — every use of a value, POSITIONED (op + block + index);
4
- // • per-block SSA value liveness (backward dataflow) — consumed by the coalescing
5
- // interference check in structure.ts;
6
- // • the effect-ordering model — which call/load defs must MATERIALIZE as named temps at
7
- // their own program position instead of inlining at their use.
8
- import { Block, Fn, Op, Value, successorsOf } from '../ir/core';
4
+ // • per-block SSA value liveness (backward dataflow) — consumed by structure.ts and
5
+ // structure/namecoalesce.ts;
6
+ // • the effect-ordering model — which defs must MATERIALIZE as named temps at their own
7
+ // program position instead of inlining at their use (calls/loads for effect order, plus
8
+ // the pure defs the homing rules claim);
9
+ // • the HOMING-AXIS ENUMERATION GATES — one export per candidate axis, each answering "does
10
+ // this function hold a value the axis would home at all" so rank.ts can skip an axis whose
11
+ // candidate would only duplicate the default. Each mirrors its axis's scope inside `analyze`
12
+ // and states where it DIVERGES from it, in which direction, and what that costs.
13
+ import { disjointConstSlots, globalCellOf, mayWriteGlobal } from '../ir/alias';
14
+ import {
15
+ Block,
16
+ Fn,
17
+ Op,
18
+ Successor,
19
+ Value,
20
+ defOpMap,
21
+ dominators,
22
+ mergeClasses,
23
+ predecessors,
24
+ successorsOf,
25
+ } from '../ir/core';
26
+ import { EFFECTFUL_OPS, ORDER_SENSITIVE_OPS, REEVAL_UNSAFE_OPS } from '../ir/opcodes';
9
27
 
10
28
  export interface UseSite {
11
29
  blk: Block;
@@ -13,6 +31,635 @@ export interface UseSite {
13
31
  op: Op;
14
32
  }
15
33
 
34
+ /** the ops whose operands[0] is a memory-access BASE — the address-home axis's slot model */
35
+ const MEM_BASE_OPS = new Set(['load', 'store', 'aload', 'astore']);
36
+
37
+ /** Is the op's own value an ADDRESS — a pointer or array whose standalone rendering must carry a
38
+ * cast? Homed, `add(p, 8)` renders `(u16 *)(gPtr + 8)`: the cast lands outside the sum, so a byte
39
+ * offset becomes element arithmetic and the address moves. The VALUE-side counterpart of
40
+ * `coneHoldsAddr`, which is a different question rather than a weaker one — that walk crosses
41
+ * reads, so a rule whose clientele IS values over a load cannot ask it, and a pointer loaded from
42
+ * memory has no gaddr of its own for it to find. Each caller's refusal says which half it buys. */
43
+ function rendersAsAddress(op: Op): boolean {
44
+ const t = op.results[0]?.type;
45
+ return t?.kind === 'ptr' || t?.kind === 'array';
46
+ }
47
+
48
+ /** Values C evaluates only under a `&&`/`||`: the SECOND operand of every `logic_and`/`logic_or`
49
+ * and its transitive operand cone. raise/shortcircuit.ts lifts that cone into the block ABOVE the
50
+ * branch on the contract that the structurer inlines it back under C's own short circuit, so the
51
+ * def block of anything in it is a FOLD ARTIFACT — a rule that names one of these values there
52
+ * emits it above the guard the source wrote (`p != 0 && *p != 0` becoming `v0 = *p;` above its own
53
+ * null check). Asked by the def-block placement rule and by the merge-feed-home scope. */
54
+ function shortCircuitGuardedValues(fn: Fn, defOf: Map<Value, Op>): Set<Value> {
55
+ const guarded = new Set<Value>();
56
+ const work: Value[] = [];
57
+ for (const b of fn.blocks) {
58
+ for (const op of b.ops) {
59
+ const rhs = op.opcode === 'logic_and' || op.opcode === 'logic_or' ? op.operands[1] : undefined;
60
+ if (rhs !== undefined) {
61
+ work.push(rhs);
62
+ }
63
+ }
64
+ }
65
+ while (work.length) {
66
+ const v = work.pop()!;
67
+ if (!guarded.has(v)) {
68
+ guarded.add(v);
69
+ work.push(...(defOf.get(v)?.operands ?? []));
70
+ }
71
+ }
72
+ return guarded;
73
+ }
74
+
75
+ /** Any gaddr/laddr in the op's operand cone (the op included). Rendered standalone, an address
76
+ * computation over one loses the memAccess's inline byte-stride cast — the value changes, so a
77
+ * homing rule asking this refuses the cone (the cast-aware machinery in l3/basecse.ts,
78
+ * scopebase.ts and nearbase.ts serves those bases instead). The walk deliberately crosses loads —
79
+ * a gaddr reachable only through a load's address keeps its cast at that load's own deref, so
80
+ * over-refusal there costs a candidate, never soundness. That over-refusal is why the
81
+ * derived-read-home axis asks its own pair instead (an address in the cone OUTSIDE a read, plus
82
+ * `rendersAsAddress` on the value): reads over named globals are its whole clientele. */
83
+ function coneHoldsAddr(op0: Op, defOf: Map<Value, Op>): boolean {
84
+ const seen = new Set<Value>();
85
+ const cone = [op0];
86
+ while (cone.length) {
87
+ const d = cone.pop()!;
88
+ if (d.opcode === 'gaddr' || d.opcode === 'laddr') {
89
+ return true;
90
+ }
91
+ for (const x of d.operands) {
92
+ if (!seen.has(x)) {
93
+ seen.add(x);
94
+ const dd = defOf.get(x);
95
+ if (dd) {
96
+ cone.push(dd);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ return false;
102
+ }
103
+
104
+ /** THE ADDRESS-HOME AXIS'S SCOPE: every value whose MERGE CLASS (ir/core.ts `mergeClasses`) is
105
+ * used only as the base of memory accesses, and at 2+ of them.
106
+ *
107
+ * WHY THE CLASS AND NOT THE VALUE. The question the axis asks is about a REGISTER — did the
108
+ * machine derive one address and dereference it at several sites — and a register that survives a
109
+ * branch merge is spelled in functional-form SSA as an edge argument plus a block parameter. So a
110
+ * base each arm derives and the join then reads is N+1 SSA values with one base use apiece, none
111
+ * of which reaches the 2-access threshold, while the register it describes reaches N+1 of them.
112
+ * Counting per value also mis-reads the edge itself: the terminator that carries the argument is
113
+ * a consumer that is not a memory access, so the per-value rule refuses on the very edge that
114
+ * makes the base shared.
115
+ *
116
+ * An edge argument is therefore NOT a use that leaves the class — it feeds the parameter beside
117
+ * it, which `mergeClasses` has already unioned in. Everything else still disqualifies the whole
118
+ * class: a store's value slot, an `aload` index, arithmetic. The home is justified by the
119
+ * shared-base reuse alone, as it always was.
120
+ *
121
+ * `ignoreRet` skips `ret` operands: `analyze` passes its own `returnsVoid` (where a ret operand
122
+ * is a phantom the use registry already drops), and rank.ts's enumeration gate passes true
123
+ * unconditionally, because it cannot know — see `hasHomeableSharedAddress`.
124
+ *
125
+ * Block PARAMETERS are members like any other and can qualify here. Neither caller homes one —
126
+ * both filter by a DEF — but they must be counted, or the join half of every class is invisible.
127
+ *
128
+ * IT IS NOT A SUPERSET OF THE PER-VALUE RULE IT REPLACED, and that is the price rather than a
129
+ * bug: a value whose CLASS MATE escapes is now refused where counting the value alone admitted
130
+ * it. Measured by running both predicates over every function in the four checkouts — 1487
131
+ * lifting functions, both symbol-map configurations — the widening admits new values in 25
132
+ * functions map-less and 8 map-ful, and REMOVES exactly one value from each of four functions
133
+ * map-less (kleod `sub_0804EB64`, marioparty3 `func_8010E344_25A994_rockin_raceway`,
134
+ * snowboardkids2 `func_8006FDA0_709A0` and `func_8006FDC8_709C8`), none map-ful. The function-
135
+ * level ENUMERATION gate is a clean superset over the same corpus, which is why a census taken
136
+ * at that scope reports no loss; this is the finer one.
137
+ *
138
+ * NO LOOP-HEADER REFUSAL OF ITS OWN, AND THE REASON IS A GUARD THAT WAS ALREADY THERE. The
139
+ * scope's plan mandated one — refuse a class reaching a loop-header PARAMETER, because
140
+ * `structure.ts`'s `carriesPreUpdate` makes a loop variable's name denote different values at
141
+ * different points. Two things are true and only together do they answer it.
142
+ *
143
+ * The FIRST is about which classes the widening adds. Of the 25+8 functions above exactly one
144
+ * carries a class reaching a loop-header parameter (marioparty3
145
+ * `func_80112508_523648_filesel`, 2 values, map-less), and neither value is one the axis could
146
+ * materialize; `addr-home.test.ts` pins both halves. A loop-carried pointer INDUCTION is refused
147
+ * by its own increment, a non-base use of a class member. The loop-header class that does survive
148
+ * has a back-edge value READ FROM MEMORY, so its only def is a `load` and the enumeration gate
149
+ * excludes it. So the widening adds no loop-header home, and the planned guard has no inhabitant
150
+ * among the values it would have been written for.
151
+ *
152
+ * The SECOND is what stands there whatever the scope rule says, and it is NOT one of those two:
153
+ * the third scope's own `!multiBlockHeaders.has(b)` seat refusal, which predates this widening
154
+ * and refuses to materialize AT a multi-block loop header regardless of which class the value is
155
+ * in. It is load-bearing and measurable: replace that clause with `true` and marioparty3
156
+ * `func_8010923C_18E46C_cosmic_coaster` stops structuring at all — it throws the
157
+ * `carriesPreUpdate` StructureError this paragraph is about — while `func_80033910_34510` and
158
+ * `func_80033970_34570` go from axis-inert to changing their source. So the hazard is real; it is
159
+ * answered by WHERE a home may sit rather than by WHICH class may have one, which is a refusal
160
+ * the widening does not touch and the plan's class guard would have restated. Note what that
161
+ * implies about the enumeration gate: it deliberately
162
+ * omits the seat refusal (see `hasHomeableSharedAddress`), which is safe only because the seat
163
+ * refusal is applied HERE, in the scope, on every candidate the gate enumerates. */
164
+ export function sharedBaseClasses(fn: Fn, ignoreRet: boolean): Set<Value> {
165
+ const classes = mergeClasses(fn);
166
+ const baseUses = new Map<Value, Set<Op>>();
167
+ const otherUse = new Set<Value>();
168
+ for (const b of fn.blocks) {
169
+ for (const op of b.ops) {
170
+ if (ignoreRet && op.opcode === 'ret') {
171
+ continue;
172
+ }
173
+ op.operands.forEach((o, i) => {
174
+ // BASE SLOT ONLY. `store p, p` — the address written as its own data — needs no clause
175
+ // here and had one: the j>0 pass over the SAME operand list puts `p` into `otherUse`
176
+ // regardless, and `otherUse` disqualifies the whole class below, so a base-slot entry for
177
+ // an escaping value can never be read. Measured before removing it: over 1487 lifted
178
+ // corpus functions the shape occurs at 10 sites and the predicate's output is identical
179
+ // with the clause and without it, in both `ignoreRet` senses. What keeps the escape out is
180
+ // therefore the `otherUse` sweep, and that is what `analysis.test.ts` pins — a clause that
181
+ // cannot change an answer is not a guard, it is a claim that one exists.
182
+ if (i === 0 && MEM_BASE_OPS.has(op.opcode)) {
183
+ (baseUses.get(o) ?? baseUses.set(o, new Set()).get(o)!).add(op);
184
+ } else {
185
+ otherUse.add(o);
186
+ }
187
+ });
188
+ for (const s of op.successors) {
189
+ s.args.forEach((a, i) => {
190
+ // Class-internal only up to the parameter list: an argument past the end binds nothing,
191
+ // so `mergeClasses` never unioned it and it escapes like any other use.
192
+ if (i >= s.block.params.length) {
193
+ otherUse.add(a);
194
+ }
195
+ });
196
+ }
197
+ }
198
+ }
199
+ const out = new Set<Value>();
200
+ for (const b of fn.blocks) {
201
+ for (const v of [...b.params, ...b.ops.flatMap((op) => op.results)]) {
202
+ const members = classes.get(v) ?? [v];
203
+ if (members.some((m) => otherUse.has(m))) {
204
+ continue;
205
+ }
206
+ const consumers = new Set<Op>();
207
+ for (const m of members) {
208
+ for (const c of baseUses.get(m) ?? []) {
209
+ consumers.add(c);
210
+ }
211
+ }
212
+ if (consumers.size >= 2) {
213
+ out.add(v);
214
+ }
215
+ }
216
+ }
217
+ return out;
218
+ }
219
+
220
+ /** Is `d` a def one of the homing axes could seat in a local — a def at all, and a PURE
221
+ * non-memory one that is not a `const`? The three enumeration gates below share this filter and
222
+ * each then adds its own cone/address/shape refusals.
223
+ *
224
+ * Named for what it tests rather than for the shape it excludes: a `const` IS a pure non-memory
225
+ * def, and it is out because a re-derived const is re-materialization — the compiler's own
226
+ * behaviour — not because it computes anything a home would preserve. */
227
+ function isHomeableDef(d: Op | undefined): d is Op {
228
+ return !!d && d.opcode !== 'const' && d.opcode !== 'call' && d.opcode !== 'load' && d.opcode !== 'aload';
229
+ }
230
+
231
+ /** THE READ CONE of a pure def: the `load`/`aload` defs its operand tree stands on. The walk stops
232
+ * AT a read (a read's own address computation is the read's business, not this walk's) and
233
+ * REFUSES — null — as soon as the cone holds a `call`, whose re-render would re-execute it, or a
234
+ * `gaddr`/`laddr`, whose standalone rendering loses the memAccess's inline byte-stride cast.
235
+ *
236
+ * Both callers gate `load`/`aload`/`call` out of `op0` itself before asking, and neither reads the
237
+ * order the reads come back in — one takes `length`/`every`, the other builds a `Set`. */
238
+ function readCone(op0: Op, defOf: Map<Value, Op>): Op[] | null {
239
+ const reads: Op[] = [];
240
+ const seen = new Set<Value>();
241
+ const cone = [op0];
242
+ while (cone.length) {
243
+ const d = cone.pop()!;
244
+ if (d.opcode === 'load' || d.opcode === 'aload') {
245
+ reads.push(d);
246
+ continue;
247
+ }
248
+ if (d.opcode === 'call' || d.opcode === 'gaddr' || d.opcode === 'laddr') {
249
+ return null;
250
+ }
251
+ for (const x of d.operands) {
252
+ if (!seen.has(x)) {
253
+ seen.add(x);
254
+ const dd = defOf.get(x);
255
+ if (dd) {
256
+ cone.push(dd);
257
+ }
258
+ }
259
+ }
260
+ }
261
+ return reads;
262
+ }
263
+
264
+ /** rank.ts's enumeration gate for the `/addr-home` axis: does the function HAVE a value the axis
265
+ * would home — a non-const pure def whose merge class is a shared base, with no gaddr/laddr in
266
+ * its cone? Mirrors the axis's scope rule in `analyze` (the same `sharedBaseClasses` call), minus
267
+ * the loop-header seat refusal (that needs the loop model; a false positive costs one
268
+ * duplicate-collapsed candidate, never a wrong one).
269
+ *
270
+ * `ignoreRet` is true here: a `ret` operand may be a void phantom, which `analyze` skips under
271
+ * `returnsVoid` and this gate cannot know. For a genuinely returned base the axis's own rule
272
+ * still refuses, costing one duplicate-collapsed candidate — the same trade as the loop-header
273
+ * divergence. */
274
+ export function hasHomeableSharedAddress(fn: Fn): boolean {
275
+ const defOf = defOpMap(fn);
276
+ for (const v of sharedBaseClasses(fn, true)) {
277
+ const d = defOf.get(v);
278
+ if (isHomeableDef(d) && !coneHoldsAddr(d, defOf)) {
279
+ return true;
280
+ }
281
+ }
282
+ return false;
283
+ }
284
+
285
+ /** rank.ts's enumeration gate for the `/expr-home` axis: does the function HAVE a value the
286
+ * axis would home — a pure non-const def with 2+ distinct consumers, at least one of them inside
287
+ * a loop the def sits outside, cone-free? Loops here are LAYOUT ranges (a successor at an
288
+ * equal-or-earlier block position closes one) where the axis's own rule uses the dominator model,
289
+ * and consumers here come from op operands only, where the rule counts `useSitesOf` and so counts
290
+ * branch args too — unlike hasHomeableSharedAddress this therefore diverges in BOTH directions. A
291
+ * false positive costs one duplicate-collapsed candidate. A false negative silently skips the arm:
292
+ * on IR whose block layout does not follow dominance, which every frontend avoids by laying blocks
293
+ * out in address order (a natural loop's back edge points backward), and on a value EITHER of
294
+ * whose two consumers is a branch arg, which the rule would home and this never enumerates. The
295
+ * second is unwitnessed over the 856-row bench the axis was measured on (#97), and costs a
296
+ * missing candidate, never a wrong one. */
297
+ export function hasLoopSharedPureValue(fn: Fn): boolean {
298
+ const defOf = defOpMap(fn);
299
+ const pos = new Map<Block, number>(fn.blocks.map((b, i) => [b, i]));
300
+ const ranges: [number, number][] = [];
301
+ for (const b of fn.blocks) {
302
+ for (const sx of successorsOf(b)) {
303
+ if (pos.get(sx)! <= pos.get(b)!) {
304
+ ranges.push([pos.get(sx)!, pos.get(b)!]);
305
+ }
306
+ }
307
+ }
308
+ if (ranges.length === 0) {
309
+ return false;
310
+ }
311
+ const consumers = new Map<Value, Set<Op>>();
312
+ const opPos = new Map<Op, number>();
313
+ for (const b of fn.blocks) {
314
+ for (const op of b.ops) {
315
+ opPos.set(op, pos.get(b)!);
316
+ for (const o of op.operands) {
317
+ (consumers.get(o) ?? consumers.set(o, new Set()).get(o)!).add(op);
318
+ }
319
+ }
320
+ }
321
+ for (const [v, cs] of consumers) {
322
+ const d = defOf.get(v);
323
+ if (!isHomeableDef(d)) {
324
+ continue;
325
+ }
326
+ const dp = opPos.get(d)!;
327
+ if (
328
+ cs.size >= 2 &&
329
+ ranges.some(
330
+ ([lo, hi]) => (dp < lo || dp > hi) && [...cs].some((c) => opPos.get(c)! >= lo && opPos.get(c)! <= hi),
331
+ ) &&
332
+ !coneHoldsAddr(d, defOf)
333
+ ) {
334
+ return true;
335
+ }
336
+ }
337
+ return false;
338
+ }
339
+
340
+ /** rank.ts's enumeration gate for the `/derived-home` axis: does the function HAVE a value the
341
+ * axis would home — a pure non-const, non-pointer def with 2+ consumers standing on a same-block
342
+ * memory read that is used nowhere else and reaches it with no write in between, and with no call
343
+ * or standalone address in the cone? A TRUE here DOUBLES the whole structuring cross for the
344
+ * function — not one candidate — so every refusal cheap enough to state without the positioned
345
+ * model is mirrored here; only the loop-header seat stays out.
346
+ *
347
+ * Diverges in BOTH directions, like `hasLoopSharedPureValue` and unlike `hasHomeableSharedAddress`.
348
+ * Over: the write scan is straight-line within the one block, where the rule's is cycle-aware, so
349
+ * a write reaching only around a back edge is invisible here — a false positive costs a doubled
350
+ * cross whose every candidate the source dedup then collapses. Under: use counting here is by SLOT
351
+ * over operands and successor args, where `analyze` drops a void function's `ret` operand — so a
352
+ * read whose second use is a suppressed return is refused here and admitted there, silently
353
+ * skipping the arm. That shape is a void function returning the very halfword it read, which no
354
+ * caller can observe; the axis's clientele reads to compute, not to return. */
355
+ export function hasDerivedReadHome(fn: Fn): boolean {
356
+ const defOf = defOpMap(fn);
357
+ const consumers = new Map<Value, Set<Op>>();
358
+ const useSlots = new Map<Value, number>();
359
+ const blockOf = new Map<Op, Block>();
360
+ const idxOf = new Map<Op, number>();
361
+ for (const b of fn.blocks) {
362
+ b.ops.forEach((op, i) => {
363
+ blockOf.set(op, b);
364
+ idxOf.set(op, i);
365
+ const use = (v: Value) => {
366
+ (consumers.get(v) ?? consumers.set(v, new Set()).get(v)!).add(op);
367
+ useSlots.set(v, (useSlots.get(v) ?? 0) + 1);
368
+ };
369
+ for (const o of op.operands) {
370
+ use(o);
371
+ }
372
+ for (const s of op.successors) {
373
+ for (const a of s.args) {
374
+ use(a);
375
+ }
376
+ }
377
+ });
378
+ }
379
+ /** any op that writes memory strictly between two ops of one block — the rule's `memWriteBetween`
380
+ * over the straight line the same-block requirement already pins */
381
+ const writeBetween = (b: Block, lo: number, hi: number): boolean =>
382
+ b.ops.slice(lo + 1, hi).some((x) => EFFECTFUL_OPS.has(x.opcode));
383
+ const standsOnRead = (op0: Op): boolean => {
384
+ const reads = readCone(op0, defOf);
385
+ if (reads === null) {
386
+ return false;
387
+ }
388
+ const b = blockOf.get(op0)!;
389
+ return (
390
+ reads.length > 0 &&
391
+ reads.every(
392
+ (r) =>
393
+ blockOf.get(r) === b &&
394
+ (useSlots.get(r.results[0]) ?? 0) === 1 &&
395
+ !writeBetween(b, idxOf.get(r)!, idxOf.get(op0)!),
396
+ )
397
+ );
398
+ };
399
+ for (const [v, cs] of consumers) {
400
+ const d = defOf.get(v);
401
+ if (cs.size >= 2 && isHomeableDef(d) && !rendersAsAddress(d) && standsOnRead(d)) {
402
+ return true;
403
+ }
404
+ }
405
+ return false;
406
+ }
407
+
408
+ /** Natural loops: a back edge is `latch → header` with the header dominating the latch, and the
409
+ * body is the backward closure from the latch. Shared by the rules inside `analyze` and by the
410
+ * `/merge-home` gate below, so the two cannot disagree about what "inside a loop" means. */
411
+ function naturalLoops(
412
+ fn: Fn,
413
+ dom: Map<Block, Set<Block>>,
414
+ predsOf: Map<Block, Block[]>,
415
+ ): { header: Block; body: Set<Block> }[] {
416
+ const loops: { header: Block; body: Set<Block> }[] = [];
417
+ for (const latch of fn.blocks) {
418
+ for (const header of successorsOf(latch)) {
419
+ if (!dom.get(latch)?.has(header)) {
420
+ continue;
421
+ }
422
+ const body = new Set<Block>([header]);
423
+ const work = [latch];
424
+ while (work.length) {
425
+ const x = work.pop()!;
426
+ if (!body.has(x)) {
427
+ body.add(x);
428
+ work.push(...(predsOf.get(x) ?? []));
429
+ }
430
+ }
431
+ loops.push({ header, body });
432
+ }
433
+ }
434
+ return loops;
435
+ }
436
+
437
+ /** THE MERGE-FEED-HOME axis's scope (rank.ts `/merge-home`, AnalyzeOptions.homeMergeFeeds): the
438
+ * pure defs it materializes.
439
+ *
440
+ * A merge parameter whose incoming edges render ONE value's expression twice or more is a value
441
+ * the source computed once ABOVE the branch and the copy machinery then sank into every arm —
442
+ * `s32 m = (b & 1) ? 0x400 : 0;` becomes the whole `neg/orr/asr #31/and` chain in each arm, which
443
+ * agbcc if-converts per arm instead of holding the value in a register across the branch. Homed at
444
+ * the def, it renders once and the arms read the name.
445
+ *
446
+ * Neither the value's use count nor its multi-render alone is the evidence: the sibling scopes'
447
+ * clientele (a value re-derived at two ordinary uses) is a value the compiler DOES re-materialize
448
+ * for free. What a merge slot adds is that the two renders are mutually exclusive ARMS of one
449
+ * branch. Which side the source spelled is still not derivable (nothing stops a source from
450
+ * writing the expression twice), so this is a differ-refereed candidate axis, never a default.
451
+ *
452
+ * Refusals:
453
+ * • a value whose cone holds a gaddr/laddr (`coneHoldsAddr`) — rendered standalone an `&g + i`
454
+ * loses the memAccess's inline byte-stride cast, the same soundness half the sibling scopes
455
+ * state.
456
+ * • a value that is ITSELF an address (`rendersAsAddress`). A SCOPE boundary rather than that
457
+ * same hazard: what it adds over `coneHoldsAddr` is the pointers with no gaddr/laddr anywhere
458
+ * in their cone — derived from, or loaded from, a pointer param — and there the backend does
459
+ * re-derive the byte cast (`v0 = (u8 *)*a1 + 6;` then `v0 = (u8 *)v0 + 2;`). Address-shaped
460
+ * bases belong to the cast-aware machinery in l3/basecse.ts, scopebase.ts and nearbase.ts;
461
+ * this axis does not offer a second spelling of them.
462
+ * • an op whose answer depends on WHERE it runs, or that can TRAP — `REEVAL_UNSAFE_OPS`, read
463
+ * from the registry rather than re-listed. Both halves carry: for a read WHERE it happens is
464
+ * the read rules' question, and a homed divide becomes an unconditional statement at a def
465
+ * block raise/shortcircuit.ts may have made, on paths C's own `&&` would have re-guarded —
466
+ * the KNOWN GAP `ir/opcodes.ts` books against `HOIST_UNSAFE_OPS`.
467
+ * • an `undef` — the axis's premise is a value the source COMPUTED once above the branch, and
468
+ * an uninitialised register was never computed at all: homed, it spells `v0 = uninit_r5;`,
469
+ * a copy of a value nothing wrote, which no asm can have.
470
+ * • a value in a `&&`/`||`'s guarded cone WHOSE CONE HOLDS a re-evaluation-unsafe op —
471
+ * raise/shortcircuit.ts put that cone above the branch on the contract that the structurer
472
+ * inlines it back under C's own short circuit, so its def block is a FOLD ARTIFACT rather than
473
+ * the block the asm computed in. Naming it there emits `v0 = *p | 1;` above `p != 0`, and
474
+ * `v0 = a2 / a0 | 1;` above the `a0 != 0` the source divided under — the trap half is the one
475
+ * that turns a re-spelling into a fault. Narrowed to that cone deliberately: a PURE guarded
476
+ * value re-spelled above the connective computes the same thing on the same paths, and
477
+ * refusing it outright costs `synthetic:modpow2:ido7.1` 4 → 6 for no soundness gain.
478
+ * • a def block or a join INSIDE A LOOP. A loop-carried merge parameter's "definition above the
479
+ * branch" is the loop's entry initializer, whose placement `/defsite/loop-entry` already
480
+ * decides; homing it here would answer the same question a second time, from a rule that
481
+ * cannot see the loop's kept guard. It has NO corpus reach — the gate admits the same 16 rows
482
+ * with it on and off, in both symbol-map configurations — so what it buys is fan on
483
+ * loop-shaped functions the corpus does not carry. klonoa's LoadBGTilemapData (89 blocks, 25
484
+ * joins with params) is refused by this clause and no other, and lifting it takes that
485
+ * function's map-less enumeration 75264 → 150528 candidates, 102s → 207s. A null there is
486
+ * this refusal, not an absent idiom.
487
+ * The `analyze` scope adds nothing to this list — the whole predicate is here, so the axis's
488
+ * enumeration gate can run it rather than approximate it. */
489
+ function mergeFeedHomes(fn: Fn, dom: Map<Block, Set<Block>>, defOf: Map<Value, Op>, inLoop: Set<Block>): Set<Op> {
490
+ // Every block's incoming COPY SITES — the places its edge assignments render, each once. Neither
491
+ // the predecessor list nor the raw edge list: `predecessors` (ir/core.ts) lists a block once per
492
+ // successor EDGE, so walking it against that block's own successors visits a join two of one
493
+ // block's edges reach k² times, and a value carried on ONE of them then tallies 2.
494
+ //
495
+ // The shape to follow is structure.ts's Regime B: it groups the `switch_br`'s CASE slots by
496
+ // target block (two naming one block are ONE arm carrying both `case` labels, args required to
497
+ // agree), then emits the DEFAULT edge as an entry of its own with its own copies — so a block a
498
+ // case slot and the default both name renders them TWICE. A `cond_br`'s two arms each emit their
499
+ // own even when both name the join. Over-counting a site costs a candidate that homes a value
500
+ // rendered once, which loses on score; under-counting costs the candidate outright.
501
+ const copySitesOf = new Map<Block, Successor[]>();
502
+ const addSite = (sx: Successor): void => {
503
+ const at = copySitesOf.get(sx.block);
504
+ if (at) {
505
+ at.push(sx);
506
+ } else {
507
+ copySitesOf.set(sx.block, [sx]);
508
+ }
509
+ };
510
+ for (const b of fn.blocks) {
511
+ const term = b.ops[b.ops.length - 1];
512
+ const succ = term?.successors ?? [];
513
+ if (term?.opcode === 'switch_br' && succ.length > 0) {
514
+ const seen = new Set<Block>();
515
+ for (const sx of succ.slice(0, -1)) {
516
+ if (!seen.has(sx.block)) {
517
+ seen.add(sx.block);
518
+ addSite(sx);
519
+ }
520
+ }
521
+ addSite(succ[succ.length - 1]!);
522
+ } else {
523
+ for (const sx of succ) {
524
+ addSite(sx);
525
+ }
526
+ }
527
+ }
528
+ const joins = fn.blocks.filter(
529
+ (m) => m.params.length > 0 && (copySitesOf.get(m)?.length ?? 0) >= 2 && !inLoop.has(m),
530
+ );
531
+ if (joins.length === 0) {
532
+ return new Set<Op>();
533
+ }
534
+ const blockOf = new Map<Op, Block>();
535
+ for (const b of fn.blocks) {
536
+ for (const op of b.ops) {
537
+ blockOf.set(op, b);
538
+ }
539
+ }
540
+ // Every value an edge ARGUMENT renders — the argument itself plus its inlined operand cone,
541
+ // memoized per value so one walk serves every slot. The walk stops DESCENDING at an
542
+ // order-sensitive def: under a call or a memory read the value renders at that op's own position,
543
+ // never at this edge. It crosses a trapping divide, which nothing materializes — that renders
544
+ // inline at the copy site and its operands render there with it. The stopping op is still
545
+ // recorded, so a membership test over the cone sees it.
546
+ const coneCache = new Map<Value, Set<Value>>();
547
+ const coneOf = (root: Value): Set<Value> => {
548
+ const hit = coneCache.get(root);
549
+ if (hit) {
550
+ return hit;
551
+ }
552
+ const acc = new Set<Value>();
553
+ const stack = [root];
554
+ while (stack.length) {
555
+ const x = stack.pop()!;
556
+ if (acc.has(x)) {
557
+ continue;
558
+ }
559
+ acc.add(x);
560
+ const memo = coneCache.get(x);
561
+ if (memo) {
562
+ for (const y of memo) {
563
+ acc.add(y);
564
+ }
565
+ continue;
566
+ }
567
+ const d = defOf.get(x);
568
+ if (d && !ORDER_SENSITIVE_OPS.has(d.opcode)) {
569
+ stack.push(...d.operands);
570
+ }
571
+ }
572
+ coneCache.set(root, acc);
573
+ return acc;
574
+ };
575
+ const scGuarded = shortCircuitGuardedValues(fn, defOf);
576
+ /** Does anything in the value's cone answer differently, or trap, at another program point? The
577
+ * cone renders INSIDE the home, so both halves move with it — a read answers whichever stores
578
+ * ran before it, and a divide that only ever ran under a guard divides by zero above it. */
579
+ const coneHoldsReevalUnsafe = (v: Value): boolean =>
580
+ [...coneOf(v)].some((x) => {
581
+ const d = defOf.get(x);
582
+ return d !== undefined && REEVAL_UNSAFE_OPS.has(d.opcode);
583
+ });
584
+ /** may this op's result be materialized at its def — and is this axis the one to do it? */
585
+ const eligible = (op: Op): boolean => {
586
+ const v = op.results[0];
587
+ return (
588
+ v !== undefined &&
589
+ !REEVAL_UNSAFE_OPS.has(op.opcode) &&
590
+ op.opcode !== 'undef' &&
591
+ !(scGuarded.has(v) && coneHoldsReevalUnsafe(v)) &&
592
+ !rendersAsAddress(op) &&
593
+ !coneHoldsAddr(op, defOf)
594
+ );
595
+ };
596
+ const out = new Set<Op>();
597
+ for (const m of joins) {
598
+ for (let i = 0; i < m.params.length; i++) {
599
+ const tally = new Map<Value, number>();
600
+ const carried = new Set<Value>();
601
+ for (const sx of copySitesOf.get(m)!) {
602
+ const a = sx.args[i];
603
+ if (a === undefined) {
604
+ continue;
605
+ }
606
+ carried.add(a);
607
+ for (const v of coneOf(a)) {
608
+ tally.set(v, (tally.get(v) ?? 0) + 1);
609
+ }
610
+ }
611
+ // The slot's feeders: rendered from 2+ of its edges, CARRIED unchanged by at least one of
612
+ // them, by a def this join's every arm reaches.
613
+ //
614
+ // Both counts carry a different half of the evidence. The 2+ renders are the duplication;
615
+ // what the carried edge adds is that the value IS the merge variable on some path — the
616
+ // register the compiler had to reserve across the branch either way, so the sunk spelling is
617
+ // strictly more work than the asm shows. Without it the scope reaches every shared
618
+ // SUBEXPRESSION of two arms, which agbcc computes per arm — `armkeep` is the row that prices
619
+ // that class, and `subexpr` the fixture that holds the line (armkeep's own arms share only a
620
+ // block PARAMETER, which has no def op to home, so the row never reaches this clause).
621
+ // Only a DOMINATING def is one definition the source could have written above the branch.
622
+ const feeders: Op[] = [];
623
+ for (const [v, n] of tally) {
624
+ const d = n >= 2 && carried.has(v) ? defOf.get(v) : undefined;
625
+ const b = d ? blockOf.get(d) : undefined;
626
+ if (d && b && b !== m && dom.get(m)!.has(b) && !inLoop.has(b) && eligible(d)) {
627
+ feeders.push(d);
628
+ }
629
+ }
630
+ // Only the MAXIMAL ones. Where a slot has enough edges for two of its arguments to qualify
631
+ // and one sits inside the other's cone, homing both spells `v0 = a1 & 1; v1 = v0 | 8;` where
632
+ // the source spelled one expression. The inner one renders INSIDE the outer's home, so its
633
+ // own is redundant; a feeder that is not covered stays, which is what keeps a second slot's
634
+ // smaller feeder its home.
635
+ const covered = new Set<Value>();
636
+ for (const d of feeders) {
637
+ for (const v of coneOf(d.results[0])) {
638
+ if (v !== d.results[0]) {
639
+ covered.add(v);
640
+ }
641
+ }
642
+ }
643
+ for (const d of feeders) {
644
+ if (!covered.has(d.results[0])) {
645
+ out.add(d);
646
+ }
647
+ }
648
+ }
649
+ }
650
+ return out;
651
+ }
652
+
653
+ /** rank.ts's enumeration gate for the `/merge-home` axis: does the function HAVE a value the axis
654
+ * would home? The scope itself rather than a restatement of it, so the gate and the rule cannot
655
+ * drift apart — admitting still says only that the rule fires, not that the tree changes. */
656
+ export function hasMergeFeedHome(fn: Fn): boolean {
657
+ const dom = dominators(fn);
658
+ const predsOf = predecessors(fn);
659
+ const inLoop = new Set(naturalLoops(fn, dom, predsOf).flatMap((L) => [...L.body]));
660
+ return mergeFeedHomes(fn, dom, defOpMap(fn), inLoop).size > 0;
661
+ }
662
+
16
663
  export interface StructureAnalysis {
17
664
  /** every positioned use of a value; a value absent here is dead */
18
665
  useSitesOf: Map<Value, UseSite[]>;
@@ -20,7 +667,8 @@ export interface StructureAnalysis {
20
667
  opBlock: Map<Op, Block>;
21
668
  /** SSA values live at each block's entry */
22
669
  liveIn: Map<Block, Set<Value>>;
23
- /** call/load defs that must emit as named temps at their own position */
670
+ /** defs that must emit as named temps at their own position — calls/loads for effect order,
671
+ * plus the pure defs the homing rules claim */
24
672
  materialize: Set<Op>;
25
673
  /** cached forward reachability (successors-transitive, excluding the start block itself) */
26
674
  reachFrom: (b: Block) => Set<Block>;
@@ -28,87 +676,315 @@ export interface StructureAnalysis {
28
676
  * transitively; null = several places / unresolvable (callers treat conservatively) */
29
677
  emitPos: (op: Op) => { blk: Block; idx: number } | null;
30
678
  /** may an op `isWrite` accepts execute between `def` and a statement at `render`, on any
31
- * def-avoiding path — the fold-ordering gate (see the closure's comment) */
679
+ * def-avoiding path — the fold-ordering gate (see `makeMemWriteBetween`) */
32
680
  memWriteBetween: (def: Op, render: { blk: Block; idx: number }, isWrite: (x: Op) => boolean) => boolean;
33
681
  }
34
682
 
35
- export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
36
- // ── use registry ────────────────────────────────────────────────────────────────────────
37
- // Every use of a value, POSITIONED: the consuming op and its block/index. Successor args are
38
- // uses AT the terminator (they render in argAssigns at block end). A void function's `ret`
39
- // operand is a phantom, not a real use — skipping it lets a call whose result ONLY flows into
40
- // the suppressed return read as a dead (side-effect) call, so `sideEffects()` emits it.
41
- // One operand SLOT = one entry (an op reading a value twice records two uses — that count is
42
- // what decides whether an inlined call would EXECUTE twice).
43
- const useSitesOf = new Map<Value, UseSite[]>();
44
- const opIndex = new Map<Op, number>();
45
- const opBlock = new Map<Op, Block>();
46
- const blockPos = new Map<Block, number>();
47
- for (const b of fn.blocks) {
48
- blockPos.set(b, blockPos.size);
49
- b.ops.forEach((op, i) => {
50
- opIndex.set(op, i);
51
- opBlock.set(op, b);
52
- });
683
+ export interface AnalyzeOptions {
684
+ /** the fn's def map (`defOpMap`) — the structurer already holds one, so it is passed rather than
685
+ * rebuilt. Absent the global-aware alias rule below cannot resolve anything and every write
686
+ * bars, exactly as before it existed. */
687
+ defs?: Map<Value, Op>;
688
+ /** Dominator sets, when the caller already holds them (structure() does) consumed by the
689
+ * live-across-a-loop rule's back-edge detection. Absent that rule stands down. */
690
+ dom?: Map<Block, Set<Block>>;
691
+ /** THE value-home axis (rank.ts `/reread-globals`). A read of a named global is barred from
692
+ * rendering at its use by any write in between — even a store to an unrelated global, which
693
+ * cannot possibly change what it sees. That over-conservatism is what invents the locals the
694
+ * round-5 dogfood measured as its highest-cost defect ("hoists what agbcc re-reads"):
695
+ *
696
+ * gA = v; gB = v; with `s32 v = gValue;` where the source said `gA = gValue; gB = gValue;`
697
+ *
698
+ * With this on, the barrier scan for a load whose address resolves to a named global uses THE
699
+ * shared disjointness query (ir/alias.ts) instead of "any write at all". Materializing a
700
+ * global's READ is always sound (the deref and its cast render at the def's position — contrast
701
+ * homeSharedAddresses below, where the materialized value is an address and soundness is
702
+ * scoped), so today's spelling is never wrong — only sometimes not the one the compiler was
703
+ * given.
704
+ * Which side matches is genuinely per-function (the same dogfood watched agbcc go both ways
705
+ * inside ONE function), so this is a differ-refereed candidate axis, never a default.
706
+ *
707
+ * SCOPE, since `readsStayWhereWritten` below now answers the same question — read once and
708
+ * reuse, or read per use — with the opposite default: this axis owns renders in the read's OWN
709
+ * block, where nothing about placement is in evidence and both spellings really do compile.
710
+ * A read whose every render sits in a STRICTLY DOMINATED block is the default's, and on a
711
+ * target that declares it the axis cannot produce the re-read spelling there (the rule
712
+ * materializes first). That is a pre-emption, not a conflict: a per-arm source read compiles to
713
+ * a per-arm load on that compiler, so the sunk spelling is one it did not emit from this asm. */
714
+ rereadGlobals?: boolean;
715
+ /** "does the project declare this global volatile?" — a read of a volatile object may NOT be
716
+ * duplicated or moved, so the axis above refuses on one. Answers false for a symbol the map
717
+ * does not carry (and for no map at all), which is the same posture the multi-render rule has
718
+ * always had: without a declaration nothing here can know, and the differ referees the extra
719
+ * load. Where the map DOES know, the axis is silent about it rather than wrong. */
720
+ volatileGlobal?: (name: string) => boolean;
721
+ /** The in-place-join axis (rank.ts `/inplace`). A load whose result is a `cond_br` successor
722
+ * ARG feeds a merge: rendered inline it has no name, so the merge param mints a fresh variable
723
+ * and BOTH arms must assign it. Materialized, the naming walk can home the merge in the load's
724
+ * own variable, the identity arm elides, and the `if` renders one-sided — `v = *p; if (v > 31)
725
+ * v = 32;` — which is also what reuses the load's register when recompiled. Whether the source
726
+ * spelled the temp or the overwrite is not derivable from the asm, so this is a differ-refereed
727
+ * candidate axis, never a default. Plain `br` args (loop-carried values) are out of scope:
728
+ * their homes are the loop-param machinery's question. */
729
+ materializeJoinFeeds?: boolean;
730
+ /** The address-home axis (rank.ts `/addr-home`). A pure computed address the asm derived ONCE
731
+ * and dereferenced at 2+ sites renders, by default, re-derived at each use — and the loads
732
+ * through it re-read per use — where the original source may have spelled a pointer local plus
733
+ * scalar temps (`u8 *entry = (u8 *)((a0 << 2) + base); type = entry[1]; idx = entry[0];`).
734
+ * The two spellings are codegen-visible (the re-derive folds each deref offset into its OWN
735
+ * pool literal; the home shares one base register across `[rN, #k]` accesses) and which one
736
+ * the source used is not derivable from asm, so this is a differ-refereed candidate axis,
737
+ * never a default. With it on: a non-const pure value whose MERGE CLASS is consumed ONLY as
738
+ * the base operand of 2+ memory accesses materializes (`sharedBaseClasses` — the class is what
739
+ * makes a base the arms derive and the join dereferences one register rather than three
740
+ * single-use values), and so does a multi-render `load` through such a base.
741
+ * Both rules only ADD materialization, which preserves semantics FOR THE VALUES THE SCOPE
742
+ * ADMITS — the gaddr/laddr cone refusal is the soundness half of that claim (rendered
743
+ * standalone, an address cone's value changes: the byte-stride cast lives at the use — see
744
+ * coneHoldsAddr; those bases stay with l3/basecse.ts, scopebase.ts and nearbase.ts), and the
745
+ * multi-block-loop-header seat refusal is the decline-avoidance half (same as
746
+ * liveAcrossLoop's). An L3 re-spell could not host this axis: by structuring's end the loads
747
+ * have already rendered per-use inside separate arms, and only this phase's positioned
748
+ * memory model can merge them into pre-branch temps. */
749
+ homeSharedAddresses?: boolean;
750
+ /** The loop-expression-home axis (rank.ts `/expr-home`). A pure computed value defined outside
751
+ * a loop and consumed by 2+ distinct ops, at least one of them inside that loop, is one the
752
+ * compiler holds in a (callee-saved) register across the iterations — it never re-derives per
753
+ * use in a loop —
754
+ * where the default renders it re-derived at each use; the source may have spelled a typed
755
+ * local (`u32 size = 16 << t;` driving a loop bound, a product and a shift). The home's
756
+ * declared type is the IR value's recovered type, so a u32 value's compares stay unsigned
757
+ * through the local. Straight-line multi-use values stay OUT (the small-constant class the
758
+ * const-across-call scope's note records); shared memory-access bases are `/addr-home`'s.
759
+ * Same refusals as that axis: gaddr/laddr cones and multi-block-loop-header seats. Adding
760
+ * materialization preserves semantics for the admitted values, exactly as above. */
761
+ homeLoopExprs?: boolean;
762
+ /** The derived-read-home axis (rank.ts `/derived-home`). A memory read whose value is not used
763
+ * directly but through a pure computation with 2+ consumers puts the home on the WRONG node:
764
+ * the read materializes (its consumer resolves no single render position) and the computation
765
+ * then re-derives from that local at every use, where the asm computed it ONCE — the read's
766
+ * register died at the computation and the DERIVED value is what a register carried on
767
+ * (`eor r1,r1,r0` keeps `0x3FF ^ REG_KEYINPUT`, never the raw halfword). With this on, a pure
768
+ * non-const value with 2+ consumers whose operand cone bottoms out at a memory read
769
+ * materializes instead; the read then renders exactly once, inside the home.
770
+ *
771
+ * A differ-refereed axis, not a fix: agbcc CSEs a re-derived expression back to one
772
+ * instruction often enough that both spellings do compile, and which one the source spelled is
773
+ * not derivable. What the cone's read supplies is the evidence the straight-line case otherwise
774
+ * lacks — `/expr-home` takes a loop as proof the value stayed in a register, and a
775
+ * freely-re-derivable value (the small-constant class) has no such proof at all, but a value
776
+ * standing on a read the source could not repeat is one the asm computed from a single access.
777
+ *
778
+ * Refusals, all of them about the ONE access the home must reproduce. A cone read used anywhere
779
+ * but the cone (its second use resolves a second render position, so the read would render
780
+ * twice). A cone read outside this value's own block, barred from it by a write, or barred by a
781
+ * read outside the cone (moving the access across a branch, into a loop, or past another access
782
+ * changes which paths read, how often, and in what order). A cone crossing a `call` (homing
783
+ * would move a side effect). A standalone gaddr/laddr in the cone, or a value that is ITSELF an
784
+ * address (rendered standalone the byte-stride cast lands outside the sum — see
785
+ * `rendersAsAddress`). And the multi-block-loop-header seat the sibling axes refuse. */
786
+ homeDerivedReads?: boolean;
787
+ /** The merge-feed-home axis (rank.ts `/merge-home`). A pure value one join's incoming edges
788
+ * render into the SAME parameter slot from 2+ places materializes at its def: the copy machinery
789
+ * has no name to reference, so the default re-derives the whole expression per arm
790
+ * (`m = (-(b & 1) | b & 1) >> 31 & 0x400;` in both) and agbcc if-converts each copy. The scope
791
+ * and every refusal it states are `mergeFeedHomes` above, which the enumeration gate also runs. */
792
+ homeMergeFeeds?: boolean;
793
+ /** DEF-BLOCK PLACEMENT for memory reads — WHERE the read happens, not where the value lives.
794
+ * The sibling of the homing axes above: there the question is which register or offset holds a
795
+ * value, here which BLOCK performs the read. A read whose every render sits in a block its own
796
+ * block STRICTLY DOMINATES has no rule at all above — those axes want 2+ consumers or a shared
797
+ * base — so it sinks and each arm re-reads it: a second load either way, plus a second pool
798
+ * literal when the address folded to a constant.
799
+ *
800
+ * A per-compiler DATA lever (TargetDescription.compilerBehaviors `readsStayWhereWritten`), not
801
+ * a differ-refereed axis, and that distinction is the argument: an axis exists where the asm
802
+ * UNDERDETERMINES the source, some pass having collapsed two spellings onto one output
803
+ * (`/uns-cmp`'s non-negativity proof is the type case). Where the compiler emits a read in the
804
+ * block the source spelled it in, re-spelling it at the block the asm read in reproduces that
805
+ * asm while the sunk spelling is one it emits only for a source that read per arm — nothing for
806
+ * the differ to referee, and the extra candidate is pure cost. Which compilers may declare
807
+ * that, and on what evidence, is at the target field; absent ⇒ the rule stands down entirely.
808
+ *
809
+ * Materializing is the conservative DIRECTION — back to the read's own def position, never
810
+ * forward past a write — so it adds no barrier scan; SINKING is what needs one (the
811
+ * multi-render rule below) and that scan stays. It is NOT sound by construction: the def block
812
+ * is the asm's read block only while nothing moved the def and a branch really does lie
813
+ * between, which is what the refusals are for. Getting that wrong emits a read on a path the
814
+ * asm never ran it on.
815
+ *
816
+ * Five refusals:
817
+ * • a multi-block loop HEADER, whose test-at-top condition seats no temp — `multiBlockHeaders`
818
+ * • a FALL-THROUGH between def and render, where the dominance is the frontend's
819
+ * block-per-label and no branch separates them — `fallThroughSeam`
820
+ * • a loop PREHEADER of the loop the renders are in, where loop invariant motion parks a read
821
+ * the source wrote in the BODY — `preheaderOfRenderLoop`
822
+ * • a read C evaluates only under a `&&`/`||`, whose def block raise/shortcircuit.ts made —
823
+ * `shortCircuitGuarded`
824
+ * • a read that IS a block parameter's incoming copy, where the seat manufactures a copy the
825
+ * compiler never emitted — `onlyFeedsBlockParams` */
826
+ readsStayWhereWritten?: boolean;
827
+ }
828
+
829
+ /** THE def-block placement rule's loop refusal: is `b` a PREHEADER of some loop whose body holds
830
+ * one of the render blocks — outside the body, and a predecessor of the header?
831
+ *
832
+ * Loop invariant motion (loop.c, which agbcc does compile and run at -O2) is the pass whose
833
+ * landing spot the source could not have spelled: it parks the read BELOW the loop guard, where
834
+ * a read the source wrote above the loop sits above it. Compiled,
835
+ * `for (i=0;i<n;i++) t += gK*i;` emits `mov r2,#0 / cmp r2,r3 / bge .L4 / ldr r0,.L8 /
836
+ * ldr r4,[r0]` — guard first, read after — while hoisting `gK` into a local above the loop by
837
+ * hand puts both `ldr`s ahead of the guard. So a read in the preheader is evidence of a read in
838
+ * the BODY, and inferring def-block placement there spells the one source the asm rules out.
839
+ * (With an aliasing store in the loop agbcc hoists only the address constant and leaves the
840
+ * `ldr` in the body — same conclusion, weaker premise.)
841
+ *
842
+ * Narrow on purpose: a loop merely lying between def and render is not this shape. */
843
+ function preheaderOfRenderLoop(
844
+ loopBodies: readonly { header: Block; body: Set<Block> }[],
845
+ b: Block,
846
+ renders: readonly Block[],
847
+ ): boolean {
848
+ return loopBodies.some(
849
+ (L) => !L.body.has(b) && successorsOf(b).includes(L.header) && renders.some((x) => L.body.has(x)),
850
+ );
851
+ }
852
+
853
+ /** THE def-block placement rule's seam refusal: does a FALL-THROUGH alone put a render below
854
+ * `b` — a chain of unconditional `br` edges, each into a block whose only predecessor is the
855
+ * one before it?
856
+ *
857
+ * The frontends start a block at every LABEL, so a label nothing branches to cuts one straight
858
+ * line of asm in two and the upper half dominates the lower with no control flow between. The
859
+ * rule's premise is that the compiler will not move a read ACROSS a branch, which says nothing
860
+ * there — while WITHIN a straight line agbcc picks the order itself. Compiled, klonoa's
861
+ * StreamCmd_SetMusicParams (a stray `sub_0804E9AC:` between its last `ldrh r2,[r4]` and the
862
+ * `bl` consuming it) assembles byte-identical to its object from the inlined read and four
863
+ * bytes off from the named one, which swaps that `ldrh` with the `ldr r0,pool` beside it. Of
864
+ * the rule's 20 firings over the 464 klonoa agbcc functions, 13 were across such a seam. */
865
+ function fallThroughSeam(predsOf: Map<Block, Block[]>, b: Block, renders: readonly Block[]): boolean {
866
+ const seen = new Set<Block>([b]);
867
+ for (let cur = b; ;) {
868
+ const t = cur.ops[cur.ops.length - 1];
869
+ if (t?.opcode !== 'br') {
870
+ return false;
871
+ }
872
+ const next = t.successors[0].block;
873
+ if (predsOf.get(next)!.length !== 1 || seen.has(next)) {
874
+ return false;
875
+ }
876
+ if (renders.includes(next)) {
877
+ return true;
878
+ }
879
+ seen.add(next);
880
+ cur = next;
53
881
  }
54
- // Linear program position (block order, then op order): a call "between" a def and a use is one
55
- // whose position lies strictly between them. This is a PROXY for "a call on a def→use path", not
56
- // the real dataflow: it checks position order only, not reachability. It can therefore FALSE-
57
- // POSITIVE a call in a forward SIBLING branch (never traversed on the def→use path) still sits
58
- // between them by position (e.g. `def; if(c){call;ret} else {…use…use}`), and back-edges are not
59
- // modelled either. That is SAFE ONLY BECAUSE the caller materializes exactly `const` ops: a const
60
- // is a relocation-invariant leaf whose def dominates every use, so binding it to a local is
61
- // UNCONDITIONALLY semantics-preserving on every path a false positive costs at most a match (an
62
- // extra `v =` the compiler would have re-inlined), caught by the zero-lost gate, never wrong C.
63
- // RE-VERIFY this before widening the whitelist to any value that is not path-independent or that
64
- // carries a use-site cast (an address computation `&g + i`), for which a false positive is unsound.
65
- const linPos = (op: Op): number => blockPos.get(opBlock.get(op)!)! * 1e6 + opIndex.get(op)!;
66
- const callPos: number[] = [];
67
- for (const b of fn.blocks) {
68
- for (const op of b.ops) {
69
- if (op.opcode === 'call') {
70
- callPos.push(linPos(op));
882
+ }
883
+
884
+ /** THE def→render path discipline. May an op `isWrite` accepts execute between `def` and a
885
+ * statement at `render`, on any def-avoiding path? The def block's tail, the render block's head,
886
+ * and every between-block on a path; a path re-crossing the def is the NEXT dynamic instance and
887
+ * does not count. Path-based on purpose: `fn.blocks` is ADDRESS order, so a linear-position scan
888
+ * misses a block laid out after the render that executes between def and render on the taken path
889
+ * (an audit round broke exactly that way). */
890
+ function makeMemWriteBetween(deps: {
891
+ opBlock: Map<Op, Block>;
892
+ opIndex: Map<Op, number>;
893
+ reachAvoiding: (from: Block, avoid: Block) => Set<Block>;
894
+ }): (def: Op, render: { blk: Block; idx: number }, isWrite: (x: Op) => boolean) => boolean {
895
+ const { opBlock, opIndex, reachAvoiding } = deps;
896
+ return (def: Op, render: { blk: Block; idx: number }, isWrite: (x: Op) => boolean): boolean => {
897
+ const b = opBlock.get(def)!;
898
+ const oi = opIndex.get(def)!;
899
+ const wDirty = (list: Op[], from: number, to: number): boolean => {
900
+ for (let k = from; k < to; k++) {
901
+ if (isWrite(list[k])) {
902
+ return true;
903
+ }
904
+ }
905
+ return false;
906
+ };
907
+ // Same block: the only def-avoiding path is the straight line between the two indices
908
+ // (leaving and re-entering the block re-crosses the def). A render BEFORE the def cannot
909
+ // happen — within a block, uses follow defs — and falls through to the path walk, whose
910
+ // answer is the conservative one.
911
+ if (render.blk === b && oi < render.idx) {
912
+ return wDirty(b.ops, oi + 1, render.idx);
913
+ }
914
+ if (wDirty(b.ops, oi + 1, b.ops.length) || wDirty(render.blk.ops, 0, render.idx)) {
915
+ return true;
916
+ }
917
+ for (const x of reachAvoiding(b, b)) {
918
+ if (x === render.blk && !reachAvoiding(render.blk, b).has(render.blk)) {
919
+ continue; // acyclic render block: head checked
920
+ }
921
+ if (x !== render.blk && !reachAvoiding(x, b).has(render.blk)) {
922
+ continue; // not on a def→render path
923
+ }
924
+ if (wDirty(x.ops, 0, x.ops.length)) {
925
+ return true;
926
+ }
927
+ }
928
+ return false;
929
+ };
930
+ }
931
+
932
+ /** INTERDEPENDENT PARALLEL-COPY ARGS. A terminator's successor args are ONE parallel copy
933
+ * (argAssigns), whose every read means the PRE-copy value. An arg whose def-tree reads a SIBLING
934
+ * arg of the same edge cannot read it by name there — so the sibling's whole expression is
935
+ * re-derived inside this arg's copy, and `sequentialize` spills old-value temps to untangle the
936
+ * order: arithmetic the compiler performed once, emitted per reader (the coupled-recurrence loop,
937
+ * `a += b*c; d += a;`). The read sibling is the register the copy machinery cannot represent —
938
+ * its def is the one the caller materializes. The walk crosses pure defs only (a call/load render
939
+ * is those rules' question) and stops at params, which always carry a name. */
940
+ function copyInterdependentValues(fn: Fn, defOf: Map<Value, Op>): Set<Value> {
941
+ const copyInterdependent = new Set<Value>();
942
+ const pureReads = (root: Value, acc: Set<Value>) => {
943
+ const stack = [root];
944
+ while (stack.length) {
945
+ const x = stack.pop()!;
946
+ const d = defOf.get(x);
947
+ if (!d || acc.has(x)) {
948
+ continue;
949
+ }
950
+ acc.add(x);
951
+ if (d.opcode !== 'call' && d.opcode !== 'load' && d.opcode !== 'aload') {
952
+ stack.push(...d.operands);
71
953
  }
72
954
  }
73
- }
74
- /** True if `def`'s value is still needed after a call — a call lies strictly between the def and
75
- * one of its `consumers`. Such a value survives in a callee-saved register (a local), which is
76
- * what materializing it reproduces. */
77
- const liveAcrossCall = (def: Op, consumers: Op[]): boolean => {
78
- const dp = linPos(def);
79
- const usePos = consumers.map(linPos);
80
- return callPos.some((c) => c > dp && usePos.some((u) => u > c));
81
955
  };
82
956
  for (const b of fn.blocks) {
83
- b.ops.forEach((op, i) => {
84
- if (returnsVoid && op.opcode === 'ret') {
85
- return;
957
+ for (const s of b.ops[b.ops.length - 1]?.successors ?? []) {
958
+ if (s.args.length < 2) {
959
+ continue;
86
960
  }
87
- const site: UseSite = { blk: b, idx: i, op };
88
- const add = (v: Value) => {
89
- const arr = useSitesOf.get(v);
90
- if (arr) {
91
- arr.push(site);
92
- } else {
93
- useSitesOf.set(v, [site]);
961
+ for (const w of s.args) {
962
+ const d = defOf.get(w);
963
+ if (!d || d.opcode === 'call' || d.opcode === 'load' || d.opcode === 'aload') {
964
+ continue;
94
965
  }
95
- };
96
- for (const u of op.operands) {
97
- add(u);
98
- }
99
- for (const s of op.successors) {
100
- for (const a of s.args) {
101
- add(a);
966
+ const reads = new Set<Value>();
967
+ for (const o of d.operands) {
968
+ pureReads(o, reads);
969
+ }
970
+ for (const v of s.args) {
971
+ if (v !== w && reads.has(v)) {
972
+ copyInterdependent.add(v);
973
+ }
102
974
  }
103
975
  }
104
- });
976
+ }
105
977
  }
978
+ return copyInterdependent;
979
+ }
106
980
 
107
- // ── per-block liveness of SSA values ──────────────────────────────────────────────────────
108
- // Backward dataflow. Successor args count as uses at the END of the predecessor (they render
109
- // in the predecessor's argAssigns), so liveIn(B) means precisely "read at-or-after B's entry".
110
- // Consumed by the coalescing interference check: merging two values that are ever
111
- // simultaneously live into one variable name is the textbook silent clobber.
981
+ /** PER-BLOCK LIVENESS of SSA values — backward dataflow. Successor args count as uses at the END
982
+ * of the predecessor (they render in the predecessor's argAssigns), so liveIn(B) means precisely
983
+ * "read at-or-after B's entry". Consumed by the coalescing interference check: merging two values
984
+ * that are ever simultaneously live into one variable name is the textbook silent clobber.
985
+ *
986
+ * `returnsVoid` suppresses the phantom `ret` operand, the same way the use registry does. */
987
+ function blockLiveIn(fn: Fn, returnsVoid: boolean): Map<Block, Set<Value>> {
112
988
  const liveIn = new Map<Block, Set<Value>>();
113
989
  for (const b of fn.blocks) {
114
990
  liveIn.set(b, new Set());
@@ -149,17 +1025,22 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
149
1025
  }
150
1026
  }
151
1027
  }
1028
+ return liveIn;
1029
+ }
152
1030
 
153
- // ── the effect-ordering model inline-at-use barriers ────────────────────────────────────
154
- // `expr()` renders a def's computation AT ITS USE, which silently MOVES it: a call executes
155
- // once per rendered copy (`foo(a0)+foo(a0)`), a load reads memory at the render point (it can
156
- // textually sink past an aliasing store). The model: a call/load/aload def may inline ONLY
157
- // when rendering cannot change behavior — exactly one render position, and the program-order
158
- // gap between def and render crosses no memory write (loads) / no memory access at all (calls,
159
- // whose own reads+writes must not reorder against anything). Every other case gets a NAMED
160
- // TEMP assigned at the def's own program position (sideEffects) which is precisely the
161
- // register the compiler used.
162
- const materialize = new Set<Op>();
1031
+ /** FORWARD REACHABILITY over the CFG, in the two flavours the materialization rules ask for.
1032
+ *
1033
+ * `reachFrom` is the plain successors-transitive set, excluding the start block itself, cached per
1034
+ * factory which is why this is a factory: the cache belongs to one `analyze` call.
1035
+ *
1036
+ * `reachAvoiding` never passes THROUGH `avoid` the def-block-avoiding variant for per-iteration
1037
+ * path checks: a path that re-enters the def's block re-executes the def, so writes on it belong
1038
+ * to the NEXT dynamic instance (which re-renders anyway) and must not count against this one.
1039
+ * Uncached (per-decision graphs are small). */
1040
+ function makeReach(): {
1041
+ reachFrom: (b: Block) => Set<Block>;
1042
+ reachAvoiding: (from: Block, avoid: Block) => Set<Block>;
1043
+ } {
163
1044
  const reachCache = new Map<Block, Set<Block>>();
164
1045
  const reachFrom = (b: Block): Set<Block> => {
165
1046
  let r = reachCache.get(b);
@@ -200,33 +1081,393 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
200
1081
  }
201
1082
  return r;
202
1083
  };
1084
+ return { reachFrom, reachAvoiding };
1085
+ }
1086
+
1087
+ export function analyze(fn: Fn, returnsVoid: boolean, opts: AnalyzeOptions = {}): StructureAnalysis {
1088
+ const {
1089
+ defs,
1090
+ dom,
1091
+ rereadGlobals = false,
1092
+ volatileGlobal,
1093
+ materializeJoinFeeds = false,
1094
+ homeSharedAddresses = false,
1095
+ homeLoopExprs = false,
1096
+ homeDerivedReads = false,
1097
+ homeMergeFeeds = false,
1098
+ readsStayWhereWritten = false,
1099
+ } = opts;
1100
+ // ── use registry ────────────────────────────────────────────────────────────────────────
1101
+ // Every use of a value, POSITIONED: the consuming op and its block/index. Successor args are
1102
+ // uses AT the terminator (they render in argAssigns at block end). A void function's `ret`
1103
+ // operand is a phantom, not a real use — skipping it lets a call whose result ONLY flows into
1104
+ // the suppressed return read as a dead (side-effect) call, so `sideEffects()` emits it.
1105
+ // One operand SLOT = one entry (an op reading a value twice records two uses — that count is
1106
+ // what decides whether an inlined call would EXECUTE twice).
1107
+ const useSitesOf = new Map<Value, UseSite[]>();
1108
+ const opIndex = new Map<Op, number>();
1109
+ const opBlock = new Map<Op, Block>();
1110
+ const blockPos = new Map<Block, number>();
1111
+ for (const b of fn.blocks) {
1112
+ blockPos.set(b, blockPos.size);
1113
+ b.ops.forEach((op, i) => {
1114
+ opIndex.set(op, i);
1115
+ opBlock.set(op, b);
1116
+ });
1117
+ }
1118
+ // Linear program position (block order, then op order): a call "between" a def and a use is one
1119
+ // whose position lies strictly between them. This is a PROXY for "a call on a def→use path", not
1120
+ // the real dataflow: it checks position order only, not reachability. It can therefore FALSE-
1121
+ // POSITIVE — a call in a forward SIBLING branch (never traversed on the def→use path) still sits
1122
+ // between them by position (e.g. `def; if(c){call;ret} else {…use…use}`), and back-edges are not
1123
+ // modelled either. That is SAFE ONLY BECAUSE the caller materializes exactly `const` ops: a const
1124
+ // is a relocation-invariant leaf whose def dominates every use, so binding it to a local is
1125
+ // UNCONDITIONALLY semantics-preserving on every path — a false positive costs at most a match (an
1126
+ // extra `v =` the compiler would have re-inlined), caught by the zero-lost gate, never wrong C.
1127
+ // RE-VERIFY this before widening the whitelist to any value that is not path-independent or that
1128
+ // carries a use-site cast (an address computation `&g + i`), for which a false positive is unsound.
1129
+ const linPos = (op: Op): number => blockPos.get(opBlock.get(op)!)! * 1e6 + opIndex.get(op)!;
1130
+ const callPos: number[] = [];
1131
+ for (const b of fn.blocks) {
1132
+ for (const op of b.ops) {
1133
+ if (op.opcode === 'call') {
1134
+ callPos.push(linPos(op));
1135
+ }
1136
+ }
1137
+ }
1138
+ // Which values ride a branch edge as a successor ARG, in two scopes with two different readers.
1139
+ //
1140
+ // `branchArgFed` is EVERY multi-successor terminator's, and it is a correctness fact: an edge
1141
+ // argument is emitted INSIDE the arm it belongs to, so a value that renders only there runs only
1142
+ // on that path. For a call that is an effect the IR performs unconditionally and the C performs
1143
+ // sometimes, and a `switch_br` does it as readily as a `cond_br`. Plain `br` args are excluded
1144
+ // because their edge copy is on the one path that reaches the successor, so nothing conditional
1145
+ // happens to them.
1146
+ //
1147
+ // `condBrArgFed` is the `/inplace` axis's narrower reading — a preference about where a load's
1148
+ // value is homed, whose own scope note is on AnalyzeOptions.materializeJoinFeeds.
1149
+ const branchArgFed = new Set<Value>();
1150
+ const condBrArgFed = new Set<Value>();
1151
+ for (const b of fn.blocks) {
1152
+ for (const op of b.ops) {
1153
+ if (op.successors.length > 1) {
1154
+ for (const s of op.successors) {
1155
+ for (const a of s.args) {
1156
+ branchArgFed.add(a);
1157
+ if (op.opcode === 'cond_br') {
1158
+ condBrArgFed.add(a);
1159
+ }
1160
+ }
1161
+ }
1162
+ }
1163
+ }
1164
+ }
1165
+ /** True if `def`'s value is still needed after a call — a call lies strictly between the def and
1166
+ * one of its `consumers`. Such a value survives in a callee-saved register (a local), which is
1167
+ * what materializing it reproduces. */
1168
+ const liveAcrossCall = (def: Op, consumers: Op[]): boolean => {
1169
+ const dp = linPos(def);
1170
+ const usePos = consumers.map(linPos);
1171
+ return callPos.some((c) => c > dp && usePos.some((u) => u > c));
1172
+ };
1173
+ for (const b of fn.blocks) {
1174
+ b.ops.forEach((op, i) => {
1175
+ if (returnsVoid && op.opcode === 'ret') {
1176
+ return;
1177
+ }
1178
+ const site: UseSite = { blk: b, idx: i, op };
1179
+ const add = (v: Value) => {
1180
+ const arr = useSitesOf.get(v);
1181
+ if (arr) {
1182
+ arr.push(site);
1183
+ } else {
1184
+ useSitesOf.set(v, [site]);
1185
+ }
1186
+ };
1187
+ for (const u of op.operands) {
1188
+ add(u);
1189
+ }
1190
+ for (const s of op.successors) {
1191
+ for (const a of s.args) {
1192
+ add(a);
1193
+ }
1194
+ }
1195
+ });
1196
+ }
1197
+
1198
+ const liveIn = blockLiveIn(fn, returnsVoid);
1199
+
1200
+ // ── the effect-ordering model — inline-at-use barriers ────────────────────────────────────
1201
+ // `expr()` renders a def's computation AT ITS USE, which silently MOVES it: a call executes
1202
+ // once per rendered copy (`foo(a0)+foo(a0)`), a load reads memory at the render point (it can
1203
+ // textually sink past an aliasing store). The model: a call/load/aload def may inline ONLY
1204
+ // when rendering cannot change behavior — exactly one render position, and the program-order
1205
+ // gap between def and render crosses no memory write (loads) / no memory access at all (calls,
1206
+ // whose own reads+writes must not reorder against anything). Every other case gets a NAMED
1207
+ // TEMP assigned at the def's own program position (sideEffects) — which is precisely the
1208
+ // register the compiler used.
1209
+ const materialize = new Set<Op>();
1210
+ const { reachFrom, reachAvoiding } = makeReach();
203
1211
  // Where a value's expression is ultimately EMITTED: the anchored consumer (statement op,
204
1212
  // terminator, materialized def) it inlines into, transitively through single-use pure ops.
205
1213
  // null = renders in several places / unresolvable (treated conservatively by the caller).
206
1214
  const emitPosCache = new Map<Op, { blk: Block; idx: number } | null>();
1215
+ /** an op that renders AT ITS OWN position: a statement, a terminator, a materialized or dead def */
1216
+ const anchored = (op: Op): boolean =>
1217
+ op.successors.length > 0 ||
1218
+ op.opcode === 'ret' ||
1219
+ op.opcode === 'store' ||
1220
+ op.opcode === 'astore' ||
1221
+ materialize.has(op) ||
1222
+ !op.results.length ||
1223
+ !useSitesOf.has(op.results[0]);
1224
+ const consumersOf = (op: Op): Op[] => [...new Set((useSitesOf.get(op.results[0]) ?? []).map((s) => s.op))];
207
1225
  const emitPos = (op: Op): { blk: Block; idx: number } | null => {
208
1226
  if (emitPosCache.has(op)) {
209
1227
  return emitPosCache.get(op)!;
210
1228
  }
211
- const own = { blk: opBlock.get(op)!, idx: opIndex.get(op)! };
212
1229
  let res: { blk: Block; idx: number } | null;
213
- if (
214
- op.successors.length ||
215
- op.opcode === 'ret' ||
216
- op.opcode === 'store' ||
217
- op.opcode === 'astore' ||
218
- materialize.has(op) ||
219
- !op.results.length ||
220
- !useSitesOf.has(op.results[0])
221
- ) {
222
- res = own; // statements, terminators, materialized/dead defs
1230
+ if (anchored(op)) {
1231
+ res = { blk: opBlock.get(op)!, idx: opIndex.get(op)! };
223
1232
  } else {
224
- const consumers = [...new Set((useSitesOf.get(op.results[0]) ?? []).map((s) => s.op))];
1233
+ const consumers = consumersOf(op);
225
1234
  res = consumers.length === 1 ? emitPos(consumers[0]) : null;
226
1235
  }
227
1236
  emitPosCache.set(op, res);
228
1237
  return res;
229
1238
  };
1239
+ // EVERY position a value's expression renders at — `emitPos` generalized to the whole set (it
1240
+ // answers one place or gives up), by following ALL consumers transitively. That matters for
1241
+ // the value-home axis: a pure expression with two consumers (`gOut = e; return e;`) has no single
1242
+ // emit position, so `emitPos` answers null and every memory read feeding it is forced into a
1243
+ // local — even when re-reading at both places is provably equivalent. Null only for a genuine
1244
+ // cycle (defensive: SSA use-def is acyclic through ops), which the caller treats as unresolvable.
1245
+ //
1246
+ // NEVER for a call: two render positions mean two executions, so a call whose consumer renders in
1247
+ // several places must keep answering null and materialize.
1248
+ const emitPosSetCache = new Map<Op, { blk: Block; idx: number }[] | null>();
1249
+ const emitPositions = (op: Op, visiting: Set<Op> = new Set()): { blk: Block; idx: number }[] | null => {
1250
+ const hit = emitPosSetCache.get(op);
1251
+ if (hit !== undefined) {
1252
+ return hit;
1253
+ }
1254
+ if (visiting.has(op)) {
1255
+ return null;
1256
+ }
1257
+ let res: { blk: Block; idx: number }[] | null;
1258
+ if (anchored(op)) {
1259
+ res = [{ blk: opBlock.get(op)!, idx: opIndex.get(op)! }];
1260
+ } else {
1261
+ visiting.add(op);
1262
+ const seenPos = new Set<string>();
1263
+ const acc: { blk: Block; idx: number }[] = [];
1264
+ res = acc;
1265
+ for (const c of consumersOf(op)) {
1266
+ const sub = emitPositions(c, visiting);
1267
+ if (!sub) {
1268
+ res = null;
1269
+ break;
1270
+ }
1271
+ for (const p of sub) {
1272
+ const key = `${blockPos.get(p.blk)}:${p.idx}`;
1273
+ if (!seenPos.has(key)) {
1274
+ seenPos.add(key);
1275
+ acc.push(p);
1276
+ }
1277
+ }
1278
+ }
1279
+ visiting.delete(op);
1280
+ }
1281
+ emitPosSetCache.set(op, res);
1282
+ return res;
1283
+ };
1284
+ const memWriteBetween = makeMemWriteBetween({ opBlock, opIndex, reachAvoiding });
1285
+ const defOf = defs ?? defOpMap(fn);
1286
+ const copyInterdependent = copyInterdependentValues(fn, defOf);
1287
+ // ── natural loops, for the live-across-a-loop rule ────────────────────────────────────────
1288
+ // From the caller's dominators (a back edge is `latch → header` with the header dominating the
1289
+ // latch); the body is the backward closure from the latch. With no `dom` the rule stands
1290
+ // down — the same posture as the `defs`-carried rules.
1291
+ const predsOf = predecessors(fn);
1292
+ const loopBodies = dom ? naturalLoops(fn, dom, predsOf) : [];
1293
+ /** The def's value enters some loop's header live and every consumer sits outside that loop,
1294
+ * as does the def: the value is carried ACROSS the loop, not into it. */
1295
+ // Never for a def in a MULTI-BLOCK loop header: a test-at-top `while`'s condition has no seat
1296
+ // for a materialized temp (the structurer's headerPure gate), so materializing there trades a
1297
+ // structuring function for a decline. Self-loop headers stay eligible — their kept-guard
1298
+ // do-while form hosts the temp.
1299
+ const multiBlockHeaders = new Set(loopBodies.filter((L) => L.body.size > 1).map((L) => L.header));
1300
+ const liveAcrossLoop = (def: Op, r: Value, consumers: Op[]): boolean =>
1301
+ !multiBlockHeaders.has(opBlock.get(def)!) &&
1302
+ loopBodies.some(
1303
+ (L) =>
1304
+ liveIn.get(L.header)!.has(r) &&
1305
+ !L.body.has(opBlock.get(def)!) &&
1306
+ consumers.every((c) => !L.body.has(opBlock.get(c)!)),
1307
+ );
1308
+ /** Would naming THIS op's own result change its value? Yes when the result is an ADDRESS built
1309
+ * over a gaddr/laddr: rendered standalone an `&g + i` loses the memAccess's inline byte-stride
1310
+ * cast, and the cast-aware base machinery in l3/ serves those bases instead. Asked by the rules
1311
+ * that home an address; a rule homing the SCALAR a load returns is not this case — the name
1312
+ * holds the loaded value and the address stays inline at the deref, which is why the load rules
1313
+ * (live-across-a-loop, join feeds, /addr-home's, def-block placement) do not ask it. */
1314
+ const addressCone = (op0: Op): boolean => coneHoldsAddr(op0, defOf);
1315
+ // ── the address-home axis's scope ─────────────────────────────────────────────────────────
1316
+ // Over the MERGE CLASS, so a base the arms derive and the join dereferences counts as the one
1317
+ // register it is — see `sharedBaseClasses`. Computed once, and only under the axis.
1318
+ const sharedBaseClass = homeSharedAddresses ? sharedBaseClasses(fn, returnsVoid) : new Set<Value>();
1319
+ // The same question asked of the VALUE ALONE, which is what the two axes below need: their
1320
+ // "shared bases stay the address-home scope's" exclusion is a hand-off between scopes, and
1321
+ // widening it to the class would make them refuse values the address-home scope only claims
1322
+ // when its own axis is ON — a candidate lost with no candidate gained. Where both axes run the
1323
+ // two scopes may claim one value, which is a no-op: `materialize` is a set and the address-home
1324
+ // scope, running first, is what registers `axisHomedBases`.
1325
+ const usedOnlyAsSharedBase = (v: Value): boolean => {
1326
+ const sites = useSitesOf.get(v) ?? [];
1327
+ const consumers = new Set(sites.map((s) => s.op));
1328
+ return (
1329
+ consumers.size >= 2 &&
1330
+ [...consumers].every(
1331
+ (c) => MEM_BASE_OPS.has(c.opcode) && c.operands[0] === v && !c.operands.some((o, i) => i > 0 && o === v),
1332
+ )
1333
+ );
1334
+ };
1335
+ // The merge-feed-home axis's ops, settled BEFORE the fixpoint: the scope reads the IR alone (no
1336
+ // render positions, no `materialize`), so it cannot change as the set grows. Unlike the rules
1337
+ // that stand down without the caller's `dom`, this one computes its own: rank.ts has already
1338
+ // admitted the candidate on `hasMergeFeedHome`, which runs the same scope, so standing down here
1339
+ // would be a refusal nothing reports.
1340
+ let mergeFeedOps = new Set<Op>();
1341
+ if (homeMergeFeeds) {
1342
+ const mdom = dom ?? dominators(fn);
1343
+ const mloops = mdom === dom ? loopBodies : naturalLoops(fn, mdom, predsOf);
1344
+ mergeFeedOps = mergeFeedHomes(fn, mdom, defOf, new Set(mloops.flatMap((L) => [...L.body])));
1345
+ }
1346
+ /** result values the address-home axis materialized — the load rule's admission key */
1347
+ const axisHomedBases = new Set<Value>();
1348
+ /** The loop-expression-home axis's scope: 2+ distinct consumers of the value, at least one of
1349
+ * them inside a loop the def's block is outside (loop model = the caller's dominators; absent ⇒
1350
+ * never).
1351
+ *
1352
+ * The two counts carry different halves of the evidence. ONE consumer inside the loop is what
1353
+ * says the compiler held the value in a callee-saved register across the iterations — it does
1354
+ * not re-derive per use in a loop, and a value crossing the loop boundary is pinned for the
1355
+ * whole nest. The SECOND consumer, anywhere, is what makes the home observable at all: a
1356
+ * single-use value inlines at its one use with the same bytes either way, so homing it can only
1357
+ * add a copy. Values consumed only OUTSIDE any loop are the straight-line class `/derived-home`
1358
+ * serves on its own evidence. */
1359
+ const loopSharedConsumers = (v: Value, defBlk: Block): boolean => {
1360
+ const consumers = [...new Set((useSitesOf.get(v) ?? []).map((s) => s.op))];
1361
+ return (
1362
+ consumers.length >= 2 &&
1363
+ loopBodies.some((L) => !L.body.has(defBlk) && consumers.some((c) => L.body.has(opBlock.get(c)!)))
1364
+ );
1365
+ };
1366
+ /** The derived-read-home axis's scope: does `op0` stand on a memory READ that may render at
1367
+ * `op0`'s own position?
1368
+ *
1369
+ * The cone walk STOPS at a read — its address stays inline at the deref, so nothing below it is
1370
+ * ever rendered standalone — and refuses on anything else that cannot move to `op0`: a `call`
1371
+ * (a side effect), and a gaddr/laddr reached OUTSIDE a read's address (rendered standalone an
1372
+ * `&g + i` loses the memAccess's byte-stride cast). `coneHoldsAddr` cannot answer this: it
1373
+ * crosses reads, so it refuses every value standing on a named global's load — which is this
1374
+ * axis's whole clientele.
1375
+ *
1376
+ * At least one read is required. A value derivable from locals and constants alone is one the
1377
+ * compiler re-materializes for free, and homing it only adds copies — the small-constant class
1378
+ * the const scope's note records.
1379
+ *
1380
+ * Each read must then sit in `op0`'s OWN BLOCK, and reach `op0`'s position with nothing that
1381
+ * writes memory able to execute in between — homing renders the read at `op0`, so both are
1382
+ * about moving it there.
1383
+ *
1384
+ * A read OUTSIDE the cone bars it too. The default's "loads never bar a load" holds for reads
1385
+ * the compiler leaves unsequenced inside ONE expression, which is what the cone's own reads
1386
+ * become; a foreign read renders in a different statement, so moving past it reorders two
1387
+ * accesses — for two MMIO cells (this axis's clientele) an observable swap, as when `A`'s
1388
+ * derived value sits below `B`'s and homing both puts `B`'s read first.
1389
+ *
1390
+ * And each read's value must go NOWHERE BUT the cone: exactly one use site. Homing resolves a
1391
+ * render position for a read that had none, so a SECOND use resolves a second one, and the
1392
+ * multi-render load rule then inlines the read at BOTH — two accesses where the asm has one
1393
+ * `ldrh`, which for a volatile cell is precisely the duplication `volatileGlobal` refuses. Two
1394
+ * homed values over one read is the same shape from the other side (each is the other's second
1395
+ * use), so one test covers both. This is what makes "renders once, inside the home" a property
1396
+ * rather than an aspiration: without it the axis silently doubles a hardware read.
1397
+ *
1398
+ * The same block is what makes the axis's claim true at all: the register handoff it reproduces
1399
+ * is one straight-line run of the asm, `ldrh` into `eor` into three uses. Across blocks WHICH
1400
+ * BLOCK reads is `readsStayWhereWritten`'s question, not this one, and answering it here goes
1401
+ * wrong in both directions — a value below a branch pulls the read into an arm that may not
1402
+ * run, a value inside a loop pulls it in to run per iteration. Neither is a write, so no
1403
+ * barrier sees either; for an ordinary cell they are worse spellings, and for a volatile one
1404
+ * they are a missing access and a duplicated one. */
1405
+ const standsOnMovableRead = (op0: Op, blk: Block): boolean => {
1406
+ const reads = readCone(op0, defOf);
1407
+ if (reads === null) {
1408
+ return false;
1409
+ }
1410
+ const at = { blk, idx: opIndex.get(op0)! };
1411
+ const coneReads = new Set(reads);
1412
+ const bars = (x: Op): boolean =>
1413
+ EFFECTFUL_OPS.has(x.opcode) || ((x.opcode === 'load' || x.opcode === 'aload') && !coneReads.has(x));
1414
+ return (
1415
+ reads.length > 0 &&
1416
+ reads.every(
1417
+ (r) =>
1418
+ opBlock.get(r) === blk && (useSitesOf.get(r.results[0])?.length ?? 0) === 1 && !memWriteBetween(r, at, bars),
1419
+ )
1420
+ );
1421
+ };
1422
+ /** 2+ distinct consuming ops — the multi-use the pure-op rule reads as a reused register. */
1423
+ const multiConsumer = (v: Value): boolean => new Set((useSitesOf.get(v) ?? []).map((s) => s.op)).size >= 2;
1424
+ /** THE def-block placement rule's short-circuit refusal: values C evaluates only under a
1425
+ * `&&`/`||` — the SECOND operand of every `logic_and`/`logic_or`, and everything it reads.
1426
+ *
1427
+ * raise/shortcircuit.ts recovers a connective by hoisting the guarded arm's whole pure body,
1428
+ * memory reads included, into the block ABOVE the branch (its value form and its control-flow
1429
+ * form both splice that body into the head). ir/opcodes.ts states the safety argument as the
1430
+ * reason a read is deliberately absent from HOIST_UNSAFE_OPS: the structurer inlines it back
1431
+ * into the `&&`/`||` right-hand side, where C's own short circuit re-guards it. So for a value
1432
+ * in that cone the def block is a FOLD ARTIFACT rather than the block the asm read in, and the
1433
+ * whole premise this rule reads placement under does not hold there. Naming it also breaks the
1434
+ * re-guard: `p != 0 && *p != 0` would emit `v0 = *p;` above its own null check.
1435
+ *
1436
+ * An operand[0] cone is unconditional and keeps the rule; only the guarded side is collected. */
1437
+ const shortCircuitGuarded = readsStayWhereWritten ? shortCircuitGuardedValues(fn, defOf) : new Set<Value>();
1438
+ /** THE def-block placement rule's copy refusal: is every use of the value a successor ARGUMENT,
1439
+ * i.e. is the value nothing but a block parameter's incoming copy?
1440
+ *
1441
+ * Then the parameter IS the read's home. Inlined, the edge assignment is the read
1442
+ * (`v1 = mplay->tracks;`); materialized it becomes two names and a copy between them
1443
+ * (`v0 = mplay->tracks; … v1 = v0;`) where the asm loaded straight into the register the
1444
+ * parameter became — `ldr r1,[r4,#0x2C]` once, never a `mov`. Six of klonoa's matched m4a
1445
+ * functions are that shape, and the manufactured copy costs more than the placement gains:
1446
+ * scored against their own objects, dropping the refusal takes m4aMPlayVolumeControl 26→33,
1447
+ * m4aMPlayPitchControl 36→39, m4aMPlayLFOSpeedSet 28→31 and FadeOutBody 69→73.
1448
+ *
1449
+ * Note what this does NOT claim: those reads really do sit above the loop guard in the asm, so
1450
+ * the placement inference was right and the SPELLING is what fails. Seating the read above the
1451
+ * guard AND as the loop variable is loop-init hoisting, a capability this rule does not have. */
1452
+ const argUsedValues = new Set<Value>();
1453
+ const operandUsedValues = new Set<Value>();
1454
+ // Both sets serve that rule alone, so they are built only where it can fire — the same posture
1455
+ // `condBrArgFed` takes above (every other target pays nothing for a behavior it never declares).
1456
+ if (readsStayWhereWritten) {
1457
+ for (const b of fn.blocks) {
1458
+ for (const op of b.ops) {
1459
+ for (const v of op.operands) {
1460
+ operandUsedValues.add(v);
1461
+ }
1462
+ for (const sc of op.successors) {
1463
+ for (const v of sc.args) {
1464
+ argUsedValues.add(v);
1465
+ }
1466
+ }
1467
+ }
1468
+ }
1469
+ }
1470
+ const onlyFeedsBlockParams = (v: Value): boolean => argUsedValues.has(v) && !operandUsedValues.has(v);
230
1471
  // Decide in REVERSE program order so a consumer's own materialization is settled before any
231
1472
  // producer asks for its emit position (SSA: uses follow defs in dominance/layout order) — and
232
1473
  // iterate to a fixpoint for IR whose block layout does not follow dominance (hand-built IR):
@@ -235,6 +1476,7 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
235
1476
  for (let sizeBefore = -1; sizeBefore !== materialize.size;) {
236
1477
  sizeBefore = materialize.size;
237
1478
  emitPosCache.clear();
1479
+ emitPosSetCache.clear(); // both render-position caches read `materialize`, which just grew
238
1480
  for (let bi = fn.blocks.length - 1; bi >= 0; bi--) {
239
1481
  const b = fn.blocks[bi];
240
1482
  for (let oi = b.ops.length - 1; oi >= 0; oi--) {
@@ -258,15 +1500,78 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
258
1500
  // across `foo(...)` calls). WITHOUT a call in its live range the const is instead cheaply
259
1501
  // re-materialized at each use (a bare `movs r, #0` per init), so materializing it would
260
1502
  // ADD pointless copies and MISS — hence the call gate (the small-constant regression).
261
- // Cheap deref casts still land on the `index` node at the use, preserving byte strides;
262
- // NON-const pure ops are excluded (an address computation `&g + i` rendered standalone
263
- // loses the memAccess's inline `(u8 *)` cast — cast-aware base materialization is separate).
1503
+ // Cheap deref casts still land on the `index` node at the use, preserving byte strides.
1504
+ // Second scope: a NON-const read by a sibling parallel-copy arg (`copyInterdependent`)
1505
+ // the one place a pure value's inlining is not value-identical rendering but a
1506
+ // re-derivation the copy machinery is forced into. Address cones are excluded from it
1507
+ // (an `&g + i` rendered standalone loses the memAccess's inline `(u8 *)` cast —
1508
+ // cast-aware base materialization is separate), and consts are not in it at all: a
1509
+ // re-derived const is re-materialization, which is the compiler's own behavior.
264
1510
  const pr = op.results[0];
265
1511
  if (op.opcode === 'const' && pr && useSitesOf.has(pr)) {
266
1512
  const cons = [...new Set((useSitesOf.get(pr) ?? []).map((s) => s.op))];
267
1513
  if (cons.length > 1 && liveAcrossCall(op, cons)) {
268
1514
  materialize.add(op);
269
1515
  }
1516
+ } else if (op.opcode !== 'const' && pr && copyInterdependent.has(pr) && !addressCone(op)) {
1517
+ materialize.add(op);
1518
+ }
1519
+ // Folding the FOUR AXIS scopes below into one predicate-parameterized scope is BOOKED
1520
+ // in docs/level-tower.md and deliberately unpaid; what it cannot absorb is named there,
1521
+ // along with the price the fourth one added to it (the gate duplication).
1522
+ // Third scope, under the address-home axis only (see AnalyzeOptions.homeSharedAddresses):
1523
+ // a non-const pure value whose MERGE CLASS is used only as the base of 2+ memory
1524
+ // accesses.
1525
+ if (
1526
+ homeSharedAddresses &&
1527
+ op.opcode !== 'const' &&
1528
+ pr &&
1529
+ sharedBaseClass.has(pr) &&
1530
+ !addressCone(op) &&
1531
+ !multiBlockHeaders.has(b)
1532
+ ) {
1533
+ materialize.add(op);
1534
+ axisHomedBases.add(pr);
1535
+ }
1536
+ // Fourth scope, under the loop-expression-home axis (AnalyzeOptions.homeLoopExprs): a
1537
+ // pure non-const value with 2+ distinct consumers, at least one of them inside a loop the
1538
+ // def sits outside. Shared bases stay the previous scope's (its load rule needs the
1539
+ // registration).
1540
+ if (
1541
+ homeLoopExprs &&
1542
+ op.opcode !== 'const' &&
1543
+ pr &&
1544
+ !usedOnlyAsSharedBase(pr) &&
1545
+ loopSharedConsumers(pr, b) &&
1546
+ !addressCone(op) &&
1547
+ !multiBlockHeaders.has(b)
1548
+ ) {
1549
+ materialize.add(op);
1550
+ }
1551
+ // Fifth scope, under the derived-read-home axis (AnalyzeOptions.homeDerivedReads): a
1552
+ // pure non-const value with 2+ consumers standing on a memory read. Shared bases stay
1553
+ // the third scope's and values consumed across a loop the fourth's; what this one adds
1554
+ // is the straight-line case, which neither reaches.
1555
+ if (
1556
+ homeDerivedReads &&
1557
+ op.opcode !== 'const' &&
1558
+ pr &&
1559
+ !usedOnlyAsSharedBase(pr) &&
1560
+ !rendersAsAddress(op) &&
1561
+ multiConsumer(pr) &&
1562
+ standsOnMovableRead(op, b) &&
1563
+ !multiBlockHeaders.has(b)
1564
+ ) {
1565
+ materialize.add(op);
1566
+ }
1567
+ // Sixth scope, under the merge-feed-home axis (AnalyzeOptions.homeMergeFeeds) —
1568
+ // `mergeFeedHomes` above. The only one of the FOUR AXIS scopes that admits a `const`; the
1569
+ // other const clientele is the first scope, a const live across a call. For the sibling
1570
+ // axes a re-derived const is re-materialization, the compiler's own behavior, while a
1571
+ // const the arms of a branch merge is one it held in a register across them
1572
+ // (`mov r5, #0` once, not per arm).
1573
+ if (homeMergeFeeds && mergeFeedOps.has(op)) {
1574
+ materialize.add(op);
270
1575
  }
271
1576
  continue;
272
1577
  }
@@ -274,6 +1579,18 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
274
1579
  if (!r || !useSitesOf.has(r)) {
275
1580
  continue;
276
1581
  } // dead call → exprstmt (unchanged)
1582
+ // Under the value-home axis: which named global cell this op reads, if any. A constant-
1583
+ // offset `load` only — an `aload`'s runtime index names no single cell, and a call reads
1584
+ // everything. Null ⇒ every write bars, exactly as before.
1585
+ const cell =
1586
+ rereadGlobals && defs && op.opcode === 'load'
1587
+ ? globalCellOf(defs, op.operands[0], op.attrs.off as number)
1588
+ : null;
1589
+ const barsThisRead = cell && defs && !volatileGlobal?.(cell.name) ? mayWriteGlobal(defs, cell.name) : null;
1590
+ if (materializeJoinFeeds && op.opcode === 'load' && condBrArgFed.has(r)) {
1591
+ materialize.add(op);
1592
+ continue;
1593
+ }
277
1594
  const sites = useSitesOf.get(r)!;
278
1595
  const consumers = [...new Set(sites.map((s) => s.op))];
279
1596
  const isCall = op.opcode === 'call';
@@ -282,54 +1599,101 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
282
1599
  materialize.add(op);
283
1600
  continue;
284
1601
  }
1602
+ // …and ONCE means once on EVERY path the asm runs it on, which the multi-site rule above
1603
+ // does not say. `anchored` calls a terminator a single render position, but a branch's edge
1604
+ // copies are emitted inside the ARMS, so a call whose only consumer is an edge argument
1605
+ // renders in one arm and is skipped on the others. Compiled: `s32 t = f2(a); if (a > 0) {
1606
+ // return t; } return 0;` gives `bl f2` ahead of the `cmp`, and inlined at the edge the
1607
+ // recovered C calls `f2` only in the `else`; a `switch_br` arm hides it the same way.
1608
+ // Materializing puts it back at the position the asm executed it. Sole-use only in
1609
+ // practice — a second use already materialized above — and it is 0 of 2288 sa3 functions,
1610
+ // 2 of 412 klonoa ones.
1611
+ if (isCall && branchArgFed.has(r)) {
1612
+ materialize.add(op);
1613
+ continue;
1614
+ }
1615
+ // Live across a LOOP neither side belongs to: the access ran before the loop and the
1616
+ // value crossed it in a callee-saved register (hipress's `keep = p[1]`, homed in r8 and
1617
+ // touched only by `mov`). Rendering at the use would re-schedule the access to the far
1618
+ // side of the loop — the same refusal liveAcrossCall makes for a call, applied to a loop.
1619
+ if (liveAcrossLoop(op, r, consumers)) {
1620
+ materialize.add(op);
1621
+ continue;
1622
+ }
1623
+ // ── DEF-BLOCK PLACEMENT (readsStayWhereWritten; see AnalyzeOptions) ──────────────────
1624
+ // Every render in a block this one strictly dominates, with a branch between ⇒ the asm
1625
+ // read once above that branch, and re-spelling the read there reproduces it. ONE render
1626
+ // suffices — the short-circuit-into-a-call shape has exactly one — and an unresolvable
1627
+ // render position refuses, as everywhere else. Both memory reads, spelled positively: a
1628
+ // `call` is the enclosing arm's other member and has its own execute-once rules above.
1629
+ if (
1630
+ (op.opcode === 'load' || op.opcode === 'aload') &&
1631
+ readsStayWhereWritten &&
1632
+ dom &&
1633
+ !multiBlockHeaders.has(b) &&
1634
+ !shortCircuitGuarded.has(r) &&
1635
+ !onlyFeedsBlockParams(r)
1636
+ ) {
1637
+ const at = consumers.map((c) => emitPos(c));
1638
+ const rb = at.some((p) => p === null) ? null : [...new Set(at.map((p) => p!.blk))];
1639
+ if (
1640
+ rb &&
1641
+ rb.length > 0 &&
1642
+ rb.every((x) => x !== b && dom.get(x)!.has(b)) &&
1643
+ !preheaderOfRenderLoop(loopBodies, b, rb) &&
1644
+ !fallThroughSeam(predsOf, b, rb)
1645
+ ) {
1646
+ materialize.add(op);
1647
+ continue;
1648
+ }
1649
+ }
1650
+ // Address-home axis: a multi-render load THROUGH a base this axis homed re-reads what the
1651
+ // asm read once into the register the home just reproduced — home the value too, at the
1652
+ // load's own position. Only through axis-homed bases (the fixpoint's later sweep sees them
1653
+ // even though reverse order visits the load first); the general multi-render re-read stays
1654
+ // the default rule below. axisHomedBases registers on the same sweep that materializes the
1655
+ // base — safe because no other rule can pre-empt a value the axis would home: base-slot-only
1656
+ // means no successor-arg use (outside copyInterdependent's read set), and the axis's scope
1657
+ // excludes consts, the const arm's only clientele.
1658
+ if (
1659
+ homeSharedAddresses &&
1660
+ op.opcode === 'load' &&
1661
+ consumers.length > 1 &&
1662
+ axisHomedBases.has(op.operands[0]) &&
1663
+ !multiBlockHeaders.has(b)
1664
+ ) {
1665
+ materialize.add(op);
1666
+ continue;
1667
+ }
285
1668
  // A MULTI-RENDER load re-reads memory at each render — which is exactly what the original
286
1669
  // per-use source spelling did (`while (*s != EOS) *d = *s;` reads *s twice per iteration),
287
1670
  // so it is sound iff every render still sees the def-time memory: NO write anywhere
288
1671
  // between the def and ANY render (cycle-aware, conservative write set). Otherwise a temp.
289
- if (!isCall && consumers.length > 1) {
290
- const MW = new Set(['store', 'astore', 'call', 'opaque']);
291
- const wDirty = (list: Op[], from: number, to: number) => {
292
- for (let k = from; k < to; k++) {
293
- if (MW.has(list[k].opcode)) {
294
- return true;
295
- }
296
- }
297
- return false;
298
- };
299
- const defToRenderDirty = (q: { blk: Block; idx: number }): boolean => {
300
- // Same block: the only def-avoiding path is the straight line between the two indices
301
- // (leaving and re-entering the block re-crosses the def).
302
- if (q.blk === b && oi < q.idx) {
303
- return wDirty(b.ops, oi + 1, q.idx);
304
- }
305
- if (wDirty(b.ops, oi + 1, b.ops.length) || wDirty(q.blk.ops, 0, q.idx)) {
306
- return true;
307
- }
308
- const between = reachAvoiding(b, b);
309
- for (const x of between) {
310
- if (x === q.blk && !reachAvoiding(q.blk, b).has(q.blk)) {
311
- continue;
312
- } // acyclic render blk: head checked
313
- if (x !== q.blk && !reachAvoiding(x, b).has(q.blk)) {
314
- continue;
315
- } // not on a def→render path
316
- if (wDirty(x.ops, 0, x.ops.length)) {
317
- return true;
318
- }
319
- }
320
- return false;
321
- };
322
- const poss = consumers.map((c) => emitPos(c));
323
- if (poss.some((p) => p === null) || poss.some((p) => defToRenderDirty(p!))) {
324
- materialize.add(op);
325
- }
1672
+ //
1673
+ // WHERE it renders. Without the axis: one position per consumer, and a consumer with no
1674
+ // single position (its own value renders in several places) refuses. With the axis a load
1675
+ // resolves the whole SET instead the second half of the value-home defect, where the
1676
+ // local is invented not by a barrier but because the pure expression downstream is itself
1677
+ // duplicated (`gOut = (gValue << 1) + gValue; return (gValue << 1) + gValue;`). Never for a
1678
+ // call: several positions there mean several executions.
1679
+ const poss =
1680
+ rereadGlobals && !isCall
1681
+ ? emitPositions(op)
1682
+ : consumers.length > 1
1683
+ ? consumers.map((c) => emitPos(c))
1684
+ : [emitPos(consumers[0])];
1685
+ if (!poss || poss.some((p) => p === null)) {
1686
+ materialize.add(op);
326
1687
  continue;
327
1688
  }
328
- const pos = emitPos(consumers[0]);
329
- if (!pos) {
330
- materialize.add(op);
1689
+ if (poss.length > 1) {
1690
+ const isWrite = barsThisRead ?? ((x: Op) => EFFECTFUL_OPS.has(x.opcode));
1691
+ if (poss.some((p) => memWriteBetween(op, p!, isWrite))) {
1692
+ materialize.add(op);
1693
+ }
331
1694
  continue;
332
1695
  }
1696
+ const pos = poss[0]!;
333
1697
  // A between-op is a BARRIER when it renders as a sequenced statement the def would cross:
334
1698
  // stores/opaque always; a call/load that is dead (statement), materialized (statement), or
335
1699
  // inlined into a DIFFERENT statement. A sibling effect inlined into the SAME statement is
@@ -337,18 +1701,16 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
337
1701
  // exactly as it originally chose to. Loads never bar a load (reads don't conflict).
338
1702
  const samePos = (q: { blk: Block; idx: number } | null) => q !== null && q.blk === pos.blk && q.idx === pos.idx;
339
1703
  const isBarrier = (x: Op): boolean => {
1704
+ // Value-home axis: a store/astore this read is PROVABLY disjoint from (a different named
1705
+ // global) does not sequence against it, so the read may still render at its use.
1706
+ if (barsThisRead && (x.opcode === 'store' || x.opcode === 'astore') && !barsThisRead(x)) {
1707
+ return false;
1708
+ }
340
1709
  if (x.opcode === 'store') {
341
- // A store to a PROVABLY-DISJOINT slot of the same base never aliases the load: same
342
- // base SSA value, both constant offset+width, ranges non-overlapping (the everyday
343
- // struct interleave `… = p->field_0; p->field_4 = …`). Anything less certain bars.
344
- if (!isCall && op.opcode === 'load' && x.operands[0] === op.operands[0]) {
345
- const lo = op.attrs.off as number,
346
- lw = op.attrs.width as number;
347
- const so = x.attrs.off as number,
348
- sw = x.attrs.width as number;
349
- if (so + sw <= lo || lo + lw <= so) {
350
- return false;
351
- }
1710
+ // A store to a PROVABLY-DISJOINT slot of the same base never aliases the load
1711
+ // (`disjointConstSlots`, ir/alias.ts). Anything less certain bars.
1712
+ if (!isCall && op.opcode === 'load' && disjointConstSlots(op, x)) {
1713
+ return false;
352
1714
  }
353
1715
  return true;
354
1716
  }
@@ -368,84 +1730,18 @@ export function analyze(fn: Fn, returnsVoid: boolean): StructureAnalysis {
368
1730
  }
369
1731
  return false;
370
1732
  };
371
- const gapDirty = (list: Op[], from: number, to: number) => {
372
- for (let k = from; k < to; k++) {
373
- if (isBarrier(list[k])) {
374
- return true;
375
- }
376
- }
377
- return false;
378
- };
379
- if (pos.blk === b) {
380
- if (gapDirty(b.ops, oi + 1, pos.idx)) {
381
- materialize.add(op);
382
- }
383
- continue;
384
- }
385
- // Cross-block: a call's execution would become path-dependent — always materialize. A
386
- // load may inline only if NO write exists on any DEF-AVOIDING def→render path (a path
387
- // re-crossing the def is the next dynamic instance): the def block's tail, the render
388
- // block's head, and every block between; a render block cyclic WITHOUT passing the def
389
- // (an inner loop around the render) is checked in full.
390
- if (isCall) {
1733
+ // A CROSS-BLOCK call's execution would become path-dependent always materialize. Within
1734
+ // its own block a call is judged like everything else, by the barrier scan below.
1735
+ if (isCall && pos.blk !== b) {
391
1736
  materialize.add(op);
392
1737
  continue;
393
1738
  }
394
- let dirty = gapDirty(b.ops, oi + 1, b.ops.length) || gapDirty(pos.blk.ops, 0, pos.idx);
395
- if (!dirty) {
396
- for (const x of reachAvoiding(b, b)) {
397
- if (x === pos.blk && !reachAvoiding(pos.blk, b).has(pos.blk)) {
398
- continue;
399
- } // acyclic render block: head checked
400
- if (x !== pos.blk && !reachAvoiding(x, b).has(pos.blk)) {
401
- continue;
402
- } // not on a def→render path
403
- if (gapDirty(x.ops, 0, x.ops.length)) {
404
- dirty = true;
405
- break;
406
- }
407
- }
408
- }
409
- if (dirty) {
1739
+ // Otherwise: inline only if no barrier stands on any def-avoiding def→render path.
1740
+ if (memWriteBetween(op, pos, isBarrier)) {
410
1741
  materialize.add(op);
411
1742
  }
412
1743
  }
413
1744
  }
414
1745
  }
415
- // The def→render path discipline, exported for the bitfield fold's ordering gate
416
- // (structure.ts): may an op `isWrite` accepts execute between `def` and a statement at
417
- // `render`, on any def-avoiding path? Same cycle-aware rules as the materialize decisions
418
- // above — the def block's tail, the render block's head, and every between-block on a path;
419
- // a path re-crossing the def is the next dynamic instance and does not count.
420
- const memWriteBetween = (def: Op, render: { blk: Block; idx: number }, isWrite: (x: Op) => boolean): boolean => {
421
- const b = opBlock.get(def)!;
422
- const oi = opIndex.get(def)!;
423
- const wDirty = (list: Op[], from: number, to: number): boolean => {
424
- for (let k = from; k < to; k++) {
425
- if (isWrite(list[k])) {
426
- return true;
427
- }
428
- }
429
- return false;
430
- };
431
- if (render.blk === b && oi < render.idx) {
432
- return wDirty(b.ops, oi + 1, render.idx);
433
- }
434
- if (wDirty(b.ops, oi + 1, b.ops.length) || wDirty(render.blk.ops, 0, render.idx)) {
435
- return true;
436
- }
437
- for (const x of reachAvoiding(b, b)) {
438
- if (x === render.blk && !reachAvoiding(render.blk, b).has(render.blk)) {
439
- continue; // acyclic render block: head checked
440
- }
441
- if (x !== render.blk && !reachAvoiding(x, b).has(render.blk)) {
442
- continue; // not on a def→render path
443
- }
444
- if (wDirty(x.ops, 0, x.ops.length)) {
445
- return true;
446
- }
447
- }
448
- return false;
449
- };
450
1746
  return { useSitesOf, opIndex, opBlock, liveIn, materialize, reachFrom, emitPos, memWriteBetween };
451
1747
  }