@onda-lang/wasm-compiler 0.9.2 → 0.9.3

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.
@@ -2,6 +2,10 @@ import { PayloadPlan } from "@onda-lang/processor-abi";
2
2
  import { prepareEventInput } from "./event-input.js";
3
3
  import { CollectionOrigins, selectedResourceRange } from "./resource-origins.js";
4
4
  import binaryen from "binaryen";
5
+ import { createModuleWithInlineHints, defineFunction } from "./inlining.js";
6
+ import { prepareFunctionBody, rewriteExpressionChildren } from "./expression-tree.js";
7
+ import { indexOrderedReductions } from "./simd-reductions.js";
8
+ import { optimizeGuardedAddresses } from "./guarded-addresses.js";
5
9
  import {
6
10
  SUPPORTED_MIR_SCHEMA_VERSION,
7
11
  OndaBinaryenError,
@@ -32,11 +36,14 @@ import {
32
36
  BUFFER_DESCRIPTOR_POINTER_GLOBALS,
33
37
  TRAPPING_DESCRIPTOR_UNARY_OPS,
34
38
  TRAPPING_DESCRIPTOR_BINARY_OPS,
35
- collectMathKernelHelpers,
39
+ collectMathHelpers,
40
+ roundHelperName,
36
41
  alignUp,
37
42
  encodeScalarValues,
38
43
  } from "./shared.js";
39
44
 
45
+ const MAX_WASM_FUNCTION_LOCALS = 50_000;
46
+
40
47
  export class MirCompilerCore {
41
48
  constructor(mir, options) {
42
49
  this.mir = mir;
@@ -50,8 +57,8 @@ export class MirCompilerCore {
50
57
  allowInliningFunctionsWithLoops:
51
58
  options.allowInliningFunctionsWithLoops === true,
52
59
  };
53
- this.module = new binaryen.Module();
54
- this.functionNames = [];
60
+ this.module = null;
61
+ this.signatureTypes = new Map();
55
62
  this.stateLayout = [];
56
63
  this.paramLayout = [];
57
64
  this.inputLayout = [];
@@ -64,11 +71,10 @@ export class MirCompilerCore {
64
71
  this.localScalarRefLayout = [];
65
72
  this.functionAbiLayout = [];
66
73
  this.memorySegments = [];
67
- this.requiredMathHelpers = collectMathKernelHelpers(mir);
68
- this.nextStaticAddress = this.requiredMathHelpers.size > 0
74
+ this.mathHelpers = collectMathHelpers(mir);
75
+ this.nextStaticAddress = this.mathHelpers.kernel.size > 0
69
76
  ? MATH_KERNEL_RESERVED_END
70
77
  : STATIC_BASE;
71
- this.internalHelpers = new Set();
72
78
  this.functionMayFail = [];
73
79
  this.bufferMayWrite = [];
74
80
  this.fallbackBufferReadAddress = 0;
@@ -78,10 +84,16 @@ export class MirCompilerCore {
78
84
  }
79
85
 
80
86
  compile() {
87
+ this.validateEnvelope();
88
+ this.orderedReductions = indexOrderedReductions(this.mir);
89
+ this.functionNames = this.mir.functions.map((_, id) => `$onda.fn.${id}`);
90
+ const hasAlways = this.options.optimize
91
+ && this.mir.functions.some((func) => func.attributes.inline === "always");
92
+ // Binaryen 132's default pipeline includes inlining at O2+ or shrink level 2.
93
+ const hintOnlyPass = hasAlways && this.options.optimizeLevel < 2 && this.options.shrinkLevel < 2;
81
94
  try {
82
- this.validateEnvelope();
83
- this.buildLayouts();
84
- this.addMathKernel();
95
+ this.initializeModule(hintOnlyPass);
96
+ for (const scalar of this.mathHelpers.round) this.addRoundHelper(scalar);
85
97
  this.addMemoryAndContextGlobals();
86
98
  this.addMirFunctions();
87
99
  this.addAbiWrappers();
@@ -102,6 +114,14 @@ export class MirCompilerCore {
102
114
  binaryen.setAllowInliningFunctionsWithLoops(
103
115
  this.options.allowInliningFunctionsWithLoops,
104
116
  );
117
+ if (hintOnlyPass) {
118
+ this.module.runPasses(["inlining-optimizing"]);
119
+ } else if (hasAlways) {
120
+ // The default pipeline merges identical functions before inlining.
121
+ // Inline explicit requests while calls still identify their original callees.
122
+ // Drop unused locals first so inlining does not copy them into callers.
123
+ this.module.runPasses(["remove-unused-module-elements", "reorder-locals", "inlining"]);
124
+ }
105
125
  this.module.optimize();
106
126
  if (this.hoistInvariantBufferDescriptorLoads()) {
107
127
  // The first rewrite makes descriptor provenance explicit in
@@ -118,6 +138,10 @@ export class MirCompilerCore {
118
138
  this.module.runPasses(["vacuum"]);
119
139
  }
120
140
  }
141
+ for (let i = 0; i < this.module.getNumFunctions(); i++) {
142
+ optimizeGuardedAddresses(this.module, this.module.getFunctionByIndex(i));
143
+ }
144
+ this.module.runPasses(["strip-toolchain-annotations"]);
121
145
  } finally {
122
146
  binaryen.setOptimizeLevel(previousOptimizeLevel);
123
147
  binaryen.setShrinkLevel(previousShrinkLevel);
@@ -144,7 +168,7 @@ export class MirCompilerCore {
144
168
  validateProcessorMetadata(result.metadata, "webassembly_module");
145
169
  return result;
146
170
  } finally {
147
- this.module.dispose();
171
+ this.module?.dispose();
148
172
  }
149
173
  }
150
174
 
@@ -157,13 +181,12 @@ export class MirCompilerCore {
157
181
  this.descriptorLoadsHoisted = 0;
158
182
  for (let index = 0; index < this.module.getNumFunctions(); index += 1) {
159
183
  const func = this.module.getFunctionByIndex(index);
160
- const body = binaryen.Function.getBody(func);
161
- if (!body) continue;
162
184
  // The local-write scan below is part of the safety proof. If Binaryen
163
185
  // adds an expression kind that this backend does not know how to walk,
164
186
  // leave the whole function untouched rather than silently overlooking
165
187
  // a nested local.tee.
166
- if (!this.visitExpression(body, () => {})) continue;
188
+ const body = prepareFunctionBody(this.module, func);
189
+ if (!body) continue;
167
190
  const rewritten = this.rewriteDescriptorLoops(body, func);
168
191
  if (rewritten !== body) binaryen.Function.setBody(func, rewritten);
169
192
  }
@@ -171,7 +194,7 @@ export class MirCompilerCore {
171
194
  }
172
195
 
173
196
  rewriteDescriptorLoops(expression, func) {
174
- this.rewriteExpressionChildren(expression, (child) =>
197
+ rewriteExpressionChildren(expression, (child) =>
175
198
  this.rewriteDescriptorLoops(child, func)
176
199
  );
177
200
  if (expressionInfo(expression).id !== binaryen.LoopId) {
@@ -197,7 +220,7 @@ export class MirCompilerCore {
197
220
  const loopLocalCaches = new Map();
198
221
 
199
222
  const rewriteLoad = (candidate) => {
200
- this.rewriteExpressionChildren(candidate, rewriteLoad);
223
+ rewriteExpressionChildren(candidate, rewriteLoad);
201
224
  const info = expressionInfo(candidate);
202
225
  if (info.id !== binaryen.LoadId || info.isAtomic) return candidate;
203
226
  const candidatePath = controlPaths.get(candidate) ?? [];
@@ -267,7 +290,13 @@ export class MirCompilerCore {
267
290
  visit(info.body, [...path, `loop:${candidate}`]);
268
291
  return;
269
292
  }
270
- this.rewriteExpressionChildren(candidate, (child) => {
293
+ // A branch to a named block can skip a tee and resume after the block.
294
+ if (info.id === binaryen.BlockId && info.name) {
295
+ const nested = [...path, `block:${candidate}`];
296
+ for (const child of info.children) visit(child, nested);
297
+ return;
298
+ }
299
+ rewriteExpressionChildren(candidate, (child) => {
271
300
  visit(child, path);
272
301
  return child;
273
302
  });
@@ -342,7 +371,7 @@ export class MirCompilerCore {
342
371
  }
343
372
 
344
373
  descriptorPointerForPreheader(expression, loopLocalCaches, candidatePath) {
345
- this.rewriteExpressionChildren(expression, (child) =>
374
+ rewriteExpressionChildren(expression, (child) =>
346
375
  this.descriptorPointerForPreheader(
347
376
  child,
348
377
  loopLocalCaches,
@@ -367,7 +396,7 @@ export class MirCompilerCore {
367
396
  }
368
397
 
369
398
  descriptorPointerExpression(expression, definitions, localIsInvariant) {
370
- if (!this.expressionUsesDescriptorTable(expression, definitions, new Set())) {
399
+ if (!this.expressionUsesDescriptorTable(expression, definitions)) {
371
400
  return false;
372
401
  }
373
402
  const visit = (candidate) => {
@@ -381,7 +410,9 @@ export class MirCompilerCore {
381
410
  return false;
382
411
  }
383
412
  if (info.id === binaryen.LocalSetId && info.isTee) {
384
- return visit(info.value);
413
+ // Coalescing can reuse this local for a different buffer or index.
414
+ // Only a single definition can supply a cache for later local.gets.
415
+ return definitions.get(info.index)?.length === 1 && visit(info.value);
385
416
  }
386
417
  if (info.id === binaryen.UnaryId) {
387
418
  return !TRAPPING_DESCRIPTOR_UNARY_OPS.has(info.op)
@@ -407,68 +438,39 @@ export class MirCompilerCore {
407
438
  return visit(expression);
408
439
  }
409
440
 
410
- expressionUsesDescriptorTable(expression, definitions, visitingLocals) {
411
- const info = expressionInfo(expression);
412
- if (info.id === binaryen.GlobalGetId) {
413
- return BUFFER_DESCRIPTOR_POINTER_GLOBALS.has(info.name);
414
- }
415
- if (info.id === binaryen.LocalGetId) {
416
- const values = definitions.get(info.index);
417
- if (
418
- !values
419
- || values.length !== 1
420
- || visitingLocals.has(info.index)
421
- ) {
422
- return false;
441
+ // Local definitions form a graph and can span many shallow statements.
442
+ expressionUsesDescriptorTable(expression, definitions) {
443
+ const pending = [expression];
444
+ const visited = new Set();
445
+ while (pending.length) {
446
+ const expr = pending.pop();
447
+ switch (binaryen.getExpressionId(expr)) {
448
+ case binaryen.GlobalGetId:
449
+ if (BUFFER_DESCRIPTOR_POINTER_GLOBALS.has(binaryen.GlobalGet.getName(expr))) return true;
450
+ break;
451
+ case binaryen.LocalGetId: {
452
+ const local = binaryen.LocalGet.getIndex(expr);
453
+ const values = definitions.get(local);
454
+ if (values?.length === 1 && !visited.has(local)) {
455
+ visited.add(local);
456
+ pending.push(values[0]);
457
+ }
458
+ break;
459
+ }
460
+ case binaryen.LocalSetId:
461
+ if (binaryen.LocalSet.isTee(expr)) pending.push(binaryen.LocalSet.getValue(expr));
462
+ break;
463
+ case binaryen.UnaryId:
464
+ pending.push(binaryen.Unary.getValue(expr));
465
+ break;
466
+ case binaryen.BinaryId:
467
+ pending.push(binaryen.Binary.getRight(expr), binaryen.Binary.getLeft(expr));
468
+ break;
469
+ case binaryen.SelectId:
470
+ pending.push(binaryen.Select.getIfFalse(expr), binaryen.Select.getIfTrue(expr),
471
+ binaryen.Select.getCondition(expr));
472
+ break;
423
473
  }
424
- visitingLocals.add(info.index);
425
- const result = this.expressionUsesDescriptorTable(
426
- values[0],
427
- definitions,
428
- visitingLocals,
429
- );
430
- visitingLocals.delete(info.index);
431
- return result;
432
- }
433
- if (info.id === binaryen.LocalSetId && info.isTee) {
434
- return this.expressionUsesDescriptorTable(
435
- info.value,
436
- definitions,
437
- visitingLocals,
438
- );
439
- }
440
- if (info.id === binaryen.UnaryId) {
441
- return this.expressionUsesDescriptorTable(
442
- info.value,
443
- definitions,
444
- visitingLocals,
445
- );
446
- }
447
- if (info.id === binaryen.BinaryId) {
448
- return this.expressionUsesDescriptorTable(
449
- info.left,
450
- definitions,
451
- visitingLocals,
452
- ) || this.expressionUsesDescriptorTable(
453
- info.right,
454
- definitions,
455
- visitingLocals,
456
- );
457
- }
458
- if (info.id === binaryen.SelectId) {
459
- return this.expressionUsesDescriptorTable(
460
- info.condition,
461
- definitions,
462
- visitingLocals,
463
- ) || this.expressionUsesDescriptorTable(
464
- info.ifTrue,
465
- definitions,
466
- visitingLocals,
467
- ) || this.expressionUsesDescriptorTable(
468
- info.ifFalse,
469
- definitions,
470
- visitingLocals,
471
- );
472
474
  }
473
475
  return false;
474
476
  }
@@ -516,140 +518,7 @@ export class MirCompilerCore {
516
518
 
517
519
  visitExpression(expression, visitor) {
518
520
  visitor(expression);
519
- let complete = true;
520
- const supported = this.rewriteExpressionChildren(expression, (child) => {
521
- if (!this.visitExpression(child, visitor)) complete = false;
522
- return child;
523
- });
524
- return complete && supported;
525
- }
526
-
527
- rewriteExpressionChildren(expression, rewrite) {
528
- const info = expressionInfo(expression);
529
- const replace = (child, setter) => {
530
- if (child) setter(rewrite(child));
531
- };
532
- switch (info.id) {
533
- case binaryen.BlockId:
534
- info.children.forEach((child, index) =>
535
- replace(child, (value) => binaryen.Block.setChildAt(expression, index, value))
536
- );
537
- break;
538
- case binaryen.IfId:
539
- replace(info.condition, (value) => binaryen.If.setCondition(expression, value));
540
- replace(info.ifTrue, (value) => binaryen.If.setIfTrue(expression, value));
541
- replace(info.ifFalse, (value) => binaryen.If.setIfFalse(expression, value));
542
- break;
543
- case binaryen.LoopId:
544
- replace(info.body, (value) => binaryen.Loop.setBody(expression, value));
545
- break;
546
- case binaryen.BreakId:
547
- replace(info.condition, (value) => binaryen.Break.setCondition(expression, value));
548
- replace(info.value, (value) => binaryen.Break.setValue(expression, value));
549
- break;
550
- case binaryen.SwitchId:
551
- replace(info.condition, (value) => binaryen.Switch.setCondition(expression, value));
552
- replace(info.value, (value) => binaryen.Switch.setValue(expression, value));
553
- break;
554
- case binaryen.CallId:
555
- info.operands.forEach((child, index) =>
556
- replace(child, (value) => binaryen.Call.setOperandAt(expression, index, value))
557
- );
558
- break;
559
- case binaryen.CallIndirectId:
560
- replace(info.target, (value) => binaryen.CallIndirect.setTarget(expression, value));
561
- info.operands.forEach((child, index) =>
562
- replace(child, (value) => binaryen.CallIndirect.setOperandAt(expression, index, value))
563
- );
564
- break;
565
- case binaryen.LocalSetId:
566
- replace(info.value, (value) => binaryen.LocalSet.setValue(expression, value));
567
- break;
568
- case binaryen.GlobalSetId:
569
- replace(info.value, (value) => binaryen.GlobalSet.setValue(expression, value));
570
- break;
571
- case binaryen.LoadId:
572
- replace(info.ptr, (value) => binaryen.Load.setPtr(expression, value));
573
- break;
574
- case binaryen.StoreId:
575
- replace(info.ptr, (value) => binaryen.Store.setPtr(expression, value));
576
- replace(info.value, (value) => binaryen.Store.setValue(expression, value));
577
- break;
578
- case binaryen.UnaryId:
579
- replace(info.value, (value) => binaryen.Unary.setValue(expression, value));
580
- break;
581
- case binaryen.BinaryId:
582
- replace(info.left, (value) => binaryen.Binary.setLeft(expression, value));
583
- replace(info.right, (value) => binaryen.Binary.setRight(expression, value));
584
- break;
585
- case binaryen.SelectId:
586
- replace(info.ifTrue, (value) => binaryen.Select.setIfTrue(expression, value));
587
- replace(info.ifFalse, (value) => binaryen.Select.setIfFalse(expression, value));
588
- replace(info.condition, (value) => binaryen.Select.setCondition(expression, value));
589
- break;
590
- case binaryen.DropId:
591
- replace(info.value, (value) => binaryen.Drop.setValue(expression, value));
592
- break;
593
- case binaryen.ReturnId:
594
- replace(info.value, (value) => binaryen.Return.setValue(expression, value));
595
- break;
596
- case binaryen.MemoryCopyId:
597
- replace(info.dest, (value) => binaryen.MemoryCopy.setDest(expression, value));
598
- replace(info.source, (value) => binaryen.MemoryCopy.setSource(expression, value));
599
- replace(info.size, (value) => binaryen.MemoryCopy.setSize(expression, value));
600
- break;
601
- case binaryen.MemoryFillId:
602
- replace(info.dest, (value) => binaryen.MemoryFill.setDest(expression, value));
603
- replace(info.value, (value) => binaryen.MemoryFill.setValue(expression, value));
604
- replace(info.size, (value) => binaryen.MemoryFill.setSize(expression, value));
605
- break;
606
- case binaryen.SIMDExtractId:
607
- replace(info.vec, (value) => binaryen.SIMDExtract.setVec(expression, value));
608
- break;
609
- case binaryen.SIMDReplaceId:
610
- replace(info.vec, (value) => binaryen.SIMDReplace.setVec(expression, value));
611
- replace(info.value, (value) => binaryen.SIMDReplace.setValue(expression, value));
612
- break;
613
- case binaryen.SIMDShuffleId:
614
- replace(info.left, (value) => binaryen.SIMDShuffle.setLeft(expression, value));
615
- replace(info.right, (value) => binaryen.SIMDShuffle.setRight(expression, value));
616
- break;
617
- case binaryen.SIMDTernaryId:
618
- replace(info.a, (value) => binaryen.SIMDTernary.setA(expression, value));
619
- replace(info.b, (value) => binaryen.SIMDTernary.setB(expression, value));
620
- replace(info.c, (value) => binaryen.SIMDTernary.setC(expression, value));
621
- break;
622
- case binaryen.SIMDShiftId:
623
- replace(info.vec, (value) => binaryen.SIMDShift.setVec(expression, value));
624
- replace(info.shift, (value) => binaryen.SIMDShift.setShift(expression, value));
625
- break;
626
- case binaryen.SIMDLoadId:
627
- replace(info.ptr, (value) => binaryen.SIMDLoad.setPtr(expression, value));
628
- break;
629
- case binaryen.SIMDLoadStoreLaneId:
630
- replace(info.ptr, (value) => binaryen.SIMDLoadStoreLane.setPtr(expression, value));
631
- replace(info.vec, (value) => binaryen.SIMDLoadStoreLane.setVec(expression, value));
632
- break;
633
- case binaryen.TupleMakeId:
634
- info.operands.forEach((child, index) =>
635
- replace(child, (value) => binaryen.TupleMake.setOperandAt(expression, index, value))
636
- );
637
- break;
638
- case binaryen.TupleExtractId:
639
- replace(info.tuple, (value) => binaryen.TupleExtract.setTuple(expression, value));
640
- break;
641
- case binaryen.ConstId:
642
- case binaryen.LocalGetId:
643
- case binaryen.GlobalGetId:
644
- case binaryen.NopId:
645
- case binaryen.UnreachableId:
646
- case binaryen.MemorySizeId:
647
- case binaryen.DataDropId:
648
- break;
649
- default:
650
- return false;
651
- }
652
- return true;
521
+ rewriteExpressionChildren(expression, child => { this.visitExpression(child, visitor); });
653
522
  }
654
523
 
655
524
  validateEnvelope() {
@@ -899,7 +768,7 @@ export class MirCompilerCore {
899
768
  }
900
769
 
901
770
  const origins = new Set(["source", "compiler_generated"]);
902
- const inlineHints = new Set(["auto", "always", "never"]);
771
+ const inlineHints = new Set(["auto", "always", "prefer", "never"]);
903
772
  for (const [functionId, func] of this.mir.functions.entries()) {
904
773
  if (
905
774
  !func?.attributes ||
@@ -1826,92 +1695,95 @@ export class MirCompilerCore {
1826
1695
  );
1827
1696
  }
1828
1697
 
1829
- addMathKernel() {
1830
- if (this.requiredMathHelpers.size === 0) return;
1831
-
1832
- const source = binaryen.readBinary(ONDA_MATH_KERNEL_WASM);
1698
+ initializeModule(hintOnlyPass) {
1699
+ const kernel = this.mathHelpers.kernel.size ? binaryen.readBinary(ONDA_MATH_KERNEL_WASM) : null;
1833
1700
  try {
1834
- if (
1835
- source.getNumGlobals() !== 1
1836
- || source.getNumTables() !== 0
1837
- || source.getNumDataSegments() !== 1
1838
- ) {
1839
- this.fail("embedded Wasm math kernel has an unsupported module shape");
1840
- }
1841
-
1842
- for (let index = source.getNumExports() - 1; index >= 0; index -= 1) {
1843
- const exported = binaryen.getExportInfo(source.getExportByIndex(index));
1844
- if (!this.requiredMathHelpers.has(exported.name)) {
1845
- source.removeExport(exported.name);
1701
+ if (kernel) {
1702
+ if (kernel.getNumGlobals() !== 1 || kernel.getNumTables() !== 0 || kernel.getNumDataSegments() !== 1) {
1703
+ this.fail("embedded Wasm math kernel has an unsupported module shape");
1846
1704
  }
1847
- }
1848
- source.runPasses(["remove-unused-module-elements"]);
1849
-
1850
- if (source.getNumGlobals() > 1 || source.getNumDataSegments() > 1) {
1851
- this.fail("optimized Wasm math kernel has an unsupported module shape");
1852
- }
1853
- if (source.getNumGlobals() === 1) {
1854
- const global = binaryen.getGlobalInfo(source.getGlobalByIndex(0));
1855
- if (
1856
- global.module
1857
- || global.name !== MATH_KERNEL_STACK_GLOBAL
1858
- || global.type !== binaryen.i32
1859
- || !global.mutable
1860
- ) {
1861
- this.fail("embedded Wasm math kernel has an invalid stack global");
1705
+ for (let i = kernel.getNumExports() - 1; i >= 0; i--) {
1706
+ const exported = binaryen.getExportInfo(kernel.getExportByIndex(i));
1707
+ if (!this.mathHelpers.kernel.has(exported.name)) kernel.removeExport(exported.name);
1862
1708
  }
1863
- this.module.addGlobal(
1864
- global.name,
1865
- global.type,
1866
- global.mutable,
1867
- this.module.copyExpression(global.init),
1868
- );
1709
+ kernel.runPasses(["remove-unused-module-elements"]);
1710
+ }
1711
+ this.module = this.options.optimize
1712
+ ? createModuleWithInlineHints(
1713
+ this.mir.functions, this.functionNames, hintOnlyPass,
1714
+ kernel, Array.from(this.mathHelpers.round, roundHelperName),
1715
+ )
1716
+ : new binaryen.Module();
1717
+ this.buildLayouts();
1718
+ if (kernel) this.linkMathKernel(kernel);
1719
+ } finally {
1720
+ kernel?.dispose();
1721
+ }
1722
+ }
1723
+
1724
+ linkMathKernel(source) {
1725
+ if (source.getNumGlobals() > 1 || source.getNumDataSegments() > 1) {
1726
+ this.fail("optimized Wasm math kernel has an unsupported module shape");
1727
+ }
1728
+ if (source.getNumGlobals() === 1) {
1729
+ const global = binaryen.getGlobalInfo(source.getGlobalByIndex(0));
1730
+ if (
1731
+ global.module
1732
+ || global.name !== MATH_KERNEL_STACK_GLOBAL
1733
+ || global.type !== binaryen.i32
1734
+ || !global.mutable
1735
+ ) {
1736
+ this.fail("embedded Wasm math kernel has an invalid stack global");
1869
1737
  }
1738
+ this.module.addGlobal(
1739
+ global.name,
1740
+ global.type,
1741
+ global.mutable,
1742
+ this.module.copyExpression(global.init),
1743
+ );
1744
+ }
1870
1745
 
1871
- if (source.getNumDataSegments() === 1) {
1872
- const segment = source.getDataSegmentInfo(source.getDataSegmentByIndex(0));
1873
- if (
1874
- segment.name !== MATH_KERNEL_DATA_SEGMENT
1875
- || segment.passive
1876
- || !Number.isInteger(segment.offset)
1877
- || segment.offset < STATIC_BASE
1878
- || segment.offset + segment.data.byteLength > MATH_KERNEL_RESERVED_END
1879
- ) {
1880
- this.fail("embedded Wasm math kernel exceeds its reserved memory region");
1881
- }
1882
- this.memorySegments.push({
1883
- offset: this.module.i32.const(segment.offset),
1884
- data: new Uint8Array(segment.data),
1885
- });
1746
+ if (source.getNumDataSegments() === 1) {
1747
+ const segment = source.getDataSegmentInfo(source.getDataSegmentByIndex(0));
1748
+ if (
1749
+ segment.name !== MATH_KERNEL_DATA_SEGMENT
1750
+ || segment.passive
1751
+ || !Number.isInteger(segment.offset)
1752
+ || segment.offset < STATIC_BASE
1753
+ || segment.offset + segment.data.byteLength > MATH_KERNEL_RESERVED_END
1754
+ ) {
1755
+ this.fail("embedded Wasm math kernel exceeds its reserved memory region");
1886
1756
  }
1757
+ this.memorySegments.push({
1758
+ offset: this.module.i32.const(segment.offset),
1759
+ data: new Uint8Array(segment.data),
1760
+ });
1761
+ }
1887
1762
 
1888
- this.module.setFeatures(this.module.getFeatures() | source.getFeatures());
1889
- for (let index = 0; index < source.getNumFunctions(); index += 1) {
1890
- const func = binaryen.getFunctionInfo(source.getFunctionByIndex(index));
1891
- if (func.module || !func.body) {
1892
- this.fail("embedded Wasm math kernel must not import functions");
1893
- }
1894
- this.module.addFunction(
1895
- func.name,
1896
- func.params,
1897
- func.results,
1898
- func.vars,
1899
- this.module.copyExpression(func.body),
1900
- );
1763
+ this.module.setFeatures(this.module.getFeatures() | source.getFeatures());
1764
+ for (let index = 0; index < source.getNumFunctions(); index += 1) {
1765
+ const func = binaryen.getFunctionInfo(source.getFunctionByIndex(index));
1766
+ if (func.module || !func.body) {
1767
+ this.fail("embedded Wasm math kernel must not import functions");
1901
1768
  }
1902
- } finally {
1903
- source.dispose();
1769
+ defineFunction(
1770
+ this.module, this.signatureTypes,
1771
+ func.name,
1772
+ func.params,
1773
+ func.results,
1774
+ func.vars,
1775
+ this.module.copyExpression(func.body),
1776
+ );
1904
1777
  }
1905
1778
  }
1906
1779
 
1907
1780
  addMirFunctions() {
1908
- this.functionNames = this.mir.functions.map((_, id) => `$onda.fn.${id}`);
1909
1781
  for (let id = 0; id < this.mir.functions.length; id += 1) {
1910
1782
  this.addMirFunction(id, this.mir.functions[id]);
1911
1783
  }
1912
1784
  }
1913
1785
 
1914
- addMirFunction(id, func) {
1786
+ addMirFunction(id, func, allowLocalOptimizations = true) {
1915
1787
  const packed = this.functionAbiLayout[id];
1916
1788
  const paramValueBase = packed ? 1 : 0;
1917
1789
  let nextIndex = paramValueBase;
@@ -1954,10 +1826,7 @@ export class MirCompilerCore {
1954
1826
  flatLocalScalars.length +
1955
1827
  callResultLocals.length +
1956
1828
  sliceScratch.count;
1957
- if (
1958
- resultScalars.length > 1
1959
- || callResultLocals.some((entry) => entry.resultCount > 1)
1960
- ) {
1829
+ if (resultScalars.length > 1 || callResultLocals.length > 0) {
1961
1830
  this.module.setFeatures(
1962
1831
  this.module.getFeatures() | binaryen.Features.Multivalue,
1963
1832
  );
@@ -1994,9 +1863,12 @@ export class MirCompilerCore {
1994
1863
  ),
1995
1864
  eventId: func.kind?.kind === "event" ? func.kind.data : null,
1996
1865
  processFrameLocals,
1866
+ allowLocalOptimizations,
1867
+ vectorizedLoop: false,
1997
1868
  generatedLocalBase,
1998
1869
  generatedLocals: [],
1999
1870
  entryInitializers: [],
1871
+ stateAddressCache: allowLocalOptimizations && func.kind.kind !== "init" ? new Map() : null,
2000
1872
  bufferDescriptorCache: new Map(),
2001
1873
  audioChannelPointerCache: new Map(),
2002
1874
  breakLabels: [],
@@ -2010,13 +1882,27 @@ export class MirCompilerCore {
2010
1882
  });
2011
1883
  }
2012
1884
  const compiledBody = this.compileBlock(func.body, context);
1885
+ // A tuple occupies one Binaryen local index but one Wasm local per component.
1886
+ const wasmLocalCount = callResultLocals.reduce(
1887
+ (count, spill) => count + spill.resultCount - 1,
1888
+ generatedLocalBase + context.generatedLocals.length,
1889
+ );
1890
+ if (wasmLocalCount > MAX_WASM_FUNCTION_LOCALS) {
1891
+ if (context.stateAddressCache?.size || context.vectorizedLoop) {
1892
+ return this.addMirFunction(id, func, false);
1893
+ }
1894
+ if (!this.options.optimize) {
1895
+ this.fail(`function '${func.name}' needs ${wasmLocalCount} parameters and locals, exceeding the Wasm limit of ${MAX_WASM_FUNCTION_LOCALS}`);
1896
+ }
1897
+ }
2013
1898
  const body = context.entryInitializers.length === 0
2014
1899
  ? compiledBody
2015
1900
  : this.module.block(null, [
2016
1901
  ...context.entryInitializers,
2017
1902
  compiledBody,
2018
1903
  ]);
2019
- const functionRef = this.module.addFunction(
1904
+ const functionRef = defineFunction(
1905
+ this.module, this.signatureTypes,
2020
1906
  this.functionNames[id],
2021
1907
  packed ? binaryen.i32 : binaryen.createType(paramScalars.map((type) => this.wasmType(type))),
2022
1908
  this.wasmResultType(resultScalars),