@asmlift/core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +22 -16
  2. package/package.json +1 -1
  3. package/src/backend/c.ts +1 -0
  4. package/src/backend/cfamily.ts +238 -167
  5. package/src/backend/cpp.ts +1 -0
  6. package/src/backend/pascal.ts +26 -12
  7. package/src/contracts.ts +194 -39
  8. package/src/declare.ts +41 -4
  9. package/src/frontend/mips.ts +11 -0
  10. package/src/frontend/ppc.ts +43 -7
  11. package/src/frontend/ssa.ts +404 -29
  12. package/src/frontend/thumb.ts +2176 -686
  13. package/src/ir/alias.ts +54 -0
  14. package/src/ir/bits.ts +75 -0
  15. package/src/ir/core.ts +337 -2
  16. package/src/ir/opcodes.ts +140 -21
  17. package/src/ir/parse.ts +19 -2
  18. package/src/ir/print.ts +27 -2
  19. package/src/ir/simplify.ts +190 -3
  20. package/src/ir/struct-names.ts +42 -0
  21. package/src/ir/verify.ts +43 -49
  22. package/src/l3/address.ts +62 -0
  23. package/src/l3/argbase.ts +2 -1
  24. package/src/l3/ast.ts +464 -57
  25. package/src/l3/basecse.ts +664 -76
  26. package/src/l3/coalesce.ts +429 -43
  27. package/src/l3/dce.ts +31 -9
  28. package/src/l3/gates.ts +21 -0
  29. package/src/l3/hoist.ts +293 -14
  30. package/src/l3/homesplit.ts +285 -0
  31. package/src/l3/initfirst.ts +301 -0
  32. package/src/l3/inlinebase.ts +193 -0
  33. package/src/l3/mentions.ts +113 -0
  34. package/src/l3/mulfirst.ts +42 -0
  35. package/src/l3/nearbase.ts +152 -0
  36. package/src/l3/offmember.ts +371 -0
  37. package/src/l3/parkfirst.ts +96 -0
  38. package/src/l3/pollguard.ts +154 -0
  39. package/src/l3/ptrfield.ts +227 -0
  40. package/src/l3/regspell.ts +110 -85
  41. package/src/l3/reindex.ts +715 -78
  42. package/src/l3/scopebase.ts +644 -218
  43. package/src/l3/sinkinit.ts +40 -0
  44. package/src/l3/slotorder.ts +123 -0
  45. package/src/l3/storage.ts +48 -0
  46. package/src/l3/symbol-refs.ts +41 -8
  47. package/src/l3/tailmerge.ts +15 -0
  48. package/src/l3/typing.ts +198 -9
  49. package/src/l3/unmerge.ts +263 -0
  50. package/src/l3/unreduce.ts +971 -0
  51. package/src/l3/volatileptr.ts +207 -0
  52. package/src/l3/volatileval.ts +130 -0
  53. package/src/l3/volstore.ts +229 -0
  54. package/src/l3/zerosub.ts +62 -0
  55. package/src/pattern/engine.ts +236 -13
  56. package/src/pipeline.ts +157 -56
  57. package/src/proto.ts +112 -14
  58. package/src/raise/arrays.ts +6 -1
  59. package/src/raise/divpow2.ts +2 -2
  60. package/src/raise/globalshape.ts +1038 -0
  61. package/src/raise/gvn.ts +33 -18
  62. package/src/raise/latch.ts +126 -0
  63. package/src/raise/memberarrays.ts +594 -0
  64. package/src/raise/narrow.ts +124 -0
  65. package/src/raise/narrowlocal.ts +556 -0
  66. package/src/raise/paramwidth.ts +179 -0
  67. package/src/raise/pre-recovery.ts +97 -14
  68. package/src/raise/recover.ts +56 -23
  69. package/src/raise/retsink.ts +210 -10
  70. package/src/raise/shortcircuit.ts +474 -74
  71. package/src/raise/struct-arrays.ts +19 -2
  72. package/src/raise/structs.ts +33 -3
  73. package/src/rank-axes.ts +630 -0
  74. package/src/rank-declare.ts +256 -0
  75. package/src/rank.ts +1723 -272
  76. package/src/structure/analysis.ts +1392 -141
  77. package/src/structure/bitfields.ts +332 -0
  78. package/src/structure/globalaccess.ts +274 -0
  79. package/src/structure/hazards.ts +411 -20
  80. package/src/structure/loops.ts +2 -49
  81. package/src/structure/namecoalesce.ts +435 -0
  82. package/src/structure/structure.ts +2678 -526
  83. package/src/structure/switch-recover.ts +616 -144
  84. package/src/symbols.ts +62 -1
  85. package/src/target.ts +367 -24
  86. package/src/trace.ts +111 -32
package/src/contracts.ts CHANGED
@@ -3,10 +3,19 @@
3
3
  // decompileRanked / decompileWithReport).
4
4
  // A pass that regresses fails AT its boundary with a diagnostic, not three stages later as
5
5
  // wrong C.
6
- import { type Block, type Fn, type Value, successorsOf } from './ir/core';
6
+ import { type Fn, type Value, reachableBlocks } from './ir/core';
7
7
  import { type IrType, typeToString } from './ir/types';
8
8
  import type { BinOp, Expr, SFn, Stmt } from './l3/ast';
9
- import { exprChildren, fieldSpellsDot, gapReasonFor, stmtChildren, stmtExprs } from './l3/ast';
9
+ import {
10
+ exprChildren,
11
+ fieldSpellsDot,
12
+ gapReasonFor,
13
+ mapExprChildren,
14
+ stmtChildren,
15
+ stmtExprs,
16
+ stmtLists,
17
+ walkExprs,
18
+ } from './l3/ast';
10
19
  import { declaredTypes, exprCType } from './l3/typing';
11
20
 
12
21
  export class ContractError extends Error {
@@ -40,20 +49,35 @@ export function assertTypesRecovered(fn: Fn): void {
40
49
  }
41
50
  }
42
51
 
43
- /** Post structuring: the AST must reference no unresolved value. The structurer emits the
44
- * sentinel var `"?"` when it cannot resolve a value (a dropped def, or an opcode it has no
45
- * lowering for) — which would print as uncompilable source. Fail at the structuring boundary
46
- * instead of emitting garbage. */
52
+ /** Post structuring: the AST must reference no unresolved name. The structurer emits the sentinel
53
+ * var `"?"` when it cannot resolve a value (a dropped def, or an opcode it has no lowering for),
54
+ * which would print as uncompilable source. Fail at the boundary instead of emitting garbage.
55
+ *
56
+ * `undefined` is the same failure from the other side — not a spelling the structurer chooses
57
+ * (`Expr` declares `name: string`) but a `varName.get(v)!` whose value was never adopted, printing
58
+ * as the token `undefined`. Both are checked on every ROUTE a name takes into the AST, and those
59
+ * are not all expressions: `var` / `addr` / `field` / `call` carry one, and so does an `assign`'s
60
+ * DESTINATION — a bare string field the expression walk never reaches. */
47
61
  export function assertResolved(sfn: SFn): void {
48
62
  // Derived from the shared exprChildren/stmtExprs/stmtChildren traversal so no statement kind
49
63
  // can be missed. A gap `marker` is annotate-mode's DESIGNED spelling of an unresolved value
50
- // ("resolved" by construction); only its args could still hide a stray `"?"` — and args are
64
+ // ("resolved" by construction); only its args could still hide a stray name — and args are
51
65
  // exactly its children.
52
- const badExpr = (e: Expr): boolean => (e.k === 'var' && e.name === '?') || exprChildren(e).some(badExpr);
53
- const badStmt = (s: Stmt): boolean => stmtExprs(s).some(badExpr) || stmtChildren(s).some(badStmt);
66
+ const badName = (n: string | undefined): boolean => n === '?' || n === undefined;
67
+ // Every Expr kind that CARRIES a name, not just `var` — each is read through the same
68
+ // `map.get(d)!` / `attrs.x as string` and prints straight into the source. `carriesName` is asked
69
+ // separately because an ABSENT name is the case being caught: keying off `nameOf` alone refuses nothing.
70
+ const carriesName = (e: Expr): boolean => e.k === 'var' || e.k === 'addr' || e.k === 'field' || e.k === 'call';
71
+ const nameOf = (e: Expr): string | undefined =>
72
+ e.k === 'call' ? e.fn : e.k === 'marker' ? undefined : (e as { name?: string }).name;
73
+ const badExpr = (e: Expr): boolean => (carriesName(e) && badName(nameOf(e))) || exprChildren(e).some(badExpr);
74
+ // An `assign`'s DESTINATION is a bare string field, so the expression walk never reaches it.
75
+ const badStmt = (s: Stmt): boolean =>
76
+ (s.k === 'assign' && badName(s.name)) || stmtExprs(s).some(badExpr) || stmtChildren(s).some(badStmt);
54
77
  if (sfn.body.some(badStmt)) {
55
78
  throw new ContractError(
56
- `structuring left an unresolved value ('?') in '${sfn.name}' — a dropped def or unlowered opcode`,
79
+ `structuring left an unresolved name ('?' or one never adopted) in '${sfn.name}' — ` +
80
+ `a dropped def, an unlowered opcode, or a name the structurer assumed the naming pipeline gave it`,
57
81
  );
58
82
  }
59
83
  }
@@ -154,15 +178,7 @@ function countCalls(stmts: Stmt[]): { total: CallCounts; path: CallCounts } {
154
178
  */
155
179
  export function assertEffectsPreserved(fn: Fn, sfn: SFn): void {
156
180
  // Reachable blocks only: an unreachable block's call is legitimately never emitted.
157
- const seen = new Set<Block>([fn.blocks[0]]);
158
- for (const stack = [fn.blocks[0]]; stack.length;) {
159
- for (const s of successorsOf(stack.pop()!)) {
160
- if (!seen.has(s)) {
161
- seen.add(s);
162
- stack.push(s);
163
- }
164
- }
165
- }
181
+ const seen = reachableBlocks(fn);
166
182
  const irCalls: CallCounts = new Map();
167
183
  // Unmodelled instructions, by the mnemonic the frontend stamped. Same "never dropped" property as
168
184
  // a call, and it needs its own tally because an `opaque` carries no `target`.
@@ -186,17 +202,11 @@ export function assertEffectsPreserved(fn: Fn, sfn: SFn): void {
186
202
  // only mode with no other backstop against a silently dropped opaque.
187
203
  if (irOpaques.size) {
188
204
  const emitted = new Set<string>();
189
- const we = (e: Expr): void => {
205
+ for (const e of walkExprs(sfn.body)) {
190
206
  if (e.k === 'marker') {
191
207
  emitted.add(e.reason);
192
208
  }
193
- exprChildren(e).forEach(we);
194
- };
195
- const ws = (s: Stmt): void => {
196
- stmtExprs(s).forEach(we);
197
- stmtChildren(s).forEach(ws);
198
- };
199
- sfn.body.forEach(ws);
209
+ }
200
210
  for (const reason of irOpaques) {
201
211
  if (!emitted.has(reason)) {
202
212
  throw new ContractError(
@@ -222,6 +232,155 @@ export function assertEffectsPreserved(fn: Fn, sfn: SFn): void {
222
232
  }
223
233
  }
224
234
 
235
+ /** Post structuring: a local the body READS must be WRITTEN somewhere in it. A materialized value
236
+ * renders as one `v = …` statement at its def's position while every use reads the bare name, so
237
+ * any pass that DISCARDS the statement's position — a collapsed switch test block, a suppressed
238
+ * edge copy — leaves the reads standing over whatever the register allocator left behind. That is
239
+ * the one wrongness the byte differ rewards rather than catches: the candidate compiles, scores,
240
+ * and can win.
241
+ *
242
+ * PRESENCE, not reaching definitions. The stronger question needs path sensitivity through
243
+ * `switch` fall-through, `do-while` and `break`, where a false positive DECLINES a function that
244
+ * is fine; assigned nowhere at all needs none of that and has no legitimate producer. Two local
245
+ * kinds are exempt and both say so in their declaration: an `uninit` local stands on an `undef`,
246
+ * where the missing assignment IS the recovery, and a `frame` local is the machine's own slot,
247
+ * whose store the readability passes between here and L3 may have dropped. */
248
+ export function assertLocalsWritten(sfn: SFn): void {
249
+ const suspect = new Set(sfn.locals.filter((l) => !l.frame && !l.uninit).map((l) => l.name));
250
+ if (!suspect.size) {
251
+ return;
252
+ }
253
+ const read = new Set<string>();
254
+ const written = new Set<string>();
255
+ // `&v` is a write channel this walk cannot follow — the callee/store behind it may fill the
256
+ // object — so it counts as one.
257
+ const walkExpr = (e: Expr): void => {
258
+ if ((e.k === 'var' || e.k === 'addr') && suspect.has(e.name)) {
259
+ (e.k === 'addr' ? written : read).add(e.name);
260
+ }
261
+ exprChildren(e).forEach(walkExpr);
262
+ };
263
+ const walkStmt = (st: Stmt): void => {
264
+ if (st.k === 'assign' && suspect.has(st.name)) {
265
+ written.add(st.name);
266
+ }
267
+ stmtExprs(st).forEach(walkExpr);
268
+ stmtChildren(st).forEach(walkStmt);
269
+ };
270
+ sfn.body.forEach(walkStmt);
271
+ const orphans = [...read].filter((n) => !written.has(n));
272
+ if (orphans.length) {
273
+ throw new ContractError(
274
+ `structuring emitted local(s) ${orphans.map((n) => `'${n}'`).join(', ')} in '${sfn.name}' read but ` +
275
+ `never assigned — a def whose assignment no render position emitted`,
276
+ );
277
+ }
278
+ }
279
+
280
+ /** Post-lever: every read of a MINTED local — its ADDRESS being taken included — must sit where
281
+ * that local's assignment has already run.
282
+ *
283
+ * THE failure a placing lever can ship, and the only one the byte differ rewards: a base local whose
284
+ * assignment does not reach a use is a DIFFERENT VARIABLE — C that compiles, scores, and can win
285
+ * (the shape #106 shipped). `contracts.ts`'s `assertLocalsWritten` does not see it: it accumulates
286
+ * reads and writes as SETS over the whole body, so a local assigned in one arm and read after the
287
+ * `if` is written somewhere and passes.
288
+ *
289
+ * Checked on the EMITTED tree rather than argued from the plan, because the plan is what a bug
290
+ * would be in. `rank.ts`'s `respell` catches the throw and drops the candidate, so the wrong
291
+ * answer becomes a reported lever error instead of a scored spelling.
292
+ *
293
+ * IT LIVES HERE, beside `assertLocalsWritten`, because it has that check's population and that
294
+ * check's call site: levers that place a def — l3/sinkinit.ts, l3/basecse.ts's first-use policy,
295
+ * l3/nearbase.ts, l3/reindex.ts, l3/scopebase.ts, l3/argbase.ts — are the population that can
296
+ * produce the failure, so the check belongs on every lever tree rather than on one lever's.
297
+ *
298
+ * Called ABSOLUTELY by the placing levers that put an init inside a nested list, each over its own
299
+ * plan; everywhere else it is reached through `assertPlacementSurvives` below, which is a
300
+ * DIFFERENTIAL — so a placement no lever's tree ever satisfied is not judged, and a lever that
301
+ * mints nothing is not judged at all.
302
+ *
303
+ * A nested list gets a COPY of the reaching set, so an assignment inside one arm does not count as
304
+ * reaching anything after the `if`. */
305
+ export function assertHoistsDominate(sfn: SFn, minted: ReadonlySet<string>): void {
306
+ if (minted.size === 0) {
307
+ return;
308
+ }
309
+ const readUndominated = (e: Expr, live: ReadonlySet<string>): string | null => {
310
+ // `&p` COUNTS, the same mention the placing passes query on (l3/hoist.ts): the address is what
311
+ // a callee reads the cell through, so an init has to precede it as surely as it must precede a
312
+ // read.
313
+ if ((e.k === 'var' || e.k === 'addr') && minted.has(e.name) && !live.has(e.name)) {
314
+ return e.name;
315
+ }
316
+ let bad: string | null = null;
317
+ mapExprChildren(e, (c) => {
318
+ bad ??= readUndominated(c, live);
319
+ return c;
320
+ });
321
+ return bad;
322
+ };
323
+ const judge = (heads: readonly Expr[], live: ReadonlySet<string>): void => {
324
+ for (const e of heads) {
325
+ const bad = readUndominated(e, live);
326
+ if (bad) {
327
+ throw new ContractError(
328
+ `'${sfn.name}' reads '${bad}' where its assignment does not reach — ` +
329
+ `a def placed below a use it claims to serve`,
330
+ );
331
+ }
332
+ }
333
+ };
334
+ const walk = (list: Stmt[], live: Set<string>): void => {
335
+ for (const st of list) {
336
+ // A `for`'s INIT runs once, before the condition, the inc and the body — so its assignment
337
+ // reaches all three, and the loop's own parts are statements with their own nested lists.
338
+ // `l3/reindex.ts` mints an induction variable whose ONLY def is that init, so reading the
339
+ // `for` as one flat head list rejects every counted walk it spells.
340
+ if (st.k === 'for') {
341
+ walk([st.init], live);
342
+ judge(stmtExprs(st), live);
343
+ walk([st.inc], new Set(live));
344
+ walk(st.body, new Set(live));
345
+ continue;
346
+ }
347
+ judge(stmtExprs(st), live);
348
+ for (const child of stmtLists(st)) {
349
+ walk(child, new Set(live));
350
+ }
351
+ if (st.k === 'assign' && minted.has(st.name)) {
352
+ live.add(st.name);
353
+ }
354
+ }
355
+ };
356
+ walk(sfn.body, new Set());
357
+ }
358
+
359
+ /** The same guarantee across a re-spelling that MOVES statements over a placement another pass
360
+ * already made — `rank.ts`'s statement shapes (`/initfirst`, `/pollguard`, `/pollread`), derived
361
+ * onto every lever tree after the lever placed its defs, and the lever-on-lever compositions in
362
+ * the same file where a def-moving pass (`sinkInitsToFirstUse`, `nearBaseClusters`,
363
+ * `reindexWalks`) runs on a tree a placing lever built. `pollReads` folds a materialized re-read
364
+ * back into a loop condition, which is exactly such a move.
365
+ *
366
+ * A DIFFERENTIAL, which is what makes it safe on every lever: the walk judges the reshaped tree
367
+ * only where it already described the unshaped one, so a placement it cannot model (a def inside
368
+ * a loop body read earlier in the same body is assigned on every iteration but the first) is not
369
+ * judged either way. `minted` may name a local `before` does not carry — a mover mints its own —
370
+ * and that one is judged absolutely, which is the same thing: a name absent from `before` is
371
+ * never read there. */
372
+ export function assertPlacementSurvives(before: SFn, after: SFn, minted: ReadonlySet<string>): void {
373
+ if (minted.size === 0) {
374
+ return;
375
+ }
376
+ try {
377
+ assertHoistsDominate(before, minted);
378
+ } catch {
379
+ return;
380
+ }
381
+ assertHoistsDominate(after, minted);
382
+ }
383
+
225
384
  /** Post structuring: the AST's memory accesses and operators must be SPELLABLE — a `field`
226
385
  * node's base a pointer-to-struct (`->`) or a struct value (`.`, an array element) carrying
227
386
  * that field; no pointer operand under an operator C rejects; and every SCALAR `index` node's
@@ -249,7 +408,7 @@ export function assertDerefsTyped(sfn: SFn): void {
249
408
  }
250
409
  }
251
410
  // Ops C rejects outright on a pointer operand (the additive ops and &&/|| are legal C).
252
- const NO_PTR_OPS = new Set<BinOp>(['&', '|', '^', '<<', '>>', '>>>', '*', '/', '%']);
411
+ const NO_PTR_OPS = new Set<BinOp>(['&', '|', '^', '<<', '>>', '>>>', '*', '/', '/u', '%', '%u']);
253
412
  // The comparison operators — where a bare `&SYM` operand is SIGN-ambiguous, not ill-formed.
254
413
  const CMP_OPS = new Set(['<', '<=', '>', '>=', '==', '!=']);
255
414
  // 1/2/4 only: the decomp typedef vocabulary (C_TYPEDEFS) has no 64-bit scalar, so a width-8
@@ -259,11 +418,13 @@ export function assertDerefsTyped(sfn: SFn): void {
259
418
  // Dot-form field bases (struct-array elements) carry the struct STRIDE as their width — any
260
419
  // stride matching the element size is legal there (the tree-level struct cast governs the
261
420
  // spelling; a stride/size MISMATCH types scalar in exprCType and the field rule flags it).
262
- // Collected as fields are visited, BEFORE recursing into their children. Identity-keyed: a
263
- // future subtree-SHARING pass (CSE-style) would leak the exemption to aliased bare uses —
264
- // trees are freshly built per node today (structure.ts), which this relies on.
421
+ // Collected as fields are visited, BEFORE recursing into their children which is what makes
422
+ // `walkExprs`' PRE-ORDER load-bearing here rather than incidental: the exemption is recorded on
423
+ // the `field` node and read at the `index` node beneath it. Identity-keyed: a future
424
+ // subtree-SHARING pass (CSE-style) would leak the exemption to aliased bare uses — trees are
425
+ // freshly built per node today (structure.ts), which this relies on.
265
426
  const structElem = new Set<Expr>();
266
- const checkExpr = (e: Expr): void => {
427
+ for (const e of walkExprs(sfn.body)) {
267
428
  if (e.k === 'index' && !structElem.has(e) && !SCALAR_WIDTHS.has(e.width)) {
268
429
  bad.push(`index width ${e.width} is not a C scalar width`);
269
430
  }
@@ -323,13 +484,7 @@ export function assertDerefsTyped(sfn: SFn): void {
323
484
  }
324
485
  }
325
486
  }
326
- exprChildren(e).forEach(checkExpr);
327
- };
328
- const checkStmt = (s: Stmt): void => {
329
- stmtExprs(s).forEach(checkExpr);
330
- stmtChildren(s).forEach(checkStmt);
331
- };
332
- sfn.body.forEach(checkStmt);
487
+ }
333
488
  if (bad.length) {
334
489
  throw new ContractError(
335
490
  `structuring emitted ill-typed C in '${sfn.name}': ${bad[0]}${bad.length > 1 ? ` (+${bad.length - 1} more)` : ''}`,
package/src/declare.ts CHANGED
@@ -29,7 +29,25 @@
29
29
  // field) can only LOSE score — the target bytes derive from the truth decls, so a
30
30
  // divergent compile can never false-match. Exception two is the NAME-ONLY data symbol
31
31
  // (`extern u32 name;` — see the default case): required to reproduce symtab-only map
32
- // rows outside project headers, justified by the same only-loses-score argument.
32
+ // rows outside project headers.
33
+ //
34
+ // WHERE THE ONLY-LOSES-SCORE ARGUMENT STOPS. It rests on the target bytes coming from the
35
+ // project's own TRUTH declarations, so a divergent decl compiles to different bytes and simply
36
+ // scores worse. The line is not map-derived vs. synthesized, it is whether the ref carries
37
+ // `access`: that field is read out of the candidate's own IR — the very asm it is then scored
38
+ // against — so a declaration wearing it is FITTED and can only manufacture agreement. Every
39
+ // `synthesized` ref can wear it, and so can a MAP-KNOWN name whose map entry has no shape
40
+ // (symtab-only projects), which is the one fitted case `synthesized` does not mark. Measured
41
+ // over the 252 real benchmark rows with their vendored maps: fitted-and-marked 2, fitted-but-
42
+ // unmarked 0 — so the marker covers today's population, and a symtab-only project is where it
43
+ // would stop.
44
+ //
45
+ // A fitted declaration is a sound ARTIFACT (decls + source really do compile to those bytes) and
46
+ // an unsound CLAIM if the decls are hidden, so a consumer publishing a verdict must show the
47
+ // block beside the source. Its price, against the benchmark's own vendored maps: of 28 fitted
48
+ // NARROW declarations over the 126 rankable agbcc rows, 26 agree with the project's real
49
+ // declaration and 2 do not (27 of 28 agree on the offset-0 ACCESS WIDTH the declaration
50
+ // produces, which is the weaker question of whether the same load is emitted).
33
51
  import { type StructFieldDecl, renderStructDecl } from './backend/cfamily';
34
52
  import { T } from './ir/types';
35
53
  import type { SymbolRef } from './l3/symbol-refs';
@@ -42,6 +60,7 @@ import {
42
60
  pointeeFields,
43
61
  symbolFieldType,
44
62
  } from './symbols';
63
+ import { C_TYPEDEFS } from './target';
45
64
 
46
65
  /** The u8/s8/u16/s16/u32/s32 spelling for a 1/2/4-byte cell, or null (no faithful narrow type). */
47
66
  function intType(size: number, signed: boolean): string | null {
@@ -223,9 +242,11 @@ export function renderDeclarations(refs: SymbolRef[]): string {
223
242
  // tree performed only under a decl of that exact width (`extern u16 g;` is `sh` where
224
243
  // a guessed u32 is `sw`). Without a bare off-0 access fact, every core spelling goes
225
244
  // through `&name` casts, where any object decl is address-identical — u32 is the
226
- // fallback cell. A divergent decl can only LOSE score — the target bytes derive from
227
- // the truth decls, so a mis-declared compile can never false-match (same argument as
228
- // enumIsSigned).
245
+ // fallback cell.
246
+ // For a MAP-derived name-only symbol (symtab-only projects) the only-loses-score
247
+ // argument applies. For a `synthesized` one it does not — the width came from the
248
+ // target's own asm, so this line is a hypothesis fitted to the bytes; see the module
249
+ // note's "WHERE THE ONLY-LOSES-SCORE ARGUMENT STOPS".
229
250
  const t = access ? intType(access.width, access.signed) : null;
230
251
  lines.push(`extern ${quals(info)}${t ?? 'u32'} ${name};`);
231
252
  break;
@@ -249,3 +270,19 @@ export function macroDefinesOf(declarations: string | undefined): string {
249
270
  const lines = declarations.split('\n').filter((l) => l.startsWith('#define '));
250
271
  return lines.length ? lines.join('\n') + '\n' : '';
251
272
  }
273
+
274
+ /** THE self-declared world's compilation context: asmlift's typedef prelude followed by this
275
+ * candidate's declaration block. One composition with two callers — the cli's compile seam
276
+ * (compile-command.ts, whose probe decides whether the world is self-declared at all) and the
277
+ * webapp's wasm scorer, which is ALWAYS in it — because two hand-rolled copies of
278
+ * `C_TYPEDEFS + decls` is exactly how the two scoring worlds come to disagree about what a
279
+ * candidate was compiled in. */
280
+ export function selfDeclaredContext(declarations: string | undefined): string {
281
+ return C_TYPEDEFS + (declarations ?? '');
282
+ }
283
+
284
+ /** The same context straight from a candidate's refs — what a scorer holding `Candidate`s (the
285
+ * webapp) needs, and the one place that decides an empty ref list renders no block at all. */
286
+ export function selfDeclaredContextFor(refs: SymbolRef[] | undefined): string {
287
+ return selfDeclaredContext(refs?.length ? renderDeclarations(refs) : undefined);
288
+ }
@@ -517,6 +517,17 @@ export function lift(
517
517
  }
518
518
  });
519
519
 
520
+ // NO FRAME PARTITION IS CLAIMED, so every def-less slot read refuses (frontend/ssa.ts,
521
+ // LiveInModel). This frontend has no frame bound at all — `addiu sp,sp,±N` is transparent and
522
+ // every word sp-relative access becomes `sp@<rawOff>` — so its slot keys span O32's CALLER-owned
523
+ // register-parameter home area and the incoming stack arguments above it, where a def-less read
524
+ // is argument 5, not an uninitialised local.
525
+ //
526
+ // Claiming one needs the frame SIZE those offsets are measured against, which is not computed
527
+ // here, plus ensureParam for the register half. The ranges themselves are known: O32 reserves
528
+ // `[0,16)` as the caller-owned home area (in NEITHER range — caller-owned, but not an argument)
529
+ // with stack arguments from 16 up, which is what `mips32be.cspec`'s `<localrange>` and stack
530
+ // `<pentry offset="16">` encode.
520
531
  const ssa = makeSsaBuilder(name, blocks.length, preds);
521
532
  const { irBlocks, readVar, writeVar, paramReg } = ssa;
522
533
  const RET = target.returnReg;
@@ -353,6 +353,17 @@ export function lift(
353
353
  // it is exempted from the loud-fail below; an UNrecovered `bctr` still fails loud.
354
354
  const jts = asmData ? recoverPpcJumpTables(instrs, asmData) : new Map<number, PpcJT>();
355
355
  const recoveredBctr = new Set([...jts.values()].map((j) => j.bctrAddr));
356
+ // A data reloc on an immediate-forming instruction means objdump printed a LINK-TIME
357
+ // placeholder (`lis r4,0` + R_PPC_ADDR16_HA sym): the real value is the symbol's half, and
358
+ // lifting the 0 silently reads the wrong address — plausible-but-wrong C, the forbidden class.
359
+ // The jump-table idiom's own @tbl pair never reaches these guards: a recovered dispatch block
360
+ // is the bounds branch's replaced fall-through, pruned as unreachable before decode.
361
+ const relocPlaceholder = (ins: Instr): void => {
362
+ throw new PpcUnsupportedError(
363
+ `cannot lift '${name}': '${ins.mnemonic}' at 0x${ins.addr.toString(16)} carries a data relocation ` +
364
+ `('${ins.sym}') — the printed immediate is a link-time placeholder, not the value`,
365
+ );
366
+ };
356
367
  // TRUSTWORTHINESS: fail loud on an unmodelled control transfer rather than dropping it (which
357
368
  // would silently miscompile the control flow). CTR-counted loops and indirect branches land here.
358
369
  for (const ins of instrs) {
@@ -573,17 +584,17 @@ export function lift(
573
584
  for (let k = 0; k < argc; k++) {
574
585
  args.push(read(ARG_REGS[k]));
575
586
  }
576
- // Pushed with `tmp` rather than `emit` so the result register is written AFTER the clobber
577
- // is recordedthe order matters: r3.. are volatile under the EABI, so a GUESSED arity
578
- // that counted a register set up before an intervening call passes an argument the caller
579
- // never set up (`finish()` cuts those back — frontend/ssa.ts), while the call's OWN result
580
- // must stay fresh for the next call (`bar(foo())`).
587
+ // Pushed with `tmp` rather than `emit` so the result register is written separately from
588
+ // the op — r3.. are volatile under the EABI, so a GUESSED arity that counted a register
589
+ // set up before an intervening call passes an argument the caller never set up
590
+ // (`finish()` cuts those back — frontend/ssa.ts), and the call's OWN result is the
591
+ // CALLEE's write, so `noteCall` records the clobber after it rather than before.
581
592
  const res = kit.tmp('call', args, { target: sym });
582
593
  if (declared === undefined) {
583
- ssa.recordGuessedCall(ops[ops.length - 1], bi, ARG_REGS);
594
+ ssa.recordGuessedCall(ops[ops.length - 1], bi, { argRegs: ARG_REGS, returnReg: RET });
584
595
  }
585
- ssa.noteCall(bi);
586
596
  write(RET, res);
597
+ ssa.noteCall(bi);
587
598
  break;
588
599
  }
589
600
  // Stack-frame + link-register bookkeeping. `stwu r1,-N(r1)` / `addi r1,r1,N` adjust the frame
@@ -629,9 +640,16 @@ export function lift(
629
640
  write(d, read(s));
630
641
  break; // move register (or rD,rS,rS)
631
642
  case 'li':
643
+ // SDA21 address formation encodes rA=0, so objdump prints `li rD,0` + R_PPC_EMB_SDA21
644
+ if (ins.sym) {
645
+ relocPlaceholder(ins);
646
+ }
632
647
  write(d, constVal(parseImm(s)));
633
648
  break; // load immediate (addi rD,0,imm)
634
649
  case 'lis':
650
+ if (ins.sym) {
651
+ relocPlaceholder(ins);
652
+ }
635
653
  write(d, constVal((parseImm(s) << 16) >> 0));
636
654
  break; // load immediate shifted
637
655
  case 'add':
@@ -641,11 +659,25 @@ export function lift(
641
659
  // `addi r1,r1,N` is frame teardown (skip); any other addi is a real add-immediate.
642
660
  case 'addi':
643
661
  case 'addic':
662
+ // reloc first: a data reloc on a stack adjust is no known compiler's output — loud
663
+ if (ins.sym) {
664
+ relocPlaceholder(ins);
665
+ }
644
666
  if (d === 'r1') {
645
667
  break;
646
668
  }
647
669
  emitBin('add', d, read(s), constVal(parseImm(t)));
648
670
  break;
671
+ // add immediate SHIFTED — the register-based `%ha` anchor: mwcc derives an absolute base
672
+ // from a scaled index (`addis r4,r3,-32736` = r3 + 0x80200000). The jump-table lis/addi
673
+ // pair recognizer is the only reloc-carrying consumer; an addis over a register is plain
674
+ // arithmetic, and a reloc-carrying one is a placeholder (guard above).
675
+ case 'addis':
676
+ if (ins.sym) {
677
+ relocPlaceholder(ins);
678
+ }
679
+ emitBin('add', d, read(s), constVal((parseImm(t) << 16) >> 0));
680
+ break;
649
681
  case 'subf':
650
682
  case 'subfc':
651
683
  case 'subfo':
@@ -697,6 +729,10 @@ export function lift(
697
729
  emitBin('or', d, read(s), read(t));
698
730
  break;
699
731
  case 'ori':
732
+ // `ori rD,rA,sym@l` is the other @l half-former — same placeholder hazard as addi
733
+ if (ins.sym) {
734
+ relocPlaceholder(ins);
735
+ }
700
736
  emitBin('or', d, read(s), constVal(parseImm(t)));
701
737
  break;
702
738
  case 'xor':