@gmitch215/folio 1.0.0 → 1.0.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/dist/extract.js CHANGED
@@ -1,12 +1,64 @@
1
1
  import binaryen from 'binaryen';
2
2
  import { restoreImportOrder } from "./import-order.js";
3
- /** Calibrated on Apple M2 Pro; see `results/20261020-regress/admission-calibration.summary.json`. */
3
+ /** Calibrated on Apple M2 Pro; see `results/execution/admission/admission-calibration.summary.json`. */
4
4
  export const DEFAULT_MINIMUM_REGION_WORK = 200_000;
5
5
  export const DEFAULT_ASSUMED_TRIP_COUNT = 1000;
6
6
  // a tracked load or store costs about this many plain instructions in a speculative lane
7
7
  const ACCESS_COST = 3600;
8
8
  const CALL_COST = 2;
9
9
  const SCALE_LIMIT = 2 ** 50;
10
+ const supported = new Set([
11
+ binaryen.BlockId,
12
+ binaryen.IfId,
13
+ binaryen.LoopId,
14
+ binaryen.BreakId,
15
+ binaryen.SwitchId,
16
+ binaryen.CallId,
17
+ binaryen.CallIndirectId,
18
+ binaryen.LocalGetId,
19
+ binaryen.LocalSetId,
20
+ binaryen.GlobalGetId,
21
+ binaryen.GlobalSetId,
22
+ binaryen.LoadId,
23
+ binaryen.StoreId,
24
+ binaryen.MemoryCopyId,
25
+ binaryen.MemoryFillId,
26
+ binaryen.MemoryInitId,
27
+ binaryen.DataDropId,
28
+ binaryen.MemorySizeId,
29
+ binaryen.MemoryGrowId,
30
+ binaryen.TableSizeId,
31
+ binaryen.ConstId,
32
+ binaryen.UnaryId,
33
+ binaryen.BinaryId,
34
+ binaryen.SelectId,
35
+ binaryen.DropId,
36
+ binaryen.ReturnId,
37
+ binaryen.NopId,
38
+ binaryen.UnreachableId
39
+ ]);
40
+ const pureNodes = new Set([
41
+ binaryen.BlockId,
42
+ binaryen.IfId,
43
+ binaryen.LoopId,
44
+ binaryen.BreakId,
45
+ binaryen.SwitchId,
46
+ binaryen.CallId,
47
+ binaryen.LocalGetId,
48
+ binaryen.LocalSetId,
49
+ binaryen.LoadId,
50
+ binaryen.StoreId,
51
+ binaryen.MemoryCopyId,
52
+ binaryen.MemoryFillId,
53
+ binaryen.ConstId,
54
+ binaryen.UnaryId,
55
+ binaryen.BinaryId,
56
+ binaryen.SelectId,
57
+ binaryen.DropId,
58
+ binaryen.ReturnId,
59
+ binaryen.NopId,
60
+ binaryen.UnreachableId
61
+ ]);
10
62
  const raw = binaryen;
11
63
  const numeric = new Set([binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64]);
12
64
  function info(expression) {
@@ -287,6 +339,215 @@ export function admission(options) {
287
339
  throw new RangeError('invalid assumedTripCount');
288
340
  return { minimumWork, assumedTrips };
289
341
  }
342
+ // every function on a call cycle, in discovery order
343
+ function recursiveFunctions(calls) {
344
+ const indexes = new Map();
345
+ const lowlinks = new Map();
346
+ const stack = [];
347
+ const active = new Set();
348
+ const recursive = new Set();
349
+ const components = (name) => {
350
+ indexes.set(name, indexes.size);
351
+ lowlinks.set(name, indexes.get(name));
352
+ stack.push(name);
353
+ active.add(name);
354
+ for (const target of calls.get(name) ?? []) {
355
+ if (!calls.has(target))
356
+ continue;
357
+ if (!indexes.has(target)) {
358
+ components(target);
359
+ lowlinks.set(name, Math.min(lowlinks.get(name), lowlinks.get(target)));
360
+ }
361
+ else if (active.has(target))
362
+ lowlinks.set(name, Math.min(lowlinks.get(name), indexes.get(target)));
363
+ }
364
+ if (lowlinks.get(name) !== indexes.get(name))
365
+ return;
366
+ const component = [];
367
+ let member;
368
+ do {
369
+ member = stack.pop();
370
+ active.delete(member);
371
+ component.push(member);
372
+ } while (member !== name);
373
+ if (component.length > 1 || calls.get(name)?.has(name))
374
+ for (const member of component)
375
+ recursive.add(member);
376
+ };
377
+ for (const name of calls.keys())
378
+ if (!indexes.has(name))
379
+ components(name);
380
+ return recursive;
381
+ }
382
+ // memoized per-function work; a call cycle is cut at its back edge, so the estimate of a recursive
383
+ // function counts one level of its own calls and always terminates
384
+ function workModel(functions, included, assumedTrips) {
385
+ const known = new Map();
386
+ const termsOf = (name) => {
387
+ let terms = known.get(name);
388
+ if (!terms) {
389
+ known.set(name, []);
390
+ const f = functions.get(name);
391
+ const written = new Set();
392
+ const scan = (e) => {
393
+ const v = info(e);
394
+ if (v.id === binaryen.LocalSetId)
395
+ written.add(v.index);
396
+ for (const child of children(v))
397
+ scan(child);
398
+ };
399
+ scan(f.body);
400
+ const count = binaryen.expandType(f.params).length;
401
+ terms = estimateTerms(f.body, workOf, assumedTrips, {
402
+ input: (index) => index < count && !written.has(index),
403
+ counter: (index) => written.has(index)
404
+ });
405
+ known.set(name, terms);
406
+ }
407
+ return terms;
408
+ };
409
+ const workOf = (name) => included(name) ? settleWork(termsOf(name), assumedTrips) : undefined;
410
+ return { termsOf, workOf };
411
+ }
412
+ // a span with every reason it cannot move into another function; none means it can
413
+ function summarizeSpan(expression, allow = {}) {
414
+ const span = {
415
+ expression,
416
+ reads: new Map(),
417
+ writes: new Set(),
418
+ locals: new Set(),
419
+ memoryWrite: false,
420
+ compute: false
421
+ };
422
+ const refusals = new Set();
423
+ const labels = new Set();
424
+ const targets = [];
425
+ if (info(expression).type !== binaryen.none)
426
+ refusals.add('statement has a value');
427
+ const visit = (e) => {
428
+ const v = info(e);
429
+ if (v.id === binaryen.CallId) {
430
+ if (!allow.call?.(v.target))
431
+ refusals.add('call outside the worker set');
432
+ }
433
+ else if (v.id === binaryen.GlobalGetId) {
434
+ if (!allow.global?.(v.name))
435
+ refusals.add('global access');
436
+ }
437
+ else if (v.id === binaryen.CallIndirectId)
438
+ refusals.add('indirect call');
439
+ else if (v.id === binaryen.ReturnId)
440
+ refusals.add('return in the body');
441
+ else if (!pureNodes.has(v.id))
442
+ refusals.add('impure expression');
443
+ if (v.isAtomic)
444
+ refusals.add('atomic access');
445
+ if (![binaryen.none, binaryen.unreachable].includes(v.type) && !numeric.has(v.type))
446
+ refusals.add('non-numeric value');
447
+ if ((v.id === binaryen.BlockId || v.id === binaryen.LoopId) && v.name)
448
+ labels.add(v.name);
449
+ if (v.id === binaryen.BreakId)
450
+ targets.push(v.name);
451
+ if (v.id === binaryen.SwitchId)
452
+ targets.push(...v.names, v.defaultName);
453
+ if (v.id === binaryen.LocalGetId) {
454
+ span.locals.add(v.index);
455
+ span.reads.set(v.index, (span.reads.get(v.index) ?? 0) + 1);
456
+ }
457
+ if (v.id === binaryen.LocalSetId) {
458
+ span.locals.add(v.index);
459
+ span.writes.add(v.index);
460
+ }
461
+ if ([binaryen.StoreId, binaryen.MemoryCopyId, binaryen.MemoryFillId].includes(v.id))
462
+ span.memoryWrite = true;
463
+ if ([binaryen.LoopId, binaryen.IfId, binaryen.BinaryId, binaryen.UnaryId].includes(v.id))
464
+ span.compute = true;
465
+ for (const child of children(v))
466
+ visit(child);
467
+ };
468
+ visit(expression);
469
+ if (!targets.every((target) => labels.has(target)))
470
+ refusals.add('branch escapes the body');
471
+ return { span, refusals };
472
+ }
473
+ // locals the spans write that something else reads, or that they read before assigning
474
+ function carriedLocals(spans, totalReads) {
475
+ const reads = new Map();
476
+ const writes = new Set();
477
+ for (const span of spans) {
478
+ for (const [index, amount] of span.reads)
479
+ reads.set(index, (reads.get(index) ?? 0) + amount);
480
+ for (const index of span.writes)
481
+ writes.add(index);
482
+ }
483
+ const carried = new Set([...writes].filter((index) => (totalReads.get(index) ?? 0) !== (reads.get(index) ?? 0)));
484
+ const exits = new Map();
485
+ const intersect = (paths) => paths.length
486
+ ? new Set([...paths[0]].filter((index) => paths.every((path) => path.has(index))))
487
+ : undefined;
488
+ const flow = (expression, incoming) => {
489
+ const v = info(expression);
490
+ let assigned = new Set(incoming);
491
+ if (v.id === binaryen.LocalGetId && writes.has(v.index) && !assigned.has(v.index))
492
+ carried.add(v.index);
493
+ if (v.id === binaryen.IfId) {
494
+ assigned = flow(v.condition, assigned);
495
+ if (!assigned)
496
+ return;
497
+ return intersect([flow(v.ifTrue, assigned), v.ifFalse ? flow(v.ifFalse, assigned) : assigned].filter((path) => path !== undefined));
498
+ }
499
+ if (v.id === binaryen.BlockId || v.id === binaryen.LoopId) {
500
+ if (v.name)
501
+ exits.set(v.name, []);
502
+ for (const child of children(v)) {
503
+ if (!assigned)
504
+ break;
505
+ assigned = flow(child, assigned);
506
+ }
507
+ const branches = v.name ? exits.get(v.name) : [];
508
+ if (v.name)
509
+ exits.delete(v.name);
510
+ return intersect([
511
+ ...(assigned ? [assigned] : []),
512
+ ...(v.id === binaryen.BlockId ? branches : [])
513
+ ]);
514
+ }
515
+ for (const child of children(v)) {
516
+ if (!assigned)
517
+ return;
518
+ assigned = flow(child, assigned);
519
+ }
520
+ if (!assigned)
521
+ return;
522
+ if (v.id === binaryen.LocalSetId)
523
+ assigned.add(v.index);
524
+ if (v.id === binaryen.BreakId || v.id === binaryen.SwitchId) {
525
+ const targets = v.id === binaryen.SwitchId ? [...v.names, v.defaultName] : [v.name];
526
+ for (const target of targets)
527
+ exits.get(target)?.push(new Set(assigned));
528
+ if (v.id === binaryen.SwitchId || !v.condition)
529
+ return;
530
+ }
531
+ return v.id === binaryen.UnreachableId ? undefined : assigned;
532
+ };
533
+ let assigned = new Set();
534
+ for (const span of spans) {
535
+ if (!assigned)
536
+ break;
537
+ assigned = flow(span.expression, assigned);
538
+ }
539
+ return carried;
540
+ }
541
+ // renumbers the locals of an expression in place
542
+ function remapLocals(expression, positions) {
543
+ const v = info(expression);
544
+ if (v.id === binaryen.LocalGetId)
545
+ raw._BinaryenLocalGetSetIndex(expression, positions.get(v.index));
546
+ if (v.id === binaryen.LocalSetId)
547
+ raw._BinaryenLocalSetSetIndex(expression, positions.get(v.index));
548
+ for (const child of children(v))
549
+ remapLocals(child, positions);
550
+ }
290
551
  export function extract(original, prepareTracked, options = {}) {
291
552
  const { minimumWork, assumedTrips } = admission(options);
292
553
  let module;
@@ -304,58 +565,6 @@ export function extract(original, prepareTracked, options = {}) {
304
565
  m.setFeatures(binaryen.Features.All & ~compactImports);
305
566
  const internalMemory = memoryName(m);
306
567
  const functions = new Map();
307
- const supported = new Set([
308
- binaryen.BlockId,
309
- binaryen.IfId,
310
- binaryen.LoopId,
311
- binaryen.BreakId,
312
- binaryen.SwitchId,
313
- binaryen.CallId,
314
- binaryen.CallIndirectId,
315
- binaryen.LocalGetId,
316
- binaryen.LocalSetId,
317
- binaryen.GlobalGetId,
318
- binaryen.GlobalSetId,
319
- binaryen.LoadId,
320
- binaryen.StoreId,
321
- binaryen.MemoryCopyId,
322
- binaryen.MemoryFillId,
323
- binaryen.MemoryInitId,
324
- binaryen.DataDropId,
325
- binaryen.MemorySizeId,
326
- binaryen.MemoryGrowId,
327
- binaryen.TableSizeId,
328
- binaryen.ConstId,
329
- binaryen.UnaryId,
330
- binaryen.BinaryId,
331
- binaryen.SelectId,
332
- binaryen.DropId,
333
- binaryen.ReturnId,
334
- binaryen.NopId,
335
- binaryen.UnreachableId
336
- ]);
337
- const pureNodes = new Set([
338
- binaryen.BlockId,
339
- binaryen.IfId,
340
- binaryen.LoopId,
341
- binaryen.BreakId,
342
- binaryen.SwitchId,
343
- binaryen.CallId,
344
- binaryen.LocalGetId,
345
- binaryen.LocalSetId,
346
- binaryen.LoadId,
347
- binaryen.StoreId,
348
- binaryen.MemoryCopyId,
349
- binaryen.MemoryFillId,
350
- binaryen.ConstId,
351
- binaryen.UnaryId,
352
- binaryen.BinaryId,
353
- binaryen.SelectId,
354
- binaryen.DropId,
355
- binaryen.ReturnId,
356
- binaryen.NopId,
357
- binaryen.UnreachableId
358
- ]);
359
568
  let outlineIndex = 0;
360
569
  const originals = Array.from({ length: m.getNumFunctions() }, (_, index) => binaryen.getFunctionInfo(m.getFunctionByIndex(index)));
361
570
  const originalBodies = new Map(originals.filter((f) => f.body).map((f) => [f.name, m.copyExpression(f.body)]));
@@ -385,126 +594,11 @@ export function extract(original, prepareTracked, options = {}) {
385
594
  if (!traversable)
386
595
  continue;
387
596
  const summarize = (expression) => {
388
- const span = {
389
- expression,
390
- reads: new Map(),
391
- writes: new Set(),
392
- locals: new Set(),
393
- memoryWrite: false,
394
- compute: false
395
- };
396
- const labels = new Set();
397
- const targets = [];
398
- let eligible = info(expression).type === binaryen.none;
399
- const visit = (e) => {
400
- const v = info(e);
401
- if (!pureNodes.has(v.id) ||
402
- v.isAtomic ||
403
- v.id === binaryen.CallId ||
404
- v.id === binaryen.ReturnId)
405
- eligible = false;
406
- if (![binaryen.none, binaryen.unreachable].includes(v.type) &&
407
- !numeric.has(v.type))
408
- eligible = false;
409
- if ((v.id === binaryen.BlockId || v.id === binaryen.LoopId) && v.name)
410
- labels.add(v.name);
411
- if (v.id === binaryen.BreakId)
412
- targets.push(v.name);
413
- if (v.id === binaryen.SwitchId)
414
- targets.push(...v.names, v.defaultName);
415
- if (v.id === binaryen.LocalGetId) {
416
- span.locals.add(v.index);
417
- span.reads.set(v.index, (span.reads.get(v.index) ?? 0) + 1);
418
- }
419
- if (v.id === binaryen.LocalSetId) {
420
- span.locals.add(v.index);
421
- span.writes.add(v.index);
422
- }
423
- if ([binaryen.StoreId, binaryen.MemoryCopyId, binaryen.MemoryFillId].includes(v.id))
424
- span.memoryWrite = true;
425
- if ([
426
- binaryen.LoopId,
427
- binaryen.IfId,
428
- binaryen.BinaryId,
429
- binaryen.UnaryId
430
- ].includes(v.id))
431
- span.compute = true;
432
- for (const child of children(v))
433
- visit(child);
434
- };
435
- visit(expression);
436
- return eligible && targets.every((target) => labels.has(target)) ? span : undefined;
597
+ const summary = summarizeSpan(expression);
598
+ return summary.refusals.size ? undefined : summary.span;
437
599
  };
438
600
  const outline = (spans) => {
439
- const reads = new Map();
440
- const writes = new Set();
441
- for (const span of spans) {
442
- for (const [index, amount] of span.reads)
443
- reads.set(index, (reads.get(index) ?? 0) + amount);
444
- for (const index of span.writes)
445
- writes.add(index);
446
- }
447
- const carried = new Set([...writes].filter((index) => (totalReads.get(index) ?? 0) !== (reads.get(index) ?? 0)));
448
- const exits = new Map();
449
- const intersect = (paths) => paths.length
450
- ? new Set([...paths[0]].filter((index) => paths.every((path) => path.has(index))))
451
- : undefined;
452
- const flow = (expression, incoming) => {
453
- const v = info(expression);
454
- let assigned = new Set(incoming);
455
- if (v.id === binaryen.LocalGetId &&
456
- writes.has(v.index) &&
457
- !assigned.has(v.index))
458
- carried.add(v.index);
459
- if (v.id === binaryen.IfId) {
460
- assigned = flow(v.condition, assigned);
461
- if (!assigned)
462
- return;
463
- return intersect([
464
- flow(v.ifTrue, assigned),
465
- v.ifFalse ? flow(v.ifFalse, assigned) : assigned
466
- ].filter((path) => path !== undefined));
467
- }
468
- if (v.id === binaryen.BlockId || v.id === binaryen.LoopId) {
469
- if (v.name)
470
- exits.set(v.name, []);
471
- for (const child of children(v)) {
472
- if (!assigned)
473
- break;
474
- assigned = flow(child, assigned);
475
- }
476
- const branches = v.name ? exits.get(v.name) : [];
477
- if (v.name)
478
- exits.delete(v.name);
479
- return intersect([
480
- ...(assigned ? [assigned] : []),
481
- ...(v.id === binaryen.BlockId ? branches : [])
482
- ]);
483
- }
484
- for (const child of children(v)) {
485
- if (!assigned)
486
- return;
487
- assigned = flow(child, assigned);
488
- }
489
- if (!assigned)
490
- return;
491
- if (v.id === binaryen.LocalSetId)
492
- assigned.add(v.index);
493
- if (v.id === binaryen.BreakId || v.id === binaryen.SwitchId) {
494
- const targets = v.id === binaryen.SwitchId ? [...v.names, v.defaultName] : [v.name];
495
- for (const target of targets)
496
- exits.get(target)?.push(new Set(assigned));
497
- if (v.id === binaryen.SwitchId || !v.condition)
498
- return;
499
- }
500
- return v.id === binaryen.UnreachableId ? undefined : assigned;
501
- };
502
- let assigned = new Set();
503
- for (const span of spans) {
504
- if (!assigned)
505
- break;
506
- assigned = flow(span.expression, assigned);
507
- }
601
+ const carried = carriedLocals(spans, totalReads);
508
602
  if (carried.size) {
509
603
  const result = [];
510
604
  let pending = [];
@@ -539,16 +633,7 @@ export function extract(original, prepareTracked, options = {}) {
539
633
  const captured = [...new Set(spans.flatMap((span) => [...span.locals]))].sort((a, b) => a - b);
540
634
  const positions = new Map(captured.map((index, position) => [index, position]));
541
635
  const body = m.block(null, spans.map((span) => m.copyExpression(span.expression)));
542
- const remap = (expression) => {
543
- const v = info(expression);
544
- if (v.id === binaryen.LocalGetId)
545
- raw._BinaryenLocalGetSetIndex(expression, positions.get(v.index));
546
- if (v.id === binaryen.LocalSetId)
547
- raw._BinaryenLocalSetSetIndex(expression, positions.get(v.index));
548
- for (const child of children(v))
549
- remap(child);
550
- };
551
- remap(body);
636
+ remapLocals(body, positions);
552
637
  let name;
553
638
  do {
554
639
  name = `__folio_inline_${outlineIndex++}`;
@@ -638,43 +723,7 @@ export function extract(original, prepareTracked, options = {}) {
638
723
  if (candidate && control)
639
724
  pure.add(f.name);
640
725
  }
641
- const indexes = new Map();
642
- const lowlinks = new Map();
643
- const stack = [];
644
- const active = new Set();
645
- const recursive = new Set();
646
- const components = (name) => {
647
- indexes.set(name, indexes.size);
648
- lowlinks.set(name, indexes.get(name));
649
- stack.push(name);
650
- active.add(name);
651
- for (const target of calls.get(name) ?? []) {
652
- if (!calls.has(target))
653
- continue;
654
- if (!indexes.has(target)) {
655
- components(target);
656
- lowlinks.set(name, Math.min(lowlinks.get(name), lowlinks.get(target)));
657
- }
658
- else if (active.has(target))
659
- lowlinks.set(name, Math.min(lowlinks.get(name), indexes.get(target)));
660
- }
661
- if (lowlinks.get(name) !== indexes.get(name))
662
- return;
663
- const component = [];
664
- let member;
665
- do {
666
- member = stack.pop();
667
- active.delete(member);
668
- component.push(member);
669
- } while (member !== name);
670
- if (component.length > 1 || calls.get(name)?.has(name))
671
- for (const member of component)
672
- recursive.add(member);
673
- };
674
- for (const name of calls.keys())
675
- if (!indexes.has(name))
676
- components(name);
677
- for (const name of recursive) {
726
+ for (const name of recursiveFunctions(calls)) {
678
727
  controllers.delete(name);
679
728
  pure.delete(name);
680
729
  diagnostics.push(`ordered native recursion: ${name}`);
@@ -692,30 +741,7 @@ export function extract(original, prepareTracked, options = {}) {
692
741
  options.refused?.('no pure function to run as a region');
693
742
  return;
694
743
  }
695
- const known = new Map();
696
- const termsOf = (name) => {
697
- let terms = known.get(name);
698
- if (!terms) {
699
- const f = functions.get(name);
700
- const written = new Set();
701
- const scan = (e) => {
702
- const v = info(e);
703
- if (v.id === binaryen.LocalSetId)
704
- written.add(v.index);
705
- for (const child of children(v))
706
- scan(child);
707
- };
708
- scan(f.body);
709
- const count = binaryen.expandType(f.params).length;
710
- terms = estimateTerms(f.body, workOf, assumedTrips, {
711
- input: (index) => index < count && !written.has(index),
712
- counter: (index) => written.has(index)
713
- });
714
- known.set(name, terms);
715
- }
716
- return terms;
717
- };
718
- const workOf = (name) => pure.has(name) ? settleWork(termsOf(name), assumedTrips) : undefined;
744
+ const { termsOf } = workModel(functions, (name) => pure.has(name), assumedTrips);
719
745
  const admitted = new Set();
720
746
  const guarded = new Map();
721
747
  for (const name of pure) {
@@ -1174,3 +1200,618 @@ export function extract(original, prepareTracked, options = {}) {
1174
1200
  module?.dispose();
1175
1201
  }
1176
1202
  }
1203
+ /** Computes the stack route of a module. A failure is reported in `diagnostics`, never thrown. */
1204
+ export function stackRoute(original, options = {}) {
1205
+ const { assumedTrips } = admission(options);
1206
+ const route = {
1207
+ eligible: false,
1208
+ constants: [],
1209
+ functions: [],
1210
+ recursive: [],
1211
+ work: Object.create(null),
1212
+ diagnostics: []
1213
+ };
1214
+ let module;
1215
+ try {
1216
+ if (memoryCount(original) !== 1) {
1217
+ route.diagnostics.push('exactly one memory required');
1218
+ return route;
1219
+ }
1220
+ module = binaryen.readBinary(original);
1221
+ if (module.getMemoryInfo().is64) {
1222
+ route.diagnostics.push('wasm64 memory');
1223
+ return route;
1224
+ }
1225
+ const compactImports = binaryen.Features
1226
+ .CompactImports;
1227
+ module.setFeatures(binaryen.Features.All & ~compactImports);
1228
+ const globals = new Map();
1229
+ for (let i = 0; i < module.getNumGlobals(); i++) {
1230
+ const g = binaryen.getGlobalInfo(module.getGlobalByIndex(i));
1231
+ const init = g.module ? undefined : info(g.init);
1232
+ const constant = init?.id === binaryen.ConstId;
1233
+ globals.set(g.name, {
1234
+ mutable: g.mutable,
1235
+ constant,
1236
+ initial: constant && g.type === binaryen.i32 ? Number(init.value) : undefined,
1237
+ refusal: g.module
1238
+ ? 'imported global'
1239
+ : !numeric.has(g.type)
1240
+ ? 'reference-typed global'
1241
+ : !constant
1242
+ ? 'initializer is not a constant'
1243
+ : g.mutable && g.type !== binaryen.i32
1244
+ ? 'mutable global is not i32'
1245
+ : undefined
1246
+ });
1247
+ }
1248
+ const bodies = [];
1249
+ for (let i = 0; i < module.getNumFunctions(); i++) {
1250
+ const f = binaryen.getFunctionInfo(module.getFunctionByIndex(i));
1251
+ if (!f.body)
1252
+ continue;
1253
+ const body = { info: f, targets: new Set(), refs: new Set() };
1254
+ if (![...binaryen.expandType(f.params), ...f.vars].every((t) => numeric.has(t)) ||
1255
+ !(f.results === binaryen.none || numeric.has(f.results)))
1256
+ body.cause = 'non-numeric signature';
1257
+ const visit = (expression) => {
1258
+ const v = info(expression);
1259
+ if (!supported.has(v.id))
1260
+ body.cause ??= 'unsupported expression';
1261
+ else if (v.id === binaryen.GlobalGetId || v.id === binaryen.GlobalSetId)
1262
+ body.refs.add(v.name);
1263
+ else if (!pureNodes.has(v.id))
1264
+ body.cause ??= 'impure expression';
1265
+ if (v.isAtomic)
1266
+ body.cause ??= 'atomic access';
1267
+ if (![binaryen.none, binaryen.unreachable].includes(v.type) && !numeric.has(v.type))
1268
+ body.cause ??= 'non-numeric value';
1269
+ if (v.id === binaryen.CallId)
1270
+ body.targets.add(v.target);
1271
+ for (const child of children(v))
1272
+ visit(child);
1273
+ };
1274
+ try {
1275
+ visit(f.body);
1276
+ }
1277
+ catch {
1278
+ body.cause ??= 'unreadable expression';
1279
+ }
1280
+ bodies.push(body);
1281
+ }
1282
+ const referenced = new Set(bodies.flatMap((body) => [...body.refs]));
1283
+ const named = [...globals.keys()].filter((name) => referenced.has(name));
1284
+ const mutable = named.filter((name) => globals.get(name).mutable);
1285
+ if (mutable.length > 1) {
1286
+ for (const name of mutable.slice(1))
1287
+ route.diagnostics.push(`refused global ${name}: second mutable global (stack candidate ${mutable[0]})`);
1288
+ return route;
1289
+ }
1290
+ const refused = new Set();
1291
+ for (const name of named) {
1292
+ const g = globals.get(name);
1293
+ if (g.refusal) {
1294
+ refused.add(name);
1295
+ route.diagnostics.push(`refused global ${name}: ${g.refusal}`);
1296
+ }
1297
+ else if (g.mutable)
1298
+ route.stack = { name, initial: g.initial };
1299
+ else
1300
+ route.constants.push(name);
1301
+ }
1302
+ if (route.stack)
1303
+ route.diagnostics.push(`stack global ${route.stack.name}`);
1304
+ for (const body of bodies)
1305
+ if (!body.cause && [...body.refs].some((name) => refused.has(name)))
1306
+ body.cause = 'refused global';
1307
+ const members = new Set(bodies.filter((body) => !body.cause).map((b) => b.info.name));
1308
+ for (let changed = true; changed;) {
1309
+ changed = false;
1310
+ for (const body of bodies) {
1311
+ if (body.cause || ![...body.targets].some((name) => !members.has(name)))
1312
+ continue;
1313
+ body.cause = 'call outside the set';
1314
+ members.delete(body.info.name);
1315
+ changed = true;
1316
+ }
1317
+ }
1318
+ const inSet = bodies.filter((body) => members.has(body.info.name));
1319
+ route.functions = inSet.map((body) => body.info.name);
1320
+ const cyclic = recursiveFunctions(new Map(inSet.map((b) => [b.info.name, b.targets])));
1321
+ route.recursive = route.functions.filter((name) => cyclic.has(name));
1322
+ const model = workModel(new Map(inSet.map((body) => [body.info.name, body.info])), (name) => members.has(name), assumedTrips);
1323
+ for (const name of route.functions)
1324
+ route.work[name] = model.workOf(name);
1325
+ route.diagnostics.push(`worker set: ${route.functions.length} of ${bodies.length} functions, ${route.recursive.length} recursive`);
1326
+ const causes = new Map();
1327
+ for (const body of bodies)
1328
+ if (body.cause)
1329
+ causes.set(body.cause, (causes.get(body.cause) ?? 0) + 1);
1330
+ if (causes.size)
1331
+ route.diagnostics.push(`excluded: ${[...causes]
1332
+ .sort(([a], [b]) => (a < b ? -1 : 1))
1333
+ .map(([cause, count]) => `${count} ${cause}`)
1334
+ .join(', ')}`);
1335
+ route.eligible = route.functions.length > 0;
1336
+ if (!route.eligible)
1337
+ route.diagnostics.push('no function can run on a worker');
1338
+ return route;
1339
+ }
1340
+ catch (error) {
1341
+ return {
1342
+ eligible: false,
1343
+ constants: [],
1344
+ functions: [],
1345
+ recursive: [],
1346
+ work: Object.create(null),
1347
+ diagnostics: [
1348
+ `stack route unavailable: ${error instanceof Error ? error.message : String(error)}`
1349
+ ]
1350
+ };
1351
+ }
1352
+ finally {
1353
+ module?.dispose();
1354
+ }
1355
+ }
1356
+ const emptyIteration = (diagnostics) => ({
1357
+ eligible: false,
1358
+ locals: [],
1359
+ diagnostics
1360
+ });
1361
+ /**
1362
+ * Finds an owner whose single loop is a countdown over independent calls into the stack route's
1363
+ * worker set and outlines one iteration of it. A refusal is a named diagnostic, never an exception.
1364
+ */
1365
+ export function iterationRoute(original, route) {
1366
+ if (!route.eligible)
1367
+ return emptyIteration([
1368
+ `stack route refused: ${route.diagnostics.join('; ') || 'empty set'}`
1369
+ ]);
1370
+ let module;
1371
+ try {
1372
+ module = binaryen.readBinary(original);
1373
+ const m = module;
1374
+ const compactImports = binaryen.Features
1375
+ .CompactImports;
1376
+ m.setFeatures(binaryen.Features.All & ~compactImports);
1377
+ const members = new Set(route.functions);
1378
+ const stack = route.stack?.name;
1379
+ const constants = new Set(route.constants);
1380
+ const refusals = [];
1381
+ for (let i = 0; i < m.getNumFunctions(); i++) {
1382
+ const f = binaryen.getFunctionInfo(m.getFunctionByIndex(i));
1383
+ if (!f.body || !callsInLoop(f.body, members))
1384
+ continue;
1385
+ const plan = outlineOwner(m, f, { members, stack, constants, route });
1386
+ if (plan.route) {
1387
+ plan.route.diagnostics.unshift(...refusals);
1388
+ return plan.route;
1389
+ }
1390
+ for (const reason of plan.refusals)
1391
+ if (refusals.length < 16)
1392
+ refusals.push(`refused loop in ${f.name}: ${reason}`);
1393
+ }
1394
+ refusals.push('no loop calls into the worker set');
1395
+ return emptyIteration(refusals);
1396
+ }
1397
+ catch (error) {
1398
+ return emptyIteration([
1399
+ `iteration route unavailable: ${error instanceof Error ? error.message : String(error)}`
1400
+ ]);
1401
+ }
1402
+ finally {
1403
+ module?.dispose();
1404
+ }
1405
+ }
1406
+ // does any loop in the body contain a call to a member of the set
1407
+ function callsInLoop(body, members) {
1408
+ const visit = (expression, inLoop) => {
1409
+ const v = info(expression);
1410
+ if (inLoop && v.id === binaryen.CallId && members.has(v.target))
1411
+ return true;
1412
+ return children(v).some((child) => visit(child, inLoop || v.id === binaryen.LoopId));
1413
+ };
1414
+ try {
1415
+ return visit(body, false);
1416
+ }
1417
+ catch {
1418
+ return false;
1419
+ }
1420
+ }
1421
+ // `local = local + c`, `local - c`, `local + other` or `local - other` as a statement
1422
+ function strideUpdate(statement) {
1423
+ const set = info(statement);
1424
+ if (set.id !== binaryen.LocalSetId || set.isTee)
1425
+ return;
1426
+ const next = info(set.value);
1427
+ if (next.id !== binaryen.BinaryId)
1428
+ return;
1429
+ const [left, right] = [info(next.left), info(next.right)];
1430
+ const isSelf = (v) => v.id === binaryen.LocalGetId && v.index === set.index;
1431
+ const constant = (v) => v.id === binaryen.ConstId && typeof v.value === 'number' ? v : undefined;
1432
+ const other = (v) => v.id === binaryen.LocalGetId && v.index !== set.index ? v.index : undefined;
1433
+ if (next.op === binaryen.AddInt32) {
1434
+ if (isSelf(left) && constant(right))
1435
+ return { local: set.index, stride: right.value | 0 };
1436
+ if (isSelf(right) && constant(left))
1437
+ return { local: set.index, stride: left.value | 0 };
1438
+ if (isSelf(left) && other(right) !== undefined)
1439
+ return { local: set.index, stride: 1, strideLocal: other(right) };
1440
+ if (isSelf(right) && other(left) !== undefined)
1441
+ return { local: set.index, stride: 1, strideLocal: other(left) };
1442
+ }
1443
+ if (next.op === binaryen.SubInt32 && isSelf(left)) {
1444
+ if (constant(right))
1445
+ return { local: set.index, stride: -right.value | 0 };
1446
+ if (other(right) !== undefined)
1447
+ return { local: set.index, stride: -1, strideLocal: other(right) };
1448
+ }
1449
+ }
1450
+ function outlineOwner(m, f, context) {
1451
+ const { members, stack, constants } = context;
1452
+ const refuse = new Set();
1453
+ const localTypes = [...binaryen.expandType(f.params), ...f.vars];
1454
+ const parameterCount = binaryen.expandType(f.params).length;
1455
+ if (!localTypes.every((type) => numeric.has(type)))
1456
+ return { refusals: ['non-numeric signature'] };
1457
+ // one pass: loops, write and read counts, the loop's own writes
1458
+ const loops = [];
1459
+ const writes = new Map();
1460
+ const totalReads = new Map();
1461
+ const scan = (expression) => {
1462
+ const v = info(expression);
1463
+ if (v.id === binaryen.LoopId)
1464
+ loops.push(expression);
1465
+ if (v.id === binaryen.LocalSetId)
1466
+ writes.set(v.index, (writes.get(v.index) ?? 0) + 1);
1467
+ if (v.id === binaryen.LocalGetId)
1468
+ totalReads.set(v.index, (totalReads.get(v.index) ?? 0) + 1);
1469
+ for (const child of children(v))
1470
+ scan(child);
1471
+ };
1472
+ scan(f.body);
1473
+ if (loops.length !== 1)
1474
+ return { refusals: [`${loops.length} loops, one required`] };
1475
+ const loopExpression = loops[0];
1476
+ const loop = info(loopExpression);
1477
+ // the blocks that lead to the loop, outermost first
1478
+ const levels = [];
1479
+ const locate = (expression) => {
1480
+ if (expression === loopExpression)
1481
+ return true;
1482
+ const v = info(expression);
1483
+ if (v.id !== binaryen.BlockId)
1484
+ return false;
1485
+ for (let i = 0; i < v.children.length; i++) {
1486
+ if (!locate(v.children[i]))
1487
+ continue;
1488
+ levels.unshift({ children: v.children, index: i });
1489
+ return true;
1490
+ }
1491
+ return false;
1492
+ };
1493
+ if (!locate(f.body))
1494
+ return { refusals: ['the loop is not reached through blocks'] };
1495
+ const before = levels.flatMap((level) => level.children.slice(0, level.index));
1496
+ const after = levels.flatMap((level) => level.children.slice(level.index + 1));
1497
+ // the trip count: a countdown that ends on its own decrement
1498
+ const counter = countdownLocal(loop);
1499
+ if (counter === undefined || localTypes[counter] !== binaryen.i32)
1500
+ return { refusals: ['trip count is not computable before the loop starts'] };
1501
+ const loopWrites = new Map();
1502
+ const countLoopWrites = (expression) => {
1503
+ const v = info(expression);
1504
+ if (v.id === binaryen.LocalSetId)
1505
+ loopWrites.set(v.index, (loopWrites.get(v.index) ?? 0) + 1);
1506
+ for (const child of children(v))
1507
+ countLoopWrites(child);
1508
+ };
1509
+ countLoopWrites(loopExpression);
1510
+ if ((loopWrites.get(counter) ?? 0) !== 1)
1511
+ return { refusals: ['trip count is not computable before the loop starts'] };
1512
+ // the loop body, the trailing stride updates and the back edge; a step is a constant or an i32
1513
+ // local the loop never writes
1514
+ const body = info(loop.body);
1515
+ const statements = body.id === binaryen.BlockId ? body.children : [loop.body];
1516
+ const stepIsInvariant = (update) => update.strideLocal === undefined ||
1517
+ (localTypes[update.strideLocal] === binaryen.i32 && !loopWrites.get(update.strideLocal));
1518
+ const updates = new Map([[counter, { local: counter, stride: -1 }]]);
1519
+ let end = statements.length - 1;
1520
+ while (end > 0) {
1521
+ const update = strideUpdate(statements[end - 1]);
1522
+ if (!update ||
1523
+ updates.has(update.local) ||
1524
+ localTypes[update.local] !== binaryen.i32 ||
1525
+ loopWrites.get(update.local) !== 1 ||
1526
+ !stepIsInvariant(update))
1527
+ break;
1528
+ updates.set(update.local, update);
1529
+ end--;
1530
+ }
1531
+ // top-level updates that stay in the body: iterate runs them, so later statements see the new
1532
+ // value; a stride-shaped statement that cannot stay names why, used if its local is carried
1533
+ const midUpdates = new Map();
1534
+ const shaped = new Map();
1535
+ const scanUpdates = (expression, top, conditional) => {
1536
+ const v = info(expression);
1537
+ const update = v.id === binaryen.LocalSetId ? strideUpdate(expression) : undefined;
1538
+ if (update && update.local !== counter && localTypes[update.local] === binaryen.i32) {
1539
+ if (!top)
1540
+ shaped.set(update.local, conditional
1541
+ ? 'stride update is conditional'
1542
+ : 'stride update is not at the top level of the body');
1543
+ else if (loopWrites.get(update.local) !== 1)
1544
+ shaped.set(update.local, 'stride update of a local the loop also writes elsewhere');
1545
+ else if (!stepIsInvariant(update))
1546
+ shaped.set(update.local, 'stride is written in the loop');
1547
+ else
1548
+ midUpdates.set(update.local, update);
1549
+ }
1550
+ for (const child of children(v))
1551
+ scanUpdates(child, false, conditional || v.id === binaryen.IfId);
1552
+ };
1553
+ for (const statement of statements.slice(0, end))
1554
+ scanUpdates(statement, true, false);
1555
+ for (const [local, update] of midUpdates)
1556
+ updates.set(local, update);
1557
+ const spans = [];
1558
+ for (const statement of statements.slice(0, end)) {
1559
+ const summary = summarizeSpan(statement, {
1560
+ call: (target) => members.has(target),
1561
+ global: (name) => name === stack || constants.has(name)
1562
+ });
1563
+ for (const reason of summary.refusals)
1564
+ refuse.add(reason);
1565
+ spans.push(summary.span);
1566
+ }
1567
+ if (!spans.length)
1568
+ refuse.add('empty loop body');
1569
+ // the frame: `sp = global - size` in the owner's prologue
1570
+ let frame;
1571
+ if (stack) {
1572
+ const frameOf = (expression) => {
1573
+ const sub = info(expression);
1574
+ if (sub.id !== binaryen.BinaryId || sub.op !== binaryen.SubInt32)
1575
+ return;
1576
+ const [from, size] = [info(sub.left), info(sub.right)];
1577
+ if (from.id === binaryen.GlobalGetId &&
1578
+ from.name === stack &&
1579
+ size.id === binaryen.ConstId)
1580
+ return size.value;
1581
+ };
1582
+ const top = levels[0] ? levels[0].children.slice(0, levels[0].index) : [];
1583
+ for (const [i, statement] of top.entries()) {
1584
+ const v = info(statement);
1585
+ if (v.id === binaryen.GlobalSetId && v.name === stack) {
1586
+ const tee = info(v.value);
1587
+ const size = tee.id === binaryen.LocalSetId && tee.isTee ? frameOf(tee.value) : undefined;
1588
+ if (size !== undefined)
1589
+ frame = { global: stack, size, local: tee.index, copy: true };
1590
+ }
1591
+ if (v.id === binaryen.LocalSetId && !v.isTee && frameOf(v.value) !== undefined) {
1592
+ const next = top[i + 1] ? info(top[i + 1]) : undefined;
1593
+ const value = next?.id === binaryen.GlobalSetId ? info(next.value) : undefined;
1594
+ if (next?.name === stack &&
1595
+ value?.id === binaryen.LocalGetId &&
1596
+ value.index === v.index)
1597
+ frame = { global: stack, size: frameOf(v.value), local: v.index, copy: true };
1598
+ }
1599
+ if (frame)
1600
+ break;
1601
+ }
1602
+ if (frame && (writes.get(frame.local) ?? 0) !== 1)
1603
+ frame = undefined;
1604
+ }
1605
+ // locals that hold or derive from a frame address
1606
+ const tainted = new Set(frame ? [frame.local] : []);
1607
+ const derives = (expression) => {
1608
+ const v = info(expression);
1609
+ if (v.id === binaryen.LocalGetId && tainted.has(v.index))
1610
+ return true;
1611
+ if (v.id === binaryen.GlobalGetId && v.name === stack)
1612
+ return true;
1613
+ return children(v).some(derives);
1614
+ };
1615
+ for (let changed = true; changed;) {
1616
+ changed = false;
1617
+ const grow = (expression) => {
1618
+ const v = info(expression);
1619
+ if (v.id === binaryen.LocalSetId && !tainted.has(v.index) && derives(v.value)) {
1620
+ tainted.add(v.index);
1621
+ changed = true;
1622
+ }
1623
+ for (const child of children(v))
1624
+ grow(child);
1625
+ };
1626
+ grow(f.body);
1627
+ }
1628
+ const callsMember = (expression) => {
1629
+ const v = info(expression);
1630
+ return (v.id === binaryen.CallId && members.has(v.target)) || children(v).some(callsMember);
1631
+ };
1632
+ if (spans.length && !spans.some((span) => callsMember(span.expression)))
1633
+ refuse.add('no call into the worker set in the loop body');
1634
+ for (const span of spans) {
1635
+ const check = (expression) => {
1636
+ const v = info(expression);
1637
+ if (v.id === binaryen.StoreId && derives(v.value))
1638
+ refuse.add('frame address stored to memory');
1639
+ if ((v.id === binaryen.CallIndirectId ||
1640
+ (v.id === binaryen.CallId && !members.has(v.target))) &&
1641
+ children(v).some(derives))
1642
+ refuse.add('frame address passed outside the worker set');
1643
+ if (v.id === binaryen.GlobalGetId && v.name === stack && !frame)
1644
+ refuse.add('stack global read in the body without a frame');
1645
+ for (const child of children(v))
1646
+ check(child);
1647
+ };
1648
+ check(span.expression);
1649
+ }
1650
+ // what runs after the loop must not read the frame; the epilogue restore is the one allowed use
1651
+ const afterReads = new Map();
1652
+ const inspect = (expression) => {
1653
+ const v = info(expression);
1654
+ if (frame && v.id === binaryen.GlobalSetId && v.name === stack) {
1655
+ const sum = info(v.value);
1656
+ const [a, b] = sum.id === binaryen.BinaryId ? [info(sum.left), info(sum.right)] : [];
1657
+ if (sum.op === binaryen.AddInt32 &&
1658
+ a?.id === binaryen.LocalGetId &&
1659
+ a.index === frame.local &&
1660
+ b?.id === binaryen.ConstId &&
1661
+ b.value === frame.size)
1662
+ return;
1663
+ }
1664
+ if (v.id === binaryen.LocalGetId) {
1665
+ afterReads.set(v.index, (afterReads.get(v.index) ?? 0) + 1);
1666
+ if (tainted.has(v.index))
1667
+ refuse.add('frame object read after the loop');
1668
+ }
1669
+ for (const child of children(v))
1670
+ inspect(child);
1671
+ };
1672
+ for (const statement of after)
1673
+ inspect(statement);
1674
+ const bodyWrites = new Set(spans.flatMap((span) => [...span.writes]));
1675
+ const carried = carriedLocals(spans, totalReads);
1676
+ for (const local of bodyWrites) {
1677
+ if (midUpdates.has(local))
1678
+ continue;
1679
+ if (afterReads.get(local))
1680
+ refuse.add('loop body writes a local the code after the loop reads');
1681
+ else if (carried.has(local)) {
1682
+ refuse.add('carried local is not a constant stride');
1683
+ const why = shaped.get(local);
1684
+ if (why)
1685
+ refuse.add(why);
1686
+ }
1687
+ }
1688
+ // the owner sets a constant-stride local to its loop-exit value, and has no way to do that for a
1689
+ // step that is held in a local
1690
+ for (const [local, update] of updates)
1691
+ if (update.strideLocal !== undefined && afterReads.get(local))
1692
+ refuse.add('local advanced by a run-time stride is read after the loop');
1693
+ // classify what the body reads
1694
+ const bodyReads = new Set(spans.flatMap((span) => [...span.reads.keys()]));
1695
+ const entry = (local) => {
1696
+ const outside = (writes.get(local) ?? 0) - (loopWrites.get(local) ?? 0);
1697
+ if (local < parameterCount && outside === 0)
1698
+ return { parameter: local };
1699
+ if (outside !== 1)
1700
+ return;
1701
+ for (const statement of [...before].reverse()) {
1702
+ const v = info(statement);
1703
+ if (v.id !== binaryen.LocalSetId || v.isTee || v.index !== local)
1704
+ continue;
1705
+ const value = info(v.value);
1706
+ if (value.id === binaryen.ConstId && typeof value.value === 'number')
1707
+ return { constant: value.value >>> 0 };
1708
+ if (value.id === binaryen.LocalGetId &&
1709
+ value.index < parameterCount &&
1710
+ !writes.get(value.index))
1711
+ return { parameter: value.index };
1712
+ return;
1713
+ }
1714
+ };
1715
+ const strided = [];
1716
+ const invariant = [];
1717
+ for (const [local, update] of [...updates].sort(([a], [b]) => a - b))
1718
+ strided.push({
1719
+ local,
1720
+ kind: local === counter ? 'induction' : 'stride',
1721
+ start: entry(local),
1722
+ stride: update.stride,
1723
+ ...(update.strideLocal === undefined ? {} : { strideLocal: update.strideLocal })
1724
+ });
1725
+ for (const local of [...bodyReads].sort((a, b) => a - b)) {
1726
+ if (bodyWrites.has(local) || updates.has(local) || local === frame?.local)
1727
+ continue;
1728
+ if ((loopWrites.get(local) ?? 0) > 0)
1729
+ refuse.add('carried local is not a constant stride');
1730
+ invariant.push({ local, kind: 'invariant', start: entry(local) });
1731
+ }
1732
+ // a step local the body does not read still needs its loop-entry value, so `iterate` takes it too
1733
+ const steps = new Set([...updates.values()].flatMap((update) => update.strideLocal === undefined ? [] : [update.strideLocal]));
1734
+ for (const local of [...steps].sort((a, b) => a - b))
1735
+ if (!invariant.some((item) => item.local === local))
1736
+ invariant.push({ local, kind: 'invariant', start: entry(local) });
1737
+ invariant.sort((a, b) => a.local - b.local);
1738
+ for (const item of [...strided, ...invariant]) {
1739
+ if (bodyReads.has(item.local) && tainted.has(item.local))
1740
+ refuse.add('frame address held in a local the body reads');
1741
+ if (steps.has(item.local) && tainted.has(item.local))
1742
+ refuse.add('frame address used as a run-time stride');
1743
+ }
1744
+ if (refuse.size)
1745
+ return { refusals: [...refuse] };
1746
+ // `iterate`: strided and invariant locals in order, then the frame base, then the body's temporaries
1747
+ const parameters = [...strided, ...invariant].filter((item) => bodyReads.has(item.local) || steps.has(item.local));
1748
+ const order = [...parameters.map((item) => item.local), ...(frame ? [frame.local] : [])];
1749
+ const temporaries = [...new Set(spans.flatMap((span) => [...span.locals]))]
1750
+ .filter((local) => !order.includes(local))
1751
+ .sort((a, b) => a - b);
1752
+ const positions = new Map([...order, ...temporaries].map((local, index) => [local, index]));
1753
+ parameters.forEach((item, index) => (item.argument = index));
1754
+ const memory = m.getMemoryInfo();
1755
+ const internalMemory = memoryName(m);
1756
+ const w = new binaryen.Module();
1757
+ try {
1758
+ w.setFeatures(m.getFeatures() | binaryen.Features.Atomics);
1759
+ w.setMemory(memory.initial, memory.max ?? 65536, null, [], true, false, internalMemory);
1760
+ w.addMemoryImport(internalMemory, 'env', 'memory', true);
1761
+ if (stack)
1762
+ w.addGlobal(stack, binaryen.i32, true, w.i32.const(context.route.stack.initial));
1763
+ for (const name of constants) {
1764
+ const g = binaryen.getGlobalInfo(m.getGlobal(name));
1765
+ w.addGlobal(name, g.type, false, w.copyExpression(g.init));
1766
+ }
1767
+ for (const name of context.route.functions) {
1768
+ const g = binaryen.getFunctionInfo(m.getFunction(name));
1769
+ w.addFunction(name, g.params, g.results, g.vars, w.copyExpression(g.body));
1770
+ }
1771
+ let iterate = '__folio_iterate';
1772
+ while (w.getFunction(iterate))
1773
+ iterate += '_';
1774
+ const block = w.block(null, spans.map((span) => w.copyExpression(span.expression)));
1775
+ remapLocals(block, positions);
1776
+ w.addFunction(iterate, binaryen.createType(order.map((local) => localTypes[local])), binaryen.none, temporaries.map((local) => localTypes[local]), block);
1777
+ w.addFunctionExport(iterate, iterate);
1778
+ const stackExport = '__folio_stack';
1779
+ if (stack)
1780
+ w.addGlobalExport(stack, stackExport);
1781
+ if (!w.validate())
1782
+ throw new Error('invalid iteration module');
1783
+ const bytes = w.emitBinary();
1784
+ new WebAssembly.Module(Uint8Array.from(bytes));
1785
+ const trip = entry(counter);
1786
+ const locals = [
1787
+ ...strided,
1788
+ ...invariant,
1789
+ ...(frame
1790
+ ? [{ local: frame.local, kind: 'frame', argument: order.length - 1 }]
1791
+ : [])
1792
+ ];
1793
+ const diagnostics = [
1794
+ `owner ${f.name}: countdown loop on local ${counter}, ${spans.length} body statements, ${order.length} arguments`
1795
+ ];
1796
+ if (frame)
1797
+ diagnostics.push(`frame ${frame.global} - ${frame.size} in local ${frame.local}`);
1798
+ return {
1799
+ refusals: [],
1800
+ route: {
1801
+ eligible: true,
1802
+ owner: f.name,
1803
+ loop: loop.name || undefined,
1804
+ trip: { local: counter, ...(trip ?? {}) },
1805
+ locals,
1806
+ frame,
1807
+ iterate,
1808
+ stackExport: stack ? stackExport : undefined,
1809
+ module: bytes,
1810
+ diagnostics
1811
+ }
1812
+ };
1813
+ }
1814
+ finally {
1815
+ w.dispose();
1816
+ }
1817
+ }