jz 0.1.0 → 0.1.1

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.
package/src/compile.js CHANGED
@@ -28,15 +28,9 @@
28
28
  import { parse as parseWat } from 'watr'
29
29
  import { ctx, err, inc, resolveIncludes, PTR } from './ctx.js'
30
30
  import {
31
- T, VAL, valTypeOf, lookupValType, analyzeValTypes, analyzeIntCertain, analyzeLocals, analyzeBody, analyzePtrUnboxable, typedElemAux, exprType, invalidateLocalsCache, invalidateValTypesCache,
32
- extractParams, classifyParam, collectParamNames,
33
- findFreeVars, analyzeBoxedCaptures, analyzeDynKeys, typedElemCtor,
34
- repOf, updateRep, repOfGlobal, updateGlobalRep,
35
- staticObjectProps, mergeParamFact, ensureParamRep, callerParamFactMap, clearStickyNull,
36
- inferArgType, inferArgSchema, inferArgArrElemSchema, inferArgArrElemValType, inferArgTypedCtor,
37
- ctorFromElemAux, collectProgramFacts, observeProgramSlots, narrowReturnArrayElems,
38
- isBlockBody, alwaysReturns, hasBareReturn, returnExprs, collectReturnExprs,
39
- findMutations,
31
+ T, VAL, analyzeValTypes, analyzeIntCertain, analyzeLocals,
32
+ analyzePtrUnboxable, typedElemAux, invalidateLocalsCache,
33
+ analyzeBoxedCaptures, updateRep,
40
34
  } from './analyze.js'
41
35
  import { optimizeFunc, hoistConstantPool, specializeMkptr, specializePtrBase, sortStrPoolByFreq, treeshake } from './optimize.js'
42
36
  import { emit, emitter, emitFlat, emitBody } from './emit.js'
@@ -53,26 +47,9 @@ import {
53
47
  multiCount, loopTop, flat, reconstructArgsWithSpreads,
54
48
  valKindToPtr,
55
49
  } from './ir.js'
50
+ import plan from './plan.js'
56
51
 
57
- // Re-export for backward compatibility (modules import from compile.js)
58
- export { T, VAL, valTypeOf, lookupValType, extractParams, classifyParam, collectParamNames, repOf, updateRep, repOfGlobal, updateGlobalRep }
59
- export { emit, emitter, emitFlat }
60
- // IR helpers — re-export from ir.js so module/*.js keep their existing import paths.
61
- export {
62
- typed, asF64, asI32, asParamType, toI32, asI64, fromI64,
63
- NULL_NAN, UNDEF_NAN, NULL_WAT, UNDEF_WAT, NULL_IR, UNDEF_IR, nullExpr, undefExpr,
64
- MAX_CLOSURE_ARITY, MEM_OPS, WASM_OPS, SPREAD_MUTATORS, BOXED_MUTATORS,
65
- mkPtrIR, ptrOffsetIR, ptrTypeIR, extractF64Bits, appendStaticSlots,
66
- isLit, litVal, isNullishLit, isPureIR, isPostfix, emitNum,
67
- temp, tempI32, tempI64, f64rem, toNumF64, truthyIR, toBoolFromEmitted,
68
- keyValType, usesDynProps, needsDynShadow,
69
- isGlobal, isConst, boxedAddr, readVar, writeVar, isNullish,
70
- slotAddr, elemLoad, elemStore, arrayLoop, allocPtr,
71
- multiCount, loopTop, flat, reconstructArgsWithSpreads,
72
- }
73
- // Emit-dependent helpers (emitTypeofCmp, toBool, materializeMulti, emitDecl,
74
- // buildArrayWithSpreads) live in emit.js and are re-exported there for modules.
75
- export { emitTypeofCmp, toBool, materializeMulti, emitDecl, buildArrayWithSpreads } from './emit.js'
52
+ const timePhase = (profiler, name, fn) => profiler ? profiler.time(name, fn) : fn()
76
53
 
77
54
  // Per-compile func name set + map live on ctx.func.names / ctx.func.map,
78
55
  // populated at compile() entry. Both reset by ctx.js reset() and re-filled here.
@@ -165,909 +142,29 @@ const tcoTailRewrite = (ir, resultType) => {
165
142
 
166
143
  // === Module compilation ===
167
144
 
168
- /**
169
- * Phase: signature narrowing.
170
- *
171
- * Reads programFacts.callSites + valueUsed; mutates each user func's `sig`:
172
- * - param types (f64 → i32 / pointer-ABI i32+ptrKind, when call sites agree)
173
- * - param schemas (per-arg schemaId, recorded into programFacts.paramReps[k].schemaId)
174
- * - result type (f64 → i32, when body always returns i32)
175
- * - result valType (`func.valResult`) and pointer narrowing (sig.ptrKind)
176
- *
177
- * Pure w.r.t. the AST — only the function `sig` records change. The unified
178
- * paramReps record is populated here (per-field lattice) and consumed by the
179
- * per-function emit phase below.
180
- *
181
- * Encoded structurally as a phase so future S3 work can move it into a
182
- * pipeline runner without re-deriving the in/out contract from comments.
183
- */
184
- function narrowSignatures(programFacts, ast) {
185
- const { callSites, valueUsed, paramReps } = programFacts
186
-
187
- // Reachability filter: dead callerFuncs (e.g. unused stdlib helpers from bundled
188
- // modules) shouldn't poison narrowing of live functions. Without this, a never-
189
- // executed call like `checksumF64 → mix(h, u[i])` would force mix's `x` rep to
190
- // bimorphic (f64 ∪ i32) and block i32 narrowing of mix's hot caller (runKernel).
191
- // Live = exported ∪ value-used ∪ transitively reached from those + top-level.
192
- // Top-level call sites have callerFunc === null and are unconditionally live.
193
- if (callSites.length) {
194
- const live = new Set()
195
- for (const f of ctx.func.list) {
196
- if (f.exported || valueUsed.has(f.name)) live.add(f.name)
197
- }
198
- let changed = true
199
- while (changed) {
200
- changed = false
201
- for (const cs of callSites) {
202
- if (cs.callerFunc === null || live.has(cs.callerFunc.name)) {
203
- if (!live.has(cs.callee)) { live.add(cs.callee); changed = true }
204
- }
205
- }
206
- }
207
- // Mutate in place — every later phase reads the same array.
208
- let w = 0
209
- for (let r = 0; r < callSites.length; r++) {
210
- const cs = callSites[r]
211
- if (cs.callerFunc === null || live.has(cs.callerFunc.name)) callSites[w++] = cs
212
- }
213
- callSites.length = w
214
- }
215
-
216
- // D: Call-site type propagation — infer param types from how functions are called.
217
- // Drives off `callSites` collected during the ProgramFacts walk; no AST re-walking.
218
- // For non-exported internal functions, if all call sites agree on a param's type,
219
- // seed the param's val rep (ctx.func.repByLocal) during per-function compilation.
220
- // Also infer i32/f64 WASM type — when all call sites pass i32 for a param, specialize
221
- // sig.params[k].type to i32 (no default, no rest, not exported, not value-used).
222
- // Also propagate schema ID — when all call sites pass objects with the same schema,
223
- // bind the callee's param to that schema so `p.x` becomes a direct slot load.
224
- // Inference helpers (inferArgType/inferArgSchema/inferArgArr*/inferArgTypedCtor)
225
- // live in analyze.js — pure AST→fact resolvers shared across fixpoint phases.
226
- // Per-caller analysis is stable across fixpoint iterations — precompute once.
227
- // callerCtx[null] (top-level) uses module globals for both locals and valTypes.
228
- const callerCtx = new Map() // funcObj | null → { callerLocals, callerValTypes }
229
- callerCtx.set(null, { callerLocals: ctx.scope.globalTypes, callerValTypes: ctx.scope.globalValTypes })
230
- for (const func of ctx.func.list) {
231
- if (!func.body || func.raw) continue
232
- // Single unified walk — locals + valTypes from the same traversal.
233
- const facts = analyzeBody(func.body)
234
- for (const p of func.sig.params) if (!facts.locals.has(p.name)) facts.locals.set(p.name, p.type)
235
- callerCtx.set(func, { callerLocals: facts.locals, callerValTypes: facts.valTypes })
236
- }
237
- // Per-caller arr-elem observations. Recomputed each fixpoint iteration so
238
- // newly-narrowed func.arrayElemSchema/.arrayElemValType results propagate
239
- // from `const rows = initRows()` observations. Two-pass fixpoint: first
240
- // pass learns from literals + module vars; second pass forwards through
241
- // chained helpers (f → addXY → {getX, getY}).
242
- const buildCallerElems = (sliceKey) => {
243
- const m = new Map()
244
- m.set(null, new Map())
245
- for (const func of ctx.func.list) {
246
- if (!func.body || func.raw) continue
247
- m.set(func, analyzeBody(func.body)[sliceKey])
248
- }
249
- return m
250
- }
251
- let callerArrElemsCtx = buildCallerElems('arrElemSchemas')
252
- const rebuildArrElems = () => { callerArrElemsCtx = buildCallerElems('arrElemSchemas') }
253
- let callerArrElemValsCtx = buildCallerElems('arrElemValTypes')
254
- const rebuildArrElemVals = () => { callerArrElemValsCtx = buildCallerElems('arrElemValTypes') }
255
- const runFixpoint = () => {
256
- for (let s = 0; s < callSites.length; s++) {
257
- const { callee, argList, callerFunc } = callSites[s]
258
- const func = ctx.func.map.get(callee)
259
- if (!func || func.exported || valueUsed.has(callee)) continue
260
- const ctxEntry = callerCtx.get(callerFunc)
261
- if (!ctxEntry) continue
262
- const { callerLocals, callerValTypes } = ctxEntry
263
- const callerSchemas = callerParamFactMap(paramReps, callerFunc, 'schemaId')
264
- const restIdx = func.rest ? func.sig.params.length - 1 : -1
265
- for (let k = 0; k < func.sig.params.length; k++) {
266
- const r = ensureParamRep(paramReps, callee, k)
267
- if (k < argList.length) {
268
- if (r.val !== null) mergeParamFact(r, 'val', inferArgType(argList[k], callerValTypes))
269
- // Wasm-type lattice: exprType always returns 'i32'|'f64' — no null sentinel.
270
- if (r.wasm !== null) {
271
- const wt = exprType(argList[k], callerLocals)
272
- if (r.wasm === undefined) r.wasm = wt
273
- else if (r.wasm !== wt) r.wasm = null
274
- }
275
- if (r.schemaId !== null) mergeParamFact(r, 'schemaId', inferArgSchema(argList[k], callerSchemas))
276
- // intConst lattice: bare-integer literal at every site → param has fixed value.
277
- // Skip rest position — argList[restIdx] is just the first packed arg, not the
278
- // whole array. Drop intConst for the rest param so it's never substituted.
279
- if (k === restIdx) r.intConst = null
280
- else if (r.intConst !== null) {
281
- // Literal forms after prepare: bare number, `[null, n]` (literal wrap),
282
- // or `['u-', n]` (negative literal). A bare string referencing a known
283
- // module-scope `const NAME = <int-literal>` resolves through ctx.scope.constInts.
284
- // Anything else → no-consensus.
285
- const a = argList[k]
286
- let raw = null
287
- if (typeof a === 'number') raw = a
288
- else if (Array.isArray(a) && a[0] == null && typeof a[1] === 'number') raw = a[1]
289
- else if (Array.isArray(a) && a[0] === 'u-' && typeof a[1] === 'number') raw = -a[1]
290
- else if (typeof a === 'string' && ctx.scope.constInts?.has(a)) raw = ctx.scope.constInts.get(a)
291
- const v = (raw != null && Number.isInteger(raw) && raw >= -2147483648 && raw <= 2147483647) ? raw : null
292
- mergeParamFact(r, 'intConst', v)
293
- }
294
- } else {
295
- // Missing arg — call pads with nullExpr (f64). Prevents narrowing.
296
- r.val = null; r.wasm = null; r.schemaId = null; r.intConst = null
297
- }
298
- }
299
- }
300
- }
301
- // Generic arr-elem fixpoint: same shape for arrayElemSchema (schema-id),
302
- // arrayElemValType (VAL.*), and typedCtor. `field` selects which fact;
303
- // `inferFn` and `elemsCtxMap` provide per-callee inference.
304
- const runArrElemFixpoint = (field, inferFn, elemsCtxMap) => {
305
- for (let s = 0; s < callSites.length; s++) {
306
- const { callee, argList, callerFunc } = callSites[s]
307
- const func = ctx.func.map.get(callee)
308
- if (!func || func.exported || valueUsed.has(callee)) continue
309
- if (!callerCtx.get(callerFunc)) continue
310
- const callerParams = callerParamFactMap(paramReps, callerFunc, field)
311
- const callerElems = elemsCtxMap.get(callerFunc)
312
- for (let k = 0; k < func.sig.params.length; k++) {
313
- const r = ensureParamRep(paramReps, callee, k)
314
- if (k >= argList.length) { r[field] = null; continue }
315
- if (r[field] === null) continue
316
- mergeParamFact(r, field, inferFn(argList[k], callerElems, callerParams))
317
- }
318
- }
319
- }
320
- const runArrFixpoint = () => runArrElemFixpoint('arrayElemSchema', inferArgArrElemSchema, callerArrElemsCtx)
321
- const runArrValTypeFixpoint = () => runArrElemFixpoint('arrayElemValType', inferArgArrElemValType, callerArrElemValsCtx)
322
- runFixpoint()
323
- runFixpoint()
324
-
325
- // Apply i32 specialization: for non-value-used funcs with consistent i32 call
326
- // sites and no defaults/rest at that position, narrow sig.params[k].type.
327
- // Exports too — boundary wrapper handles the f64→i32 truncation at the JS edge.
328
- for (const func of ctx.func.list) {
329
- if (func.raw || valueUsed.has(func.name)) continue
330
- const reps = paramReps.get(func.name)
331
- if (!reps) continue
332
- const restIdx = func.rest ? func.sig.params.length - 1 : -1
333
- for (const [k, r] of reps) {
334
- if (r.wasm !== 'i32' || k === restIdx) continue
335
- const pname = func.sig.params[k].name
336
- if (func.defaults?.[pname] != null) continue // defaults need nullish-sentinel f64
337
- func.sig.params[k].type = 'i32'
338
- }
339
- }
340
-
341
- // intConst validation: a param marked with a unanimous integer literal at every call
342
- // site is only safe to substitute if the body never reassigns it. Clear intConst on any
343
- // param whose name appears on the LHS of an assignment / `++` / `--`. Skip exported
344
- // (callable from JS with arbitrary value), value-used (closure callees), raw, defaulted,
345
- // and rest params — same exclusions as the wasm-narrowing pass above.
346
- for (const func of ctx.func.list) {
347
- if (func.exported || func.raw || valueUsed.has(func.name)) continue
348
- if (!func.body) continue
349
- const reps = paramReps.get(func.name)
350
- if (!reps) continue
351
- const restIdx = func.rest ? func.sig.params.length - 1 : -1
352
- let candidates = null
353
- for (const [k, r] of reps) {
354
- if (r.intConst == null || k === restIdx) continue
355
- if (k >= func.sig.params.length) { r.intConst = null; continue }
356
- const pname = func.sig.params[k].name
357
- if (func.defaults?.[pname] != null) { r.intConst = null; continue }
358
- ;(candidates ||= new Map()).set(pname, r)
359
- }
360
- if (!candidates) continue
361
- const mutated = new Set()
362
- findMutations(func.body, new Set(candidates.keys()), mutated)
363
- for (const name of mutated) candidates.get(name).intConst = null
364
- }
365
-
366
- // Pointer-ABI specialization: for non-forwarding pointer params consistent across
367
- // call sites, narrow from NaN-boxed f64 to i32 offset. Eliminates per-call __ptr_offset
368
- // extraction + f64→i64→i32 reinterpret chains that dominate watr-style compilers.
369
- // Safety:
370
- // - exclude ARRAY (forwards on realloc — f64 NaN-box is a stable identity) and
371
- // STRING (SSO vs heap dual encoding depends on ptr-type bits we'd drop).
372
- // - exclude CLOSURE/TYPED (aux bits carry schema/element-type, lost with offset).
373
- // - exclude params with defaults (nullish sentinel needs the f64 NaN space).
374
- // - exclude rest position (array pack/unpack stays f64).
375
- const PTR_ABI_KINDS = new Set([VAL.OBJECT, VAL.SET, VAL.MAP, VAL.BUFFER])
376
- for (const func of ctx.func.list) {
377
- if (func.exported || func.raw || valueUsed.has(func.name)) continue
378
- const reps = paramReps.get(func.name)
379
- if (!reps) continue
380
- const restIdx = func.rest ? func.sig.params.length - 1 : -1
381
- for (const [k, r] of reps) {
382
- if (!PTR_ABI_KINDS.has(r.val)) continue
383
- if (k === restIdx) continue
384
- if (k >= func.sig.params.length) continue
385
- const p = func.sig.params[k]
386
- if (p.type === 'i32') continue // already narrowed by numeric pass
387
- if (func.defaults?.[p.name] != null) continue
388
- p.type = 'i32'
389
- p.ptrKind = r.val
390
- }
391
- }
392
-
393
- // E: Result-type monomorphization — narrow sig.results[0] to 'i32' when body only
394
- // produces i32 values. Fixpoint: a call to another narrowed func now contributes i32;
395
- // iterate until stable so chains of i32-only helpers all narrow together.
396
- // Safety: skip exported (JS boundary preserves number semantics), value-used (closure
397
- // trampolines assume f64 result), raw WAT, multi-value. `undefined` return = skip.
398
- // exprType already consults ctx.func.map for narrowed user-function results
399
- // (analyze.js exprType `()` branch), plus the Math.imul/Math.clz32/charCodeAt
400
- // stdlib subset and primitive-op rules. Earlier we had a local shim here that
401
- // shadowed exprType's stdlib rules with `return 'f64'` for any non-user call;
402
- // unifying through exprType lets a single rule (math.imul → i32) flow through
403
- // to mix-style helpers (`(h, x) => Math.imul(h ^ (x|0), C)`) and unblocks the
404
- // E-phase result narrowing on every call site that consumes them.
405
- const exprTypeWithCalls = exprType
406
- // Body-driven: safe for exports — the result type is determined by what the body
407
- // computes, not by what JS callers might pass. JS-visible f64 ABI is restored at
408
- // the boundary via a synthesized wrapper (see synthesizeBoundaryWrappers below).
409
- // Shared pool for E (numeric), E2 (valType) and E3 (ptr) narrowing — same predicate.
410
- const narrowableFuncs = ctx.func.list.filter(f =>
411
- !f.raw && !valueUsed.has(f.name) && f.sig.results.length === 1
412
- )
413
- let changed = true
414
- while (changed) {
415
- changed = false
416
- for (const func of narrowableFuncs) {
417
- if (func.sig.results[0] === 'i32') continue
418
- const body = func.body
419
- // Bare `return;` produces undef (f64) — narrowing to i32 would lose that.
420
- if (isBlockBody(body) && hasBareReturn(body)) continue
421
- const exprs = returnExprs(body)
422
- if (!exprs.length) continue
423
- // Skip narrowing when any return-tail is `>>>` (unsigned uint32). Narrowing to i32
424
- // loses the unsigned interpretation: the wrapper rebox via `f64.convert_i32_s` would
425
- // sign-flip values with bit 31 set, breaking the canonical `(x >>> 0)` uint32 idiom.
426
- // A future pass could track sig.unsignedResult and emit `f64.convert_i32_u` instead.
427
- if (exprs.some(e => Array.isArray(e) && e[0] === '>>>')) continue
428
- const savedCurrent = ctx.func.current
429
- ctx.func.current = func.sig
430
- const locals = isBlockBody(body) ? analyzeLocals(body) : new Map()
431
- for (const p of func.sig.params) if (!locals.has(p.name)) locals.set(p.name, p.type)
432
- const allI32 = exprs.every(e => exprTypeWithCalls(e, locals) === 'i32')
433
- ctx.func.current = savedCurrent
434
- if (allI32) { func.sig.results = ['i32']; changed = true }
435
- }
436
- }
437
-
438
- // E2: VAL-type result inference — if a function always returns the same VAL kind,
439
- // record it so callers inherit that type (enables static dispatch on .length, .[],
440
- // .prop through a call chain). Fixpoint propagates through helper chains.
441
- // Safety: skip exported (host sees raw f64), value-used (indirect call signature).
442
- // Shim so calls to already-typed funcs contribute their result type.
443
- const valTypeOfWithCalls = (expr, localValTypes) => {
444
- if (expr == null) return null
445
- if (typeof expr === 'string') return localValTypes?.get(expr) || ctx.scope.globalValTypes?.get(expr) || null
446
- if (!Array.isArray(expr)) return valTypeOf(expr)
447
- const [op, ...args] = expr
448
- if (op === '()' && typeof args[0] === 'string') {
449
- const f = ctx.func.map.get(args[0])
450
- if (f?.valResult) return f.valResult
451
- }
452
- if (op === '?:') {
453
- const a = valTypeOfWithCalls(args[1], localValTypes), b = valTypeOfWithCalls(args[2], localValTypes)
454
- return a && a === b ? a : null
455
- }
456
- if (op === '&&' || op === '||') {
457
- const a = valTypeOfWithCalls(args[0], localValTypes), b = valTypeOfWithCalls(args[1], localValTypes)
458
- return a && a === b ? a : null
459
- }
460
- return valTypeOf(expr)
461
- }
462
- // Body-driven valResult inference: same safety analysis as numeric narrowing
463
- // above — exports OK because boundary wrapper restores f64 ABI for JS callers.
464
- changed = true
465
- while (changed) {
466
- changed = false
467
- for (const func of narrowableFuncs) {
468
- if (func.valResult) continue
469
- const body = func.body
470
- const isBlock = isBlockBody(body)
471
- if (isBlock && hasBareReturn(body)) continue
472
- const exprs = returnExprs(body)
473
- if (!exprs.length) continue
474
- const localValTypes = isBlock ? analyzeBody(body).valTypes : new Map()
475
- // Params of this function contribute no known VAL type yet (paramReps may help later).
476
- const vt0 = valTypeOfWithCalls(exprs[0], localValTypes)
477
- if (!vt0) continue
478
- const allSame = exprs.every(e => valTypeOfWithCalls(e, localValTypes) === vt0)
479
- if (allSame) { func.valResult = vt0; changed = true }
480
- }
481
- }
482
-
483
- // Now that E2 set `valResult` on funcs, narrow per-func `arrayElemSchema` for
484
- // VAL.ARRAY-returning funcs (via push observations + call chains). Then re-run the
485
- // D-pass arrayElemSchema/val fixpoints so `const rows = initRows()` in main
486
- // resolves to VAL.ARRAY (lets runKernel pick up r.val=ARRAY) and its arr-elem
487
- // schema (sets paramReps[runKernel][0].arrayElemSchema=sid).
488
- // Cache invalidation: analyzeBody.valTypes is body-keyed, and entries cached
489
- // during the first D pass have stale (null) `valTypeOf(call)` results because
490
- // valResult was unset back then.
491
- narrowReturnArrayElems('arrayElemSchema', paramReps, valueUsed)
492
- narrowReturnArrayElems('arrayElemValType', paramReps, valueUsed)
493
- for (const func of ctx.func.list) {
494
- if (func.body && !func.raw) invalidateValTypesCache(func.body)
495
- }
496
- for (const func of ctx.func.list) {
497
- if (!func.body || func.raw) continue
498
- const entry = callerCtx.get(func)
499
- if (entry) entry.callerValTypes = analyzeBody(func.body).valTypes
500
- }
501
- // Re-observe schema slot val-types now that E2 has set `valResult` on user
502
- // funcs. First pass runs in collectProgramFacts before valResult is known, so
503
- // a slot like `cs` in `{ ..., cs }` (where `cs = checksum(out)`) gets observed
504
- // as null. observeSlot's first-wins-then-clash rule lets a later precise
505
- // observation upgrade `undefined` → NUMBER without poisoning earlier
506
- // monomorphic observations.
507
- observeProgramSlots(ast)
508
- rebuildArrElems()
509
- rebuildArrElemVals()
510
- // Clear sticky-null on val/schemaId — first 2 passes ran with valResult unset, so
511
- // call args resolving via `f.valResult` returned null and got stuck. Re-running
512
- // with refreshed callerValTypes lets these flow.
513
- clearStickyNull(paramReps, 'val')
514
- clearStickyNull(paramReps, 'schemaId')
515
- runFixpoint()
516
- // Now that .val is refreshed, dedicated arr-elem-schema fixpoint.
517
- runArrFixpoint()
518
- runArrFixpoint()
519
- // Parallel arr-elem-val fixpoint (NUMBER/STRING/…). Twice for transitive closure
520
- // through helper chains: `init()→main→runKernel`.
521
- runArrValTypeFixpoint()
522
- runArrValTypeFixpoint()
523
- // E3: Result-type pointer narrowing — when valResult is a non-ambiguous pointer kind
524
- // with constant aux, narrow sig.results[0] from f64 to i32 and tag sig.ptrKind/.ptrAux.
525
- // Eliminates the f64.reinterpret_i64+i64.or rebox at every return and the
526
- // i32.wrap_i64+i64.reinterpret_f64 unbox at every callsite that uses the value as a
527
- // pointer (load .[], .length, .prop slot dispatch).
528
- // - SET/MAP/BUFFER: aux always 0 — no per-callsite aux preservation needed.
529
- // - OBJECT: aux is schema-id; narrow only when all return exprs share a constant
530
- // schema (literal `{a,b,c}`, schemaId-bound param, module-bound var, or call to
531
- // another OBJECT-narrowed func). Caller picks aux up via callIR.ptrAux → readVar →
532
- // repByLocal.schemaId, restoring property-slot dispatch through the call boundary.
533
- // Safety: ARRAY forwards on realloc (no narrowing). STRING dual-encoded SSO/heap.
534
- // CLOSURE/TYPED also carry meaningful aux — TYPED narrowing is a follow-up. Body must
535
- // be a guaranteed-return form — fallthrough fallback i32.const 0 would be a valid
536
- // offset 0 of the narrowed kind, not undefined.
537
- const PTR_RESULT_KINDS_NOAUX = new Set([VAL.SET, VAL.MAP, VAL.BUFFER])
538
- // Schema-id inference for a return expression. Returns id (number), or null if unknown
539
- // / not constant. Mirrors inferArgSchema but extends with calls to already-narrowed
540
- // OBJECT-result funcs (fixpoint propagation through helper chains).
541
- const schemaIdOfReturn = (expr, paramSchemasMap) => {
542
- if (typeof expr === 'string') {
543
- if (paramSchemasMap?.has(expr)) return paramSchemasMap.get(expr)
544
- if (ctx.schema.vars.has(expr)) return ctx.schema.vars.get(expr)
545
- return null
546
- }
547
- if (!Array.isArray(expr)) return null
548
- const [op, ...args] = expr
549
- if (op === '{}') {
550
- // Object literal: bail to null on block body, dynamic key, or spread.
551
- const parsed = staticObjectProps(args)
552
- return parsed ? ctx.schema.register(parsed.names) : null
553
- }
554
- if (op === '()' && typeof args[0] === 'string') {
555
- const f = ctx.func.map.get(args[0])
556
- if (f?.valResult === VAL.OBJECT && f.sig.ptrAux != null) return f.sig.ptrAux
557
- return null
558
- }
559
- if (op === '?:') {
560
- const a = schemaIdOfReturn(args[1], paramSchemasMap)
561
- const b = schemaIdOfReturn(args[2], paramSchemasMap)
562
- return a != null && a === b ? a : null
563
- }
564
- if (op === '&&' || op === '||') {
565
- const a = schemaIdOfReturn(args[0], paramSchemasMap)
566
- const b = schemaIdOfReturn(args[1], paramSchemasMap)
567
- return a != null && a === b ? a : null
568
- }
569
- return null
570
- }
571
- // Per-body local elemAux map: scans `let/const x = new TypedArray(...)` decls so
572
- // a return like `let a = new Float64Array(...); return a` resolves to a constant
573
- // aux. Result calls + ?: are handled inline in typedAuxOfReturn.
574
- const localElemAuxMap = (body) => {
575
- const m = new Map()
576
- const walk = (n) => {
577
- if (!Array.isArray(n)) return
578
- const op = n[0]
579
- if (op === '=>') return
580
- if ((op === 'let' || op === 'const') && n.length > 1) {
581
- for (let i = 1; i < n.length; i++) {
582
- const a = n[i]
583
- if (Array.isArray(a) && a[0] === '=' && typeof a[1] === 'string') {
584
- const aux = typedElemAux(typedElemCtor(a[2]))
585
- if (aux != null) m.set(a[1], aux)
586
- }
587
- }
588
- }
589
- for (let i = 1; i < n.length; i++) walk(n[i])
590
- }
591
- walk(body)
592
- return m
593
- }
594
- const typedAuxOfReturn = (expr, localElemMap) => {
595
- if (typeof expr === 'string') return localElemMap?.get(expr) ?? null
596
- if (!Array.isArray(expr)) return null
597
- const [op, ...args] = expr
598
- if (op === '()' && typeof args[0] === 'string') {
599
- if (args[0].startsWith('new.')) {
600
- const ctor = typedElemCtor(expr)
601
- return ctor != null ? typedElemAux(ctor) : null
602
- }
603
- const f = ctx.func.map.get(args[0])
604
- if (f?.valResult === VAL.TYPED && f.sig.ptrAux != null) return f.sig.ptrAux
605
- return null
606
- }
607
- if (op === '?:') {
608
- const a = typedAuxOfReturn(args[1], localElemMap)
609
- const b = typedAuxOfReturn(args[2], localElemMap)
610
- return a != null && a === b ? a : null
611
- }
612
- if (op === '&&' || op === '||') {
613
- const a = typedAuxOfReturn(args[0], localElemMap)
614
- const b = typedAuxOfReturn(args[1], localElemMap)
615
- return a != null && a === b ? a : null
616
- }
617
- return null
618
- }
619
- // Fixpoint: a chain `outer → inner → {a,b}` needs inner to narrow first so outer's
620
- // call to inner contributes a known schema-id.
621
- let narrowChanged = true
622
- while (narrowChanged) {
623
- narrowChanged = false
624
- for (const func of narrowableFuncs) {
625
- if (!func.valResult) continue
626
- if (func.sig.results[0] !== 'f64') continue
627
- const isBlock = isBlockBody(func.body)
628
- if (isBlock && !alwaysReturns(func.body)) continue
629
- if (PTR_RESULT_KINDS_NOAUX.has(func.valResult)) {
630
- func.sig.results = ['i32']
631
- func.sig.ptrKind = func.valResult
632
- narrowChanged = true
633
- continue
634
- }
635
- const exprs = returnExprs(func.body)
636
- if (!exprs.length) continue
637
- if (func.valResult === VAL.OBJECT) {
638
- const paramSchemasMap = callerParamFactMap(paramReps, func, 'schemaId')
639
- const sid0 = schemaIdOfReturn(exprs[0], paramSchemasMap)
640
- if (sid0 == null) continue
641
- if (!exprs.every(e => schemaIdOfReturn(e, paramSchemasMap) === sid0)) continue
642
- func.sig.results = ['i32']
643
- func.sig.ptrKind = VAL.OBJECT
644
- func.sig.ptrAux = sid0
645
- narrowChanged = true
646
- } else if (func.valResult === VAL.TYPED) {
647
- const localMap = isBlock ? localElemAuxMap(func.body) : null
648
- const aux0 = typedAuxOfReturn(exprs[0], localMap)
649
- if (aux0 == null) continue
650
- if (!exprs.every(e => typedAuxOfReturn(e, localMap) === aux0)) continue
651
- func.sig.results = ['i32']
652
- func.sig.ptrKind = VAL.TYPED
653
- func.sig.ptrAux = aux0
654
- narrowChanged = true
655
- }
656
- }
657
- }
658
-
659
- // F: Cross-call typed-array element ctor propagation. Runs AFTER E3 so that
660
- // calls to user functions returning a TYPED-narrowed pointer (with constant
661
- // ptrAux, e.g. mkInput → Float64Array) contribute their element type to the
662
- // caller's local typedElem map. Result: callees pick up `ctx.types.typedElem`
663
- // for their own params and `arr[i]` reads emit a direct `f64.load` instead of
664
- // the runtime `__is_str_key + __typed_idx` dispatch — closes the largest
665
- // chunk of the JS→wasm gap on f64-heavy hot loops.
666
- // (Helpers `inferArgTypedCtor`/`ctorFromElemAux` live in analyze.js so the
667
- // bimorphic-typed specialization pass below can reuse them.)
668
- // Per-caller typed-elem map, recomputed now that E3 has tagged helper sigs.
669
- // Cache invalidation: analyzeBody.typedElems reads `ctx.func.map.get(...).sig.ptrKind`
670
- // for `let x = mkInput(...)` decls; entries cached during the initial walk
671
- // (before E3 ran) are stale (mkInput's ptrKind was unset then).
672
- for (const func of ctx.func.list) {
673
- if (func.body && !func.raw) invalidateValTypesCache(func.body)
674
- }
675
- const callerTypedCtx = new Map()
676
- callerTypedCtx.set(null, ctx.scope.globalTypedElem || new Map())
677
- for (const func of ctx.func.list) {
678
- if (!func.body || func.raw) continue
679
- callerTypedCtx.set(func, analyzeBody(func.body).typedElems)
680
- }
681
- // Two-pass fixpoint: lets a caller's params, once typed, propagate further to
682
- // its own callees (e.g. if `outer(buf)` calls `inner(buf)` and we learn `buf`
683
- // for outer, the second pass picks it up for inner). Reuses runArrElemFixpoint
684
- // (same shape — field/inferFn/elemsCtxMap parameterization).
685
- const runTypedFixpoint = () => runArrElemFixpoint('typedCtor', inferArgTypedCtor, callerTypedCtx)
686
- runTypedFixpoint()
687
- runTypedFixpoint()
688
-
689
- // G: TYPED pointer-ABI narrowing — once .typedCtor agrees on a single
690
- // ctor across all call sites, narrow the param from NaN-boxed f64 to raw
691
- // i32 offset (with ptrAux carrying the elem-type bits). Eliminates the
692
- // per-read `i32.wrap_i64 (i64.reinterpret_f64 (local.get $arr))` unbox dance
693
- // that today dominates hot loops dominated by typed-array indexing.
694
- // Call sites coerce via emitArgForParam → ptrOffsetIR(arg, VAL.TYPED).
695
- // Safety: same exclusions as the OBJECT/SET/MAP/BUFFER narrowing above —
696
- // exported, value-used, raw, defaults, rest position.
697
- for (const func of ctx.func.list) {
698
- if (func.exported || func.raw || valueUsed.has(func.name)) continue
699
- const reps = paramReps.get(func.name)
700
- if (!reps) continue
701
- const restIdx = func.rest ? func.sig.params.length - 1 : -1
702
- for (const [k, r] of reps) {
703
- const ctor = r.typedCtor
704
- if (ctor == null) continue
705
- if (k === restIdx) continue
706
- if (k >= func.sig.params.length) continue
707
- const p = func.sig.params[k]
708
- if (p.type === 'i32') continue
709
- if (func.defaults?.[p.name] != null) continue
710
- const aux = typedElemAux(ctor)
711
- if (aux == null) continue
712
- p.type = 'i32'
713
- p.ptrKind = VAL.TYPED
714
- p.ptrAux = aux
715
- }
716
- }
717
-
718
- // H: Post-F/G re-fixpoint — propagates VAL kinds through bimorphic call sites
719
- // where ptrKind narrowed but ptrAux disagreed (e.g. `sum(f64arr)` and `sum(i32arr)`
720
- // → both VAL.TYPED, different ctors). Without this, callerValTypes carries no entry
721
- // for caller's params, so inferArgType returns null and paramReps[callee][k].val is
722
- // sticky null. With ptrKind enriching callerValTypes, sum's arr gets val=TYPED in
723
- // its rep, letting array.js skip __is_str_key + __str_idx dispatch on `arr[i]`.
724
- for (const func of ctx.func.list) {
725
- if (!func.body || func.raw) continue
726
- const entry = callerCtx.get(func)
727
- if (!entry) continue
728
- for (const p of func.sig.params) {
729
- if (p.ptrKind == null) continue
730
- if (entry.callerValTypes.has(p.name)) continue
731
- entry.callerValTypes.set(p.name, p.ptrKind)
732
- }
733
- }
734
- clearStickyNull(paramReps, 'val')
735
- runFixpoint()
736
-
737
- // I: Post-E re-narrow of numeric (i32) params. The first numeric narrowing pass
738
- // ran before E narrowed any result types, so callerLocals saw `let h = mix(...)`
739
- // as f64 (mix's result was f64 then). After E narrowed mix's result to i32,
740
- // exprType (which now consults func.sig.results for user calls) sees `h` as i32.
741
- // Refresh callerLocals + clear sticky-null wasm + re-run fixpoint + re-apply
742
- // numeric narrowing to propagate i32 through chains of i32-only helpers
743
- // (callback bench: mix is FNV — params and result all i32-shaped, but inferred
744
- // only after E phase narrowed mix's result).
745
- for (const func of ctx.func.list) {
746
- if (!func.body || func.raw) continue
747
- invalidateLocalsCache(func.body)
748
- const fresh = analyzeLocals(func.body)
749
- for (const p of func.sig.params) if (!fresh.has(p.name)) fresh.set(p.name, p.type)
750
- callerCtx.get(func).callerLocals = fresh
751
- }
752
- // Reset wasm field unconditionally — first pass populated it from stale callerLocals
753
- // (where `let h = mix(...)` widened h to f64 because mix's result wasn't narrowed
754
- // yet). clearStickyNull only resets null; here we need to reset f64-observed too
755
- // so the refreshed exprType view propagates.
756
- for (const m of paramReps.values()) for (const r of m.values()) r.wasm = undefined
757
- runFixpoint()
758
- for (const func of ctx.func.list) {
759
- if (func.raw || valueUsed.has(func.name)) continue
760
- const reps = paramReps.get(func.name)
761
- if (!reps) continue
762
- const restIdx = func.rest ? func.sig.params.length - 1 : -1
763
- for (const [k, r] of reps) {
764
- if (r.wasm !== 'i32' || k === restIdx) continue
765
- if (k >= func.sig.params.length) continue
766
- const p = func.sig.params[k]
767
- if (p.type === 'i32') continue // already narrowed (incl. ptr-ABI)
768
- if (func.defaults?.[p.name] != null) continue
769
- // Don't steal typed-array params from specializeBimorphicTyped: F phase parks
770
- // bimorphic typed params at type='f64' with sticky-null typedCtor (two distinct
771
- // ctors at call sites). Their callers post-F pass them as i32 (pointer ABI),
772
- // so r.wasm flips to 'i32' here — but narrowing now breaks the clone path
773
- // that still needs to mint per-ctor sigs with ptrKind=TYPED, ptrAux=ctor-aux.
774
- if (r.val === VAL.TYPED) continue
775
- p.type = 'i32'
776
- }
777
- }
778
- }
779
-
780
- /**
781
- * Phase: bimorphic typed-array param specialization.
782
- *
783
- * For each non-exported user function with a typed-array param that F/G-phase
784
- * left bimorphic (paramReps[name][k].typedCtor === null because two or more call sites
785
- * disagreed on the elem-ctor — e.g. `sum(f64)` and `sum(i32)`), clone the
786
- * function once per concrete ctor seen at the call sites, narrow each clone's
787
- * sig.params[k] to a monomorphic typed pointer ABI (type='i32', ptrKind=TYPED,
788
- * ptrAux=ctor's aux), and rewrite the call AST nodes to dispatch to the right
789
- * clone. The original survives as a fallback for any non-static call sites
790
- * (e.g. inside arrow bodies); treeshake removes it if every site got rewritten.
791
- *
792
- * Why this matters: without specialization, `arr[i]` inside `sum` falls into
793
- * the runtime `__typed_idx` path on every iteration — V8 can't inline a wasm
794
- * call dominated by a switch on elem type. After specialization, each clone's
795
- * `arr[i]` lowers to a direct `f64.load` (or `i32.load + f64.convert`) with
796
- * the elem-ctor known at compile time. On poly bench this is the difference
797
- * between ~5 ms and matching AS at ~1 ms.
798
- *
799
- * Safety mirrors G-phase: skip exported, raw, value-used, defaulted, rest, or
800
- * already-i32 params. Bounded by MAX_CLONES_PER_FN to guard against polymorphic
801
- * blow-up (≥5 distinct ctors at one site → no specialization).
802
- */
803
- function specializeBimorphicTyped(programFacts) {
804
- const { callSites, valueUsed, paramReps } = programFacts
805
- const MAX_CLONES_PER_FN = 4
806
-
807
- // Per-callee static-call-site index. Built once; cheap.
808
- const sitesByCallee = new Map()
809
- for (const cs of callSites) {
810
- const list = sitesByCallee.get(cs.callee)
811
- if (list) list.push(cs); else sitesByCallee.set(cs.callee, [cs])
812
- }
813
-
814
- // Per-caller typedElem map (literal `new TypedArray(N)` bindings inside body).
815
- const callerTypedCtx = new Map()
816
- callerTypedCtx.set(null, ctx.scope.globalTypedElem || new Map())
817
- for (const func of ctx.func.list) {
818
- if (!func.body || func.raw) continue
819
- callerTypedCtx.set(func, analyzeBody(func.body).typedElems)
820
- }
821
- // Per-caller typed-param map: caller's own params that F/G already narrowed
822
- // (so transitive `sum(arr)` inside a func that took `arr` from above resolves).
823
- const callerTypedParamsCtx = new Map()
824
- for (const func of ctx.func.list) {
825
- const m = callerParamFactMap(paramReps, func, 'typedCtor') || null
826
- let acc = m
827
- if (func.sig?.params) for (const p of func.sig.params) {
828
- if (p.ptrKind === VAL.TYPED && p.ptrAux != null) {
829
- acc ||= new Map()
830
- if (!acc.has(p.name)) acc.set(p.name, ctorFromElemAux(p.ptrAux))
831
- }
832
- }
833
- if (acc) callerTypedParamsCtx.set(func, acc)
834
- }
835
-
836
- // Snapshot ctx.func.list — we'll be appending clones during the loop.
837
- const originals = ctx.func.list.slice()
838
- for (const func of originals) {
839
- if (func.exported || func.raw || valueUsed.has(func.name)) continue
840
- if (!func.body) continue
841
- if (func.rest) continue
842
- const reps = paramReps.get(func.name)
843
- if (!reps) continue
844
- const sites = sitesByCallee.get(func.name)
845
- if (!sites || sites.length < 2) continue
846
-
847
- // Find sticky-bimorphic typed-param positions left by F-phase.
848
- const bimorphic = []
849
- for (let k = 0; k < func.sig.params.length; k++) {
850
- if (reps.get(k)?.typedCtor !== null) continue
851
- const p = func.sig.params[k]
852
- if (p.type === 'i32') continue
853
- if (func.defaults?.[p.name] != null) continue
854
- bimorphic.push(k)
855
- }
856
- if (bimorphic.length === 0) continue
857
-
858
- // For each site, infer the ctor combination across bimorphic positions.
859
- // Abort if any site has unknown ctor at any bimorphic position — we can't
860
- // route that call to a specific clone without it.
861
- const siteCombos = []
862
- let abort = false
863
- for (const site of sites) {
864
- const callerTypedElems = callerTypedCtx.get(site.callerFunc)
865
- const callerTypedParams = callerTypedParamsCtx.get(site.callerFunc)
866
- const combo = []
867
- for (const k of bimorphic) {
868
- if (k >= site.argList.length) { abort = true; break }
869
- const c = inferArgTypedCtor(site.argList[k], callerTypedElems, callerTypedParams)
870
- if (c == null || typedElemAux(c) == null) { abort = true; break }
871
- combo.push(c)
872
- }
873
- if (abort) break
874
- siteCombos.push(combo)
875
- }
876
- if (abort) continue
877
-
878
- // Distinct combos seen across call sites.
879
- const distinct = new Map()
880
- for (const combo of siteCombos) {
881
- const key = combo.join('|')
882
- if (!distinct.has(key)) distinct.set(key, combo)
883
- }
884
- if (distinct.size < 2) continue // F-phase already mono — nothing to do
885
- if (distinct.size > MAX_CLONES_PER_FN) continue // polymorphic blow-up
886
-
887
- // Build one clone per distinct combo.
888
- const cloneByKey = new Map()
889
- for (const [key, combo] of distinct) {
890
- const suffix = combo.map(c => c.replace(/^new\./, '').replace(/\./g, '_')).join('$')
891
- let cloneName = `${func.name}$${suffix}`
892
- let n = 0
893
- while (ctx.func.names.has(cloneName)) cloneName = `${func.name}$${suffix}$${++n}`
894
-
895
- const cloneSig = {
896
- ...func.sig,
897
- params: func.sig.params.map(p => ({ ...p })),
898
- results: [...func.sig.results],
899
- }
900
- for (let i = 0; i < bimorphic.length; i++) {
901
- const k = bimorphic[i]
902
- const aux = typedElemAux(combo[i])
903
- const p = cloneSig.params[k]
904
- p.type = 'i32'
905
- p.ptrKind = VAL.TYPED
906
- p.ptrAux = aux
907
- }
908
- const clone = { ...func, name: cloneName, sig: cloneSig }
909
- ctx.func.list.push(clone)
910
- ctx.func.map.set(cloneName, clone)
911
- ctx.func.names.add(cloneName)
912
-
913
- // Mirror per-param reps under the clone's name with mono ctors at bimorphic
914
- // positions. emitFunc's preseed reads typedCtor → seeds typedElem map →
915
- // `arr[i]` lowers to direct typed load.
916
- const cloneReps = new Map()
917
- for (const [k, r] of reps) cloneReps.set(k, { ...r })
918
- for (let i = 0; i < bimorphic.length; i++) {
919
- const k = bimorphic[i]
920
- const r = cloneReps.get(k) || {}
921
- r.typedCtor = combo[i]
922
- r.val = VAL.TYPED
923
- cloneReps.set(k, r)
924
- }
925
- paramReps.set(cloneName, cloneReps)
926
-
927
- cloneByKey.set(key, clone)
928
- }
929
-
930
- // Rewrite each site's call AST to point at the matching clone.
931
- for (let i = 0; i < sites.length; i++) {
932
- const clone = cloneByKey.get(siteCombos[i].join('|'))
933
- sites[i].node[1] = clone.name
934
- }
935
- }
936
- }
937
-
938
- /**
939
- * Phase: refine ctx.types.anyDynKey using post-narrowSignatures type info.
940
- *
941
- * collectProgramFacts conservatively flags `anyDynKey=true` whenever it sees
942
- * `obj[idx]` with a non-literal-string index — but typed-array / array /
943
- * string `[]` is element access (sound for that base type), not a true
944
- * dyn-key lookup that needs the hash-table shadow on object literals.
945
- *
946
- * After narrowSignatures populates paramReps (call-site fixpoint), we can
947
- * type each `obj` in `obj[idx]` and skip the ones that are provably non-object.
948
- * If no genuine dyn-key access remains program-wide, drop anyDynKey to false
949
- * — object literals then skip the __dyn_set shadow loop (large code + perf win,
950
- * especially on hot allocators like aos.initRows).
951
- *
952
- * Live-function gate: walking dead funcs (e.g. unused benchlib helpers) would
953
- * pollute analysis with `out` params we never narrowed. Restrict to functions
954
- * reachable from exports / first-class value uses.
955
- */
956
- const NON_DYN_VTS = new Set([VAL.TYPED, VAL.ARRAY, VAL.STRING, VAL.BUFFER])
957
- const TYPED_ARRAY_CTOR = /^(Float|Int|Uint|BigInt|BigUint)(8|16|32|64)(Clamped)?Array$/
958
-
959
- function refineDynKeys(programFacts) {
960
- if (!ctx.types.anyDynKey) return
961
- const { paramReps, valueUsed } = programFacts
962
- const isLitStr = idx => Array.isArray(idx) && idx[0] === 'str' && typeof idx[1] === 'string'
963
-
964
- // Per-function type map: param vtypes from paramReps, plus locals
965
- // we can prove are typed arrays from `let v = new TypedArray(...)`. After
966
- // prepare, that node is `['()', 'new.Float64Array', ...args]`.
967
- const buildTypeMap = (funcName, body, params) => {
968
- const map = new Map()
969
- if (params) {
970
- const reps = paramReps.get(funcName)
971
- if (reps) for (let i = 0; i < params.length; i++) {
972
- const t = reps.get(i)?.val
973
- if (t != null) map.set(params[i].name, t)
974
- }
975
- }
976
- const walk = (node) => {
977
- if (!Array.isArray(node)) return
978
- const op = node[0]
979
- if (op === 'let' || op === 'const') {
980
- for (let i = 1; i < node.length; i++) {
981
- const d = node[i]
982
- if (!Array.isArray(d) || d[0] !== '=' || typeof d[1] !== 'string') continue
983
- const init = d[2]
984
- let ctor = null
985
- if (Array.isArray(init) && init[0] === '()' && typeof init[1] === 'string' && init[1].startsWith('new.'))
986
- ctor = init[1].slice(4)
987
- if (ctor && TYPED_ARRAY_CTOR.test(ctor)) map.set(d[1], VAL.TYPED)
988
- else if (typeof init === 'string' && map.has(init)) map.set(d[1], map.get(init))
989
- }
990
- }
991
- if (op === '=>') return // don't cross into nested arrows; they're separate funcs
992
- for (let i = 1; i < node.length; i++) walk(node[i])
993
- }
994
- walk(body)
995
- return map
996
- }
145
+ const cloneRepMap = map => map ? new Map([...map].map(([k, v]) => [k, { ...v }])) : null
997
146
 
998
- let real = false
999
- const visit = (typeMap, node) => {
1000
- if (real || !Array.isArray(node)) return
1001
- const op = node[0]
1002
- if (op === '[]') {
1003
- const idx = node[2]
1004
- if (!isLitStr(idx)) {
1005
- const obj = node[1]
1006
- const vt = typeof obj === 'string' ? typeMap.get(obj) : null
1007
- if (!NON_DYN_VTS.has(vt)) real = true
1008
- }
1009
- } else if (op === 'for-in') real = true
1010
- if (op === '=>') return
1011
- for (let i = 1; i < node.length; i++) visit(typeMap, node[i])
1012
- }
1013
-
1014
- // Live: anything reachable from exports/first-class value uses. Skipping
1015
- // dead helpers (unused benchlib imports) keeps their generic params from
1016
- // pretending to be dyn-key access.
1017
- const isLive = f => f.exported || paramReps.has(f.name) || (valueUsed && valueUsed.has(f.name))
1018
-
1019
- const topMap = buildTypeMap(null, null, null)
1020
- for (const f of ctx.func.list) {
1021
- if (real) break
1022
- if (!f.body || !isLive(f)) continue
1023
- visit(buildTypeMap(f.name, f.body, f.sig?.params), f.body)
1024
- }
1025
- if (!real && ctx.module.moduleInits) for (const mi of ctx.module.moduleInits) {
1026
- if (real) break
1027
- visit(topMap, mi)
1028
- }
1029
-
1030
- if (!real) ctx.types.anyDynKey = false
147
+ function enterFunc(func) {
148
+ ctx.func.stack = []
149
+ ctx.func.uniq = 0
150
+ ctx.func.current = func.sig
151
+ ctx.func.body = func.body
152
+ ctx.func.directClosures = null
153
+ ctx.func.localProps = null
1031
154
  }
1032
155
 
1033
- /**
1034
- * Phase: emit one user function to WAT IR.
1035
- *
1036
- * Reads the (already-narrowed) `func.sig` and `programFacts.paramReps[name]`
1037
- * to seed per-param val reps / schema bindings; emits body via emit / emitBody.
1038
- *
1039
- * Mutates ctx.func.* per-function state (locals, boxed, repByLocal, …) and
1040
- * ctx.schema.vars (restored on exit so bindings don't leak across functions).
1041
- */
1042
- function emitFunc(func, programFacts) {
156
+ function analyzeFuncForEmit(func, programFacts) {
1043
157
  const { paramReps } = programFacts
158
+ if (func.raw) return null
1044
159
 
1045
- // Raw WAT functions (e.g., _alloc, _reset from memory module)
1046
- if (func.raw) return parseWat(func.raw)
1047
-
1048
- const { name, body, exported, sig } = func
1049
- const multi = sig.results.length > 1
1050
-
1051
- // Reset per-function state
1052
- ctx.func.stack = []
1053
- ctx.func.uniq = 0
1054
- ctx.func.current = sig
1055
- ctx.func.body = body
1056
- ctx.func.directClosures = null
160
+ const { name, body, sig } = func
161
+ enterFunc(func)
1057
162
 
1058
- // Pre-analyze local types from body
1059
- // Block body vs object literal: object has ':' property nodes
1060
163
  const block = Array.isArray(body) && body[0] === '{}' && body[1]?.[0] !== ':'
1061
- ctx.func.boxed = new Map() // variable name → cell local name (i32) for mutable capture
1062
- ctx.func.localProps = null // reset per function
1063
- ctx.func.repByLocal = null // Map<name, ValueRep> — populated lazily; reset per function
164
+ ctx.func.boxed = new Map()
165
+ ctx.func.repByLocal = null
1064
166
  ctx.types.typedElem = ctx.scope.globalTypedElem ? new Map(ctx.scope.globalTypedElem) : null
1065
- // Pre-seed cross-call param facts BEFORE analyzeLocals/analyzeValTypes(body) so that
1066
- // when the walker sees `const b0 = arr[i]` or `let n = arr.length`, lookupValType(arr)
1067
- // already resolves to VAL.TYPED — letting valTypeOf's `[]` rule propagate VAL.NUMBER
1068
- // to b0 (skips __to_num) and exprType's `.length` rule keep n as i32 (skips per-iter
1069
- // f64.convert_i32_s + i32.trunc_sat_f64_s on the loop counter). Without this seed,
1070
- // params don't gain VAL.TYPED until after analyzeLocals freezes counter widths.
167
+
1071
168
  const _reps = paramReps.get(name)
1072
169
  if (_reps) {
1073
170
  for (const [k, r] of _reps) {
@@ -1117,6 +214,39 @@ function emitFunc(func, programFacts) {
1117
214
  if (p.ptrAux != null) fields.ptrAux = p.ptrAux
1118
215
  updateRep(p.name, fields)
1119
216
  }
217
+
218
+ return {
219
+ block,
220
+ locals: new Map(ctx.func.locals),
221
+ boxed: new Map(ctx.func.boxed),
222
+ typedElem: ctx.types.typedElem ? new Map(ctx.types.typedElem) : null,
223
+ repByLocal: cloneRepMap(ctx.func.repByLocal),
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Phase: emit one user function to WAT IR.
229
+ *
230
+ * Reads precomputed `funcFacts` and the narrowed `func.sig`; applies scoped
231
+ * schema param bindings during emission so they cannot leak between functions.
232
+ */
233
+ function emitFunc(func, funcFacts, programFacts) {
234
+ const { paramReps } = programFacts
235
+
236
+ // Raw WAT functions (e.g., _alloc, _reset from memory module)
237
+ if (func.raw) return parseWat(func.raw)
238
+
239
+ const { name, body, exported, sig } = func
240
+ const multi = sig.results.length > 1
241
+ const _reps = paramReps.get(name)
242
+
243
+ enterFunc(func)
244
+ const block = funcFacts.block
245
+ ctx.func.locals = new Map(funcFacts.locals)
246
+ ctx.func.boxed = new Map(funcFacts.boxed)
247
+ ctx.func.repByLocal = cloneRepMap(funcFacts.repByLocal)
248
+ ctx.types.typedElem = funcFacts.typedElem ? new Map(funcFacts.typedElem) : null
249
+
1120
250
  // D: Apply call-site param facts (only if body analysis didn't already set them).
1121
251
  // Schema bindings additionally write into ctx.schema.vars so prop-access dispatch
1122
252
  // hits the slot map. ctx.schema.vars is saved/restored so bindings don't leak.
@@ -1862,7 +992,7 @@ function stripStaticDataPrefix(sec) {
1862
992
  * @param {import('./prepare.js').ASTNode} ast - Prepared AST
1863
993
  * @returns {Array} Complete WASM module as S-expression
1864
994
  */
1865
- export default function compile(ast) {
995
+ export default function compile(ast, profiler) {
1866
996
  // Populate known function names + lookup map on ctx.func for direct call detection
1867
997
  ctx.func.names.clear()
1868
998
  ctx.func.map.clear()
@@ -1918,105 +1048,11 @@ export default function compile(ast) {
1918
1048
  }
1919
1049
  }
1920
1050
 
1921
- // Pre-scan module-scope value types so functions can dispatch methods on globals.
1922
- // Also scan moduleInits so cross-module imports (e.g. regex literals from util.js)
1923
- // resolve to the correct static dispatch path.
1924
- const scanStmts = (root) => {
1925
- if (!root) return
1926
- const stmts = Array.isArray(root) && root[0] === ';' ? root.slice(1) : [root]
1927
- for (const s of stmts) {
1928
- if (!Array.isArray(s) || (s[0] !== 'const' && s[0] !== 'let')) continue
1929
- for (const decl of s.slice(1)) {
1930
- if (!Array.isArray(decl) || decl[0] !== '=' || typeof decl[1] !== 'string') continue
1931
- const vt = valTypeOf(decl[2])
1932
- if (vt) {
1933
- if (!ctx.scope.globalValTypes) ctx.scope.globalValTypes = new Map()
1934
- ctx.scope.globalValTypes.set(decl[1], vt)
1935
- if (vt === VAL.REGEX && ctx.runtime.regex) ctx.runtime.regex.vars.set(decl[1], decl[2])
1936
- }
1937
- const ctor = typedElemCtor(decl[2])
1938
- if (ctor) {
1939
- if (!ctx.scope.globalTypedElem) ctx.scope.globalTypedElem = new Map()
1940
- ctx.scope.globalTypedElem.set(decl[1], ctor)
1941
- }
1942
- }
1943
- }
1944
- }
1945
- scanStmts(ast)
1946
- if (ctx.module.moduleInits) for (const init of ctx.module.moduleInits) scanStmts(init)
1947
-
1948
- // Unbox const TYPED globals: change `(mut f64)` slot to `(mut i32)` and store the raw
1949
- // pointer offset. Reads tag the global.get with ptrKind=TYPED + ptrAux=elemType so
1950
- // typed-array consumers (.[]/.buffer/…) can resolve through ptrOffsetIR without ever
1951
- // calling __ptr_offset on a NaN-box. Init still flows through emit.js, but the assign
1952
- // coerces via asPtrOffset(val, VAL.TYPED) — one bit-extract at startup, then every
1953
- // hot read is a plain `global.get` of an i32.
1954
- if (ctx.scope.globalTypedElem && ctx.scope.consts) {
1955
- for (const [name, ctor] of ctx.scope.globalTypedElem) {
1956
- if (!ctx.scope.consts.has(name)) continue
1957
- if (ctx.scope.globalValTypes?.get(name) !== VAL.TYPED) continue
1958
- const aux = typedElemAux(ctor)
1959
- if (aux == null) continue
1960
- const decl = ctx.scope.globals.get(name)
1961
- if (typeof decl !== 'string' || !decl.includes('mut f64')) continue
1962
- ctx.scope.globals.set(name, `(global $${name} (mut i32) (i32.const 0))`)
1963
- ctx.scope.globalTypes.set(name, 'i32')
1964
- updateGlobalRep(name, { ptrKind: VAL.TYPED, ptrAux: aux })
1965
- }
1966
- }
1967
-
1968
- // === ProgramFacts: single whole-program walk over ast + user funcs + moduleInits ===
1969
- // See collectProgramFacts (top of file) for the contract. ctx.types.* mirrors are
1970
- // kept here because ir.js consumes them at emit time (will be replaced when emit
1971
- // takes facts explicitly — S3).
1972
- const programFacts = collectProgramFacts(ast)
1973
- ctx.types.dynKeyVars = programFacts.dynVars
1974
- ctx.types.anyDynKey = programFacts.anyDyn
1975
-
1976
- // Materialize auto-box schemas from collected propMap
1977
- if (ast && ctx.schema.register) {
1978
- for (const [name, props] of programFacts.propMap) {
1979
- if (ctx.schema.vars.has(name)) {
1980
- const existing = ctx.schema.resolve(name)
1981
- const newProps = [...props].filter(p => !existing.includes(p))
1982
- if (newProps.length) {
1983
- const merged = [...existing, ...newProps]
1984
- const mergedId = ctx.schema.register(merged)
1985
- ctx.schema.vars.set(name, mergedId)
1986
- }
1987
- continue
1988
- }
1989
- const valueProps = [...props].filter(p => !ctx.func.names.has(`${name}$${p}`))
1990
- if (!valueProps.length) continue
1991
- const allProps = [...props]
1992
- const schema = ['__inner__', ...allProps]
1993
- const schemaId = ctx.schema.register(schema)
1994
- ctx.schema.vars.set(name, schemaId)
1995
- if (ctx.func.names.has(name) && !ctx.scope.globals.has(name))
1996
- ctx.scope.globals.set(name, `(global $${name} (mut f64) (f64.const 0))`)
1997
- if (!ctx.schema.autoBox) ctx.schema.autoBox = new Map()
1998
- ctx.schema.autoBox.set(name, { schemaId, schema })
1999
- }
2000
- }
2001
-
2002
- // Dynamic closure ABI width: max param count (`=>` defs), max call arity, rest/spread
2003
- // accumulated by walkFacts above. $ftN type, call-site padding, and body slot decls
2004
- // use this instead of the static MAX_CLOSURE_ARITY cap. hasRest adds +1 for rest
2005
- // overflow. hasSpread + hasRest together force MAX (spread expands unknown element
2006
- // count at runtime, and any rest receiver may consume them).
2007
- if (ctx.closure.make) {
2008
- const { hasSpread, hasRest, maxCall, maxDef } = programFacts
2009
- const floor = ctx.closure.floor ?? 0
2010
- ctx.closure.width = (hasSpread && hasRest)
2011
- ? MAX_CLOSURE_ARITY
2012
- : Math.min(MAX_CLOSURE_ARITY, Math.max(maxCall, maxDef + (hasRest ? 1 : 0), floor))
2013
- }
2014
-
2015
- narrowSignatures(programFacts, ast)
2016
- specializeBimorphicTyped(programFacts)
2017
- refineDynKeys(programFacts)
1051
+ const programFacts = timePhase(profiler, 'plan', () => plan(ast))
2018
1052
 
2019
- const funcs = ctx.func.list.map(func => emitFunc(func, programFacts))
1053
+ const funcFacts = new Map()
1054
+ for (const func of ctx.func.list) if (!func.raw) funcFacts.set(func, analyzeFuncForEmit(func, programFacts))
1055
+ const funcs = ctx.func.list.map(func => emitFunc(func, funcFacts.get(func), programFacts))
2020
1056
  funcs.push(...synthesizeBoundaryWrappers())
2021
1057
 
2022
1058
  const closureFuncs = []