@gmitch215/folio 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1176 @@
1
+ import binaryen from 'binaryen';
2
+ import { restoreImportOrder } from "./import-order.js";
3
+ /** Calibrated on Apple M2 Pro; see `results/20261020-regress/admission-calibration.summary.json`. */
4
+ export const DEFAULT_MINIMUM_REGION_WORK = 200_000;
5
+ export const DEFAULT_ASSUMED_TRIP_COUNT = 1000;
6
+ // a tracked load or store costs about this many plain instructions in a speculative lane
7
+ const ACCESS_COST = 3600;
8
+ const CALL_COST = 2;
9
+ const SCALE_LIMIT = 2 ** 50;
10
+ const raw = binaryen;
11
+ const numeric = new Set([binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64]);
12
+ function info(expression) {
13
+ const id = binaryen.getExpressionId(expression);
14
+ if (id === binaryen.NopId || id === binaryen.UnreachableId)
15
+ return { id, type: binaryen.getExpressionType(expression) };
16
+ return binaryen.getExpressionInfo(expression);
17
+ }
18
+ function children(v) {
19
+ switch (v.id) {
20
+ case binaryen.BlockId:
21
+ return v.children;
22
+ case binaryen.IfId:
23
+ return [v.condition, v.ifTrue, v.ifFalse].filter(Boolean);
24
+ case binaryen.LoopId:
25
+ return [v.body];
26
+ case binaryen.BreakId:
27
+ case binaryen.SwitchId:
28
+ return [v.value, v.condition].filter(Boolean);
29
+ case binaryen.CallId:
30
+ return v.operands;
31
+ case binaryen.CallIndirectId:
32
+ return [...v.operands, v.target];
33
+ case binaryen.LocalSetId:
34
+ case binaryen.GlobalSetId:
35
+ case binaryen.UnaryId:
36
+ case binaryen.DropId:
37
+ return [v.value];
38
+ case binaryen.LoadId:
39
+ return [v.ptr];
40
+ case binaryen.StoreId:
41
+ return [v.ptr, v.value];
42
+ case binaryen.BinaryId:
43
+ return [v.left, v.right];
44
+ case binaryen.SelectId:
45
+ return [v.ifTrue, v.ifFalse, v.condition];
46
+ case binaryen.ReturnId:
47
+ return v.value ? [v.value] : [];
48
+ case binaryen.MemoryGrowId:
49
+ return [v.delta];
50
+ case binaryen.MemoryCopyId:
51
+ return [v.dest, v.source, v.size];
52
+ case binaryen.MemoryFillId:
53
+ return [v.dest, v.value, v.size];
54
+ case binaryen.MemoryInitId:
55
+ return [v.dest, v.offset, v.size];
56
+ default:
57
+ return [];
58
+ }
59
+ }
60
+ function memoryCount(bytes) {
61
+ let cursor = 8;
62
+ const uint = () => {
63
+ let result = 0, shift = 0, byte;
64
+ do {
65
+ byte = bytes[cursor++];
66
+ result += (byte & 127) * 2 ** shift;
67
+ shift += 7;
68
+ } while (byte & 128);
69
+ return result;
70
+ };
71
+ let defined = 0;
72
+ while (cursor < bytes.length) {
73
+ const section = bytes[cursor++];
74
+ const length = uint();
75
+ const end = cursor + length;
76
+ if (section === 5)
77
+ defined = uint();
78
+ cursor = end;
79
+ }
80
+ return (defined +
81
+ WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(bytes))).filter((value) => value.kind === 'memory').length);
82
+ }
83
+ function memoryName(module) {
84
+ for (let i = 0; i < module.getNumExports(); i++) {
85
+ const exported = binaryen.getExportInfo(module.getExportByIndex(i));
86
+ if (exported.kind === binaryen.ExternalMemory)
87
+ return exported.value;
88
+ }
89
+ const token = /\(memory\s+(\$(?:"(?:\\.|[^"\\])*"|[^\s()]+))/.exec(module.emitText())?.[1];
90
+ if (!token)
91
+ throw new Error('missing memory name');
92
+ if (token[1] !== '"')
93
+ return token.slice(1);
94
+ const bytes = [];
95
+ const content = token.slice(2, -1);
96
+ for (let i = 0; i < content.length;) {
97
+ if (content[i] === '\\') {
98
+ bytes.push(Number.parseInt(content.slice(i + 1, i + 3), 16));
99
+ i += 3;
100
+ }
101
+ else {
102
+ const point = content.codePointAt(i);
103
+ bytes.push(...new TextEncoder().encode(String.fromCodePoint(point)));
104
+ i += point > 65535 ? 2 : 1;
105
+ }
106
+ }
107
+ return new TextDecoder().decode(new Uint8Array(bytes));
108
+ }
109
+ const comparisons = new Set([
110
+ binaryen.LtUInt32,
111
+ binaryen.LtSInt32,
112
+ binaryen.LeUInt32,
113
+ binaryen.LeSInt32,
114
+ binaryen.GtUInt32,
115
+ binaryen.GtSInt32,
116
+ binaryen.GeUInt32,
117
+ binaryen.GeSInt32,
118
+ binaryen.NeInt32
119
+ ]);
120
+ // a counted loop ends on a comparison of a counter local against a constant or an untouched input
121
+ function loopBound(loop, inputs) {
122
+ const body = info(loop.body);
123
+ const tail = body.id === binaryen.BlockId ? body.children.at(-1) : loop.body;
124
+ if (tail === undefined)
125
+ return;
126
+ const branch = info(tail);
127
+ if (branch.id !== binaryen.BreakId || branch.name !== loop.name || !branch.condition)
128
+ return;
129
+ const test = info(branch.condition);
130
+ if (test.id !== binaryen.BinaryId || !comparisons.has(test.op))
131
+ return;
132
+ const sides = [info(test.left), info(test.right)];
133
+ for (const [index, bound] of sides.entries()) {
134
+ if (bound.id === binaryen.ConstId && typeof bound.value === 'number' && bound.value >= 1)
135
+ return { constant: bound.value };
136
+ const counter = sides[1 - index];
137
+ if (inputs &&
138
+ bound.id === binaryen.LocalGetId &&
139
+ inputs.input(bound.index) &&
140
+ counter.id === binaryen.LocalGetId &&
141
+ inputs.counter(counter.index))
142
+ return { parameter: bound.index };
143
+ }
144
+ }
145
+ // a countdown loop ends on `local.tee $c (c - 1)`, so it runs for the value $c held on entry
146
+ function countdownLocal(loop) {
147
+ const body = info(loop.body);
148
+ const tail = body.id === binaryen.BlockId ? body.children.at(-1) : loop.body;
149
+ if (tail === undefined)
150
+ return;
151
+ const branch = info(tail);
152
+ if (branch.id !== binaryen.BreakId || branch.name !== loop.name || !branch.condition)
153
+ return;
154
+ const step = info(branch.condition);
155
+ if (step.id !== binaryen.LocalSetId || !step.isTee)
156
+ return;
157
+ const next = info(step.value);
158
+ if (next.id !== binaryen.BinaryId)
159
+ return;
160
+ const [from, by] = [info(next.left), info(next.right)];
161
+ if (from.id !== binaryen.LocalGetId || from.index !== step.index || by.id !== binaryen.ConstId)
162
+ return;
163
+ const down = (next.op === binaryen.AddInt32 && by.value === -1) ||
164
+ (next.op === binaryen.SubInt32 && by.value === 1);
165
+ return down ? step.index : undefined;
166
+ }
167
+ /**
168
+ * Trip-weighted instruction and tracked-access counts of one body, calls included. A loop bounded
169
+ * by an untouched input makes a term in that local; other unknown bounds use `assumedTrips`.
170
+ */
171
+ export function estimateTerms(body, callee, assumedTrips, inputs) {
172
+ const terms = new Map();
173
+ const add = (factor, params, compute, accesses) => {
174
+ const key = params.join(',');
175
+ const term = terms.get(key) ?? { params, compute: 0, accesses: 0 };
176
+ term.compute = Math.min(term.compute + factor * compute, SCALE_LIMIT);
177
+ term.accesses = Math.min(term.accesses + factor * accesses, SCALE_LIMIT);
178
+ terms.set(key, term);
179
+ };
180
+ // what a local was last set to in program order: an untouched input or a constant
181
+ const initial = new Map();
182
+ const visit = (expression, factor, params) => {
183
+ const v = info(expression);
184
+ let inner = factor;
185
+ let innerParams = params;
186
+ let countdown;
187
+ switch (v.id) {
188
+ case binaryen.LocalSetId: {
189
+ const value = info(v.value);
190
+ if (value.id === binaryen.LocalGetId && inputs?.input(value.index))
191
+ initial.set(v.index, { parameter: value.index });
192
+ else if (value.id === binaryen.ConstId &&
193
+ typeof value.value === 'number' &&
194
+ value.value >= 1)
195
+ initial.set(v.index, { constant: value.value });
196
+ else
197
+ initial.delete(v.index);
198
+ add(factor, params, 1, 0);
199
+ break;
200
+ }
201
+ case binaryen.LoopId: {
202
+ countdown = countdownLocal(v);
203
+ const bound = (countdown === undefined ? undefined : initial.get(countdown)) ??
204
+ loopBound(v, inputs);
205
+ if (bound && 'parameter' in bound)
206
+ innerParams = [...params, bound.parameter].sort((a, b) => a - b);
207
+ else
208
+ inner = Math.min(factor * (bound && 'constant' in bound ? bound.constant : assumedTrips), SCALE_LIMIT);
209
+ break;
210
+ }
211
+ case binaryen.CallId: {
212
+ const known = callee(v.target);
213
+ add(factor, params, CALL_COST + (known?.compute ?? 0), known?.accesses ?? 0);
214
+ break;
215
+ }
216
+ case binaryen.LoadId:
217
+ case binaryen.StoreId:
218
+ add(factor, params, 1, 1);
219
+ break;
220
+ case binaryen.MemoryCopyId:
221
+ case binaryen.MemoryFillId: {
222
+ const size = info(v.size);
223
+ add(factor, params, 1, size.id === binaryen.ConstId ? Number(size.value) >>> 0 : assumedTrips);
224
+ break;
225
+ }
226
+ case binaryen.BlockId:
227
+ case binaryen.ConstId:
228
+ case binaryen.LocalGetId:
229
+ case binaryen.NopId:
230
+ case binaryen.DropId:
231
+ break;
232
+ default:
233
+ add(factor, params, 1, 0);
234
+ }
235
+ for (const child of children(v))
236
+ visit(child, inner, innerParams);
237
+ if (countdown !== undefined)
238
+ initial.delete(countdown);
239
+ };
240
+ visit(body, 1, []);
241
+ return [...terms.values()];
242
+ }
243
+ function mergeTerms(lists) {
244
+ const merged = new Map();
245
+ for (const term of lists.flat()) {
246
+ const key = term.params.join(',');
247
+ const known = merged.get(key) ?? { params: term.params, compute: 0, accesses: 0 };
248
+ known.compute += term.compute;
249
+ known.accesses += term.accesses;
250
+ merged.set(key, known);
251
+ }
252
+ return [...merged.values()];
253
+ }
254
+ /** Numeric work with every parameter-bounded loop assumed to run `assumedTrips` times. */
255
+ export function settleWork(terms, assumedTrips) {
256
+ const total = { compute: 0, accesses: 0 };
257
+ for (const term of terms) {
258
+ const factor = Math.min(assumedTrips ** term.params.length, SCALE_LIMIT);
259
+ total.compute = Math.min(total.compute + factor * term.compute, SCALE_LIMIT);
260
+ total.accesses = Math.min(total.accesses + factor * term.accesses, SCALE_LIMIT);
261
+ }
262
+ return total;
263
+ }
264
+ export function estimateWork(body, callee, assumedTrips) {
265
+ return settleWork(estimateTerms(body, callee, assumedTrips), assumedTrips);
266
+ }
267
+ export const netWork = (work) => work.compute - ACCESS_COST * work.accesses;
268
+ /**
269
+ * `static` regions always run as regions, `dynamic` ones when their parameters make the estimate
270
+ * reach the threshold at the call, and the rest never. A threshold of zero admits every region.
271
+ */
272
+ function classify(terms, minimum) {
273
+ if (minimum === 0)
274
+ return 'static';
275
+ const fixed = terms.filter((term) => !term.params.length);
276
+ if (fixed.reduce((sum, term) => sum + netWork(term), 0) >= minimum)
277
+ return 'static';
278
+ return terms.some((term) => term.params.length && netWork(term) > 0) ? 'dynamic' : 'refused';
279
+ }
280
+ /** Resolves defaults and rejects values the estimate cannot use. */
281
+ export function admission(options) {
282
+ const minimumWork = options.minimumRegionWork ?? DEFAULT_MINIMUM_REGION_WORK;
283
+ const assumedTrips = options.assumedTripCount ?? DEFAULT_ASSUMED_TRIP_COUNT;
284
+ if (!Number.isFinite(minimumWork) || minimumWork < 0)
285
+ throw new RangeError('invalid minimumRegionWork');
286
+ if (!Number.isInteger(assumedTrips) || assumedTrips < 1)
287
+ throw new RangeError('invalid assumedTripCount');
288
+ return { minimumWork, assumedTrips };
289
+ }
290
+ export function extract(original, prepareTracked, options = {}) {
291
+ const { minimumWork, assumedTrips } = admission(options);
292
+ let module;
293
+ let worker;
294
+ try {
295
+ if (memoryCount(original) !== 1)
296
+ return;
297
+ module = binaryen.readBinary(original);
298
+ const memory = module.getMemoryInfo();
299
+ if (memory.is64)
300
+ return;
301
+ const m = module;
302
+ const compactImports = binaryen.Features
303
+ .CompactImports;
304
+ m.setFeatures(binaryen.Features.All & ~compactImports);
305
+ const internalMemory = memoryName(m);
306
+ 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
+ let outlineIndex = 0;
360
+ const originals = Array.from({ length: m.getNumFunctions() }, (_, index) => binaryen.getFunctionInfo(m.getFunctionByIndex(index)));
361
+ const originalBodies = new Map(originals.filter((f) => f.body).map((f) => [f.name, m.copyExpression(f.body)]));
362
+ for (const f of originals) {
363
+ if (!f.body)
364
+ continue;
365
+ const localTypes = [...binaryen.expandType(f.params), ...f.vars];
366
+ if (!localTypes.every((type) => numeric.has(type)))
367
+ continue;
368
+ const totalReads = new Map();
369
+ let traversable = true;
370
+ const count = (expression) => {
371
+ const v = info(expression);
372
+ if (!supported.has(v.id))
373
+ traversable = false;
374
+ if (v.id === binaryen.LocalGetId)
375
+ totalReads.set(v.index, (totalReads.get(v.index) ?? 0) + 1);
376
+ for (const child of children(v))
377
+ count(child);
378
+ };
379
+ try {
380
+ count(f.body);
381
+ }
382
+ catch {
383
+ traversable = false;
384
+ }
385
+ if (!traversable)
386
+ continue;
387
+ 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;
437
+ };
438
+ 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
+ }
508
+ if (carried.size) {
509
+ const result = [];
510
+ let pending = [];
511
+ for (const span of spans) {
512
+ if ([...span.writes].some((index) => carried.has(index))) {
513
+ if (pending.length)
514
+ result.push(...outline(pending));
515
+ pending = [];
516
+ result.push(span.expression);
517
+ }
518
+ else
519
+ pending.push(span);
520
+ }
521
+ if (pending.length)
522
+ result.push(...outline(pending));
523
+ return result;
524
+ }
525
+ if (!spans.some((span) => span.memoryWrite) || !spans.some((span) => span.compute))
526
+ return spans.map((span) => span.expression);
527
+ const written = new Set(spans.flatMap((span) => [...span.writes]));
528
+ const spanned = mergeTerms(spans.map((span) => estimateTerms(span.expression, () => undefined, assumedTrips, {
529
+ input: (index) => !written.has(index),
530
+ counter: (index) => written.has(index)
531
+ })));
532
+ const verdict = classify(spanned, minimumWork);
533
+ if (options.observed) {
534
+ const work = settleWork(spanned, assumedTrips);
535
+ options.observed({ name: `span in ${f.name}`, kind: verdict, ...work });
536
+ }
537
+ if (verdict === 'refused')
538
+ return spans.map((span) => span.expression);
539
+ const captured = [...new Set(spans.flatMap((span) => [...span.locals]))].sort((a, b) => a - b);
540
+ const positions = new Map(captured.map((index, position) => [index, position]));
541
+ 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);
552
+ let name;
553
+ do {
554
+ name = `__folio_inline_${outlineIndex++}`;
555
+ } while (m.getFunction(name));
556
+ m.addFunction(name, binaryen.createType(captured.map((index) => localTypes[index])), binaryen.none, [], body);
557
+ return [
558
+ m.call(name, captured.map((index) => m.local.get(index, localTypes[index])), binaryen.none)
559
+ ];
560
+ };
561
+ const rewrite = (expression) => {
562
+ const v = info(expression);
563
+ for (const child of children(v))
564
+ rewrite(child);
565
+ if (v.id !== binaryen.BlockId)
566
+ return;
567
+ const current = info(expression).children;
568
+ const rewritten = [];
569
+ let pending = [];
570
+ for (const child of current) {
571
+ const span = summarize(child);
572
+ if (span)
573
+ pending.push(span);
574
+ else {
575
+ if (pending.length)
576
+ rewritten.push(...outline(pending));
577
+ pending = [];
578
+ rewritten.push(child);
579
+ }
580
+ }
581
+ if (pending.length)
582
+ rewritten.push(...outline(pending));
583
+ for (let i = current.length - 1; i >= 0; i--)
584
+ raw._BinaryenBlockRemoveChildAt(expression, i);
585
+ for (const child of rewritten)
586
+ raw._BinaryenBlockAppendChild(expression, child);
587
+ };
588
+ rewrite(f.body);
589
+ }
590
+ for (let i = 0; i < m.getNumFunctions(); i++) {
591
+ const f = binaryen.getFunctionInfo(m.getFunctionByIndex(i));
592
+ functions.set(f.name, f);
593
+ }
594
+ const controllers = new Set();
595
+ const pure = new Set();
596
+ const calls = new Map();
597
+ const diagnostics = [];
598
+ for (const f of functions.values()) {
599
+ if (!f.body)
600
+ continue;
601
+ let control = [...binaryen.expandType(f.params), ...f.vars].every((t) => numeric.has(t)) &&
602
+ (f.results === binaryen.none || numeric.has(f.results));
603
+ let candidate = control;
604
+ const targets = new Set();
605
+ const visit = (expression) => {
606
+ const v = info(expression);
607
+ if (!supported.has(v.id))
608
+ control = false;
609
+ if (!pureNodes.has(v.id) || v.isAtomic)
610
+ candidate = false;
611
+ if (![binaryen.none, binaryen.unreachable].includes(v.type) &&
612
+ !numeric.has(v.type)) {
613
+ control = false;
614
+ candidate = false;
615
+ }
616
+ if (v.id === binaryen.CallId) {
617
+ targets.add(v.target);
618
+ if (v.operands.some((e) => !numeric.has(info(e).type)))
619
+ control = false;
620
+ }
621
+ if (v.id === binaryen.CallIndirectId &&
622
+ children(v).some((e) => !numeric.has(info(e).type)))
623
+ control = false;
624
+ for (const child of children(v))
625
+ visit(child);
626
+ };
627
+ try {
628
+ visit(f.body);
629
+ }
630
+ catch {
631
+ control = candidate = false;
632
+ }
633
+ calls.set(f.name, targets);
634
+ if (control)
635
+ controllers.add(f.name);
636
+ else
637
+ diagnostics.push(`ordered native function: ${f.name}`);
638
+ if (candidate && control)
639
+ pure.add(f.name);
640
+ }
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) {
678
+ controllers.delete(name);
679
+ pure.delete(name);
680
+ diagnostics.push(`ordered native recursion: ${name}`);
681
+ }
682
+ for (let changed = true; changed;) {
683
+ changed = false;
684
+ for (const name of pure) {
685
+ if ([...calls.get(name)].some((target) => !pure.has(target))) {
686
+ pure.delete(name);
687
+ changed = true;
688
+ }
689
+ }
690
+ }
691
+ if (!pure.size) {
692
+ options.refused?.('no pure function to run as a region');
693
+ return;
694
+ }
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;
719
+ const admitted = new Set();
720
+ const guarded = new Map();
721
+ for (const name of pure) {
722
+ const kind = classify(termsOf(name), minimumWork);
723
+ options.observed?.({
724
+ name,
725
+ kind,
726
+ ...settleWork(termsOf(name), assumedTrips)
727
+ });
728
+ if (kind !== 'refused')
729
+ admitted.add(name);
730
+ if (kind === 'dynamic')
731
+ guarded.set(name, termsOf(name));
732
+ }
733
+ const enqueued = new Set();
734
+ const queued = new Set();
735
+ const enqueues = (v) => {
736
+ const call = v.id === binaryen.DropId ? info(v.value) : v;
737
+ const direct = v.id === binaryen.CallId && v.type === binaryen.none;
738
+ if (call.id === binaryen.CallId &&
739
+ !call.isReturn &&
740
+ (direct || v.id === binaryen.DropId) &&
741
+ admitted.has(call.target))
742
+ return call.target;
743
+ };
744
+ for (const name of controllers) {
745
+ const visit = (e) => {
746
+ const v = info(e);
747
+ const target = enqueues(v);
748
+ if (target) {
749
+ enqueued.add(target);
750
+ queued.add(name);
751
+ }
752
+ for (const child of children(v))
753
+ visit(child);
754
+ };
755
+ visit(functions.get(name).body);
756
+ }
757
+ if (!enqueued.size) {
758
+ options.refused?.(admitted.size
759
+ ? `no admitted region has a call site (${pure.size} pure functions, ${admitted.size} admitted)`
760
+ : `no region reached ${minimumWork} net work (${pure.size} pure functions, none admitted)`);
761
+ return;
762
+ }
763
+ for (let changed = true; changed;) {
764
+ changed = false;
765
+ for (const name of controllers) {
766
+ if (!queued.has(name) &&
767
+ [...calls.get(name)].some((target) => controllers.has(target) && queued.has(target))) {
768
+ queued.add(name);
769
+ changed = true;
770
+ }
771
+ }
772
+ }
773
+ // a function that never reaches a region keeps its original body and runs natively
774
+ for (const name of [...controllers])
775
+ if (!queued.has(name))
776
+ controllers.delete(name);
777
+ for (const f of originals) {
778
+ if (f.body && !controllers.has(f.name))
779
+ raw._BinaryenFunctionSetBody(m.getFunction(f.name), originalBodies.get(f.name));
780
+ }
781
+ diagnostics.push(`region admission: ${enqueued.size} regions from ${admitted.size} of ${pure.size} pure functions at ${minimumWork} net work; ${queued.size} instrumented`);
782
+ let namespace = '__folio_control';
783
+ const imported = WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(original)));
784
+ while (imported.some((item) => item.module === namespace))
785
+ namespace += '_';
786
+ let serial = '__folio_control_serial';
787
+ while (m.getGlobal(serial))
788
+ serial += '_';
789
+ let pending = '__folio_control_pending';
790
+ while (m.getGlobal(pending))
791
+ pending += '_';
792
+ let memoryExport = '__folio_control_memory';
793
+ while (m.getExport(memoryExport))
794
+ memoryExport += '_';
795
+ const unique = (stem) => {
796
+ let name = stem;
797
+ while (m.getFunction(name) || m.getExport(name))
798
+ name += '_';
799
+ return name;
800
+ };
801
+ const barrier = unique('__folio_control_barrier');
802
+ m.addFunctionImport(barrier, namespace, 'barrier', binaryen.none, binaryen.none);
803
+ const poll = unique('__folio_control_poll');
804
+ m.addFunctionImport(poll, namespace, 'poll', binaryen.none, binaryen.none);
805
+ m.addGlobalImport(serial, namespace, 'serial', binaryen.i32, true);
806
+ m.addGlobalImport(pending, namespace, 'pending', binaryen.i32, true);
807
+ m.addMemoryExport(internalMemory, memoryExport);
808
+ worker = new binaryen.Module();
809
+ const w = worker;
810
+ const maximum = memory.max ?? 65536;
811
+ w.setFeatures(m.getFeatures() | binaryen.Features.Atomics);
812
+ w.setMemory(memory.initial, maximum, null, [], true, false, internalMemory);
813
+ w.addMemoryImport(internalMemory, 'env', 'memory', true);
814
+ for (const name of pure) {
815
+ const f = functions.get(name);
816
+ w.addFunction(name, f.params, f.results, f.vars, w.copyExpression(f.body));
817
+ }
818
+ for (let i = 0; i < m.getNumExports(); i++) {
819
+ const exported = binaryen.getExportInfo(m.getExportByIndex(i));
820
+ if (exported.kind === binaryen.ExternalFunction && pure.has(exported.value))
821
+ w.addFunctionExport(exported.value, exported.name);
822
+ }
823
+ const regions = [];
824
+ const enqueueFor = new Map();
825
+ for (const name of enqueued) {
826
+ const f = functions.get(name);
827
+ const params = binaryen.expandType(f.params);
828
+ const encoded = params.map((t) => t === binaryen.i64 || t === binaryen.f64 ? binaryen.i64 : binaryen.i32);
829
+ const exportName = unique(`__folio_region_${regions.length}`);
830
+ const importName = `region_${regions.length}`;
831
+ const descriptor = {
832
+ importName,
833
+ exportName,
834
+ parameters: encoded.map((t) => t === binaryen.i64 ? 'i64' : 'i32')
835
+ };
836
+ regions.push(descriptor);
837
+ const wrapper = (target) => {
838
+ const args = params.map((t, i) => {
839
+ const value = target.local.get(i, encoded[i]);
840
+ return t === binaryen.f32
841
+ ? target.f32.reinterpret(value)
842
+ : t === binaryen.f64
843
+ ? target.f64.reinterpret(value)
844
+ : value;
845
+ });
846
+ const call = target.call(name, args, f.results);
847
+ target.addFunction(exportName, binaryen.createType(encoded), binaryen.none, [], f.results === binaryen.none ? call : target.drop(call));
848
+ target.addFunctionExport(exportName, exportName);
849
+ };
850
+ wrapper(m);
851
+ wrapper(w);
852
+ const enqueue = unique(`__folio_enqueue_${regions.length - 1}`);
853
+ enqueueFor.set(name, enqueue);
854
+ m.addFunctionImport(enqueue, namespace, importName, binaryen.createType(encoded), binaryen.none);
855
+ }
856
+ const labels = new Map();
857
+ for (const name of controllers) {
858
+ const map = new Map();
859
+ const existing = new Set();
860
+ const visit = (e) => {
861
+ const v = info(e);
862
+ if ((v.id === binaryen.BlockId || v.id === binaryen.LoopId) && v.name)
863
+ existing.add(v.name);
864
+ for (const child of children(v))
865
+ visit(child);
866
+ };
867
+ visit(functions.get(name).body);
868
+ for (const label of existing) {
869
+ let replacement = `${label}__folio`;
870
+ while (existing.has(replacement) || [...map.values()].includes(replacement))
871
+ replacement += '_';
872
+ map.set(label, replacement);
873
+ }
874
+ labels.set(name, map);
875
+ }
876
+ let helperIndex = 0;
877
+ const memoryHelpers = new Map();
878
+ const trappedUnary = new Set([
879
+ binaryen.TruncSFloat32ToInt32,
880
+ binaryen.TruncUFloat32ToInt32,
881
+ binaryen.TruncSFloat64ToInt32,
882
+ binaryen.TruncUFloat64ToInt32,
883
+ binaryen.TruncSFloat32ToInt64,
884
+ binaryen.TruncUFloat32ToInt64,
885
+ binaryen.TruncSFloat64ToInt64,
886
+ binaryen.TruncUFloat64ToInt64
887
+ ]);
888
+ const trappedBinary = new Set([
889
+ binaryen.DivSInt32,
890
+ binaryen.DivUInt32,
891
+ binaryen.RemSInt32,
892
+ binaryen.RemUInt32,
893
+ binaryen.DivSInt64,
894
+ binaryen.DivUInt64,
895
+ binaryen.RemSInt64,
896
+ binaryen.RemUInt64
897
+ ]);
898
+ // the host raises `pending` while regions are queued; an empty queue never crosses into JSPI
899
+ const whenPending = (target) => m.if(m.global.get(pending, binaryen.i32), m.call(target, [], binaryen.none));
900
+ const drain = () => whenPending(barrier);
901
+ const joinPoll = () => whenPending(poll);
902
+ // a call the owner makes natively: queued regions join first, and callees see serial set
903
+ const hostCalls = new Map();
904
+ const hostCall = (target) => {
905
+ const known = hostCalls.get(target);
906
+ if (known)
907
+ return known;
908
+ const callee = functions.get(target);
909
+ const types = binaryen.expandType(callee.params);
910
+ const result = callee.results;
911
+ const name = unique(`__folio_control_host_${helperIndex++}`);
912
+ const native = m.call(target, types.map((t, i) => m.local.get(i, t)), result);
913
+ const prefix = [drain(), m.global.set(serial, m.i32.const(1))];
914
+ const vars = result === binaryen.none ? [] : [result];
915
+ const code = vars.length
916
+ ? m.block(null, [
917
+ ...prefix,
918
+ m.local.set(types.length, native),
919
+ m.global.set(serial, m.i32.const(0)),
920
+ m.local.get(types.length, result)
921
+ ], result)
922
+ : m.block(null, [...prefix, native, m.global.set(serial, m.i32.const(0))], result);
923
+ m.addFunction(name, binaryen.createType(types), result, vars, code);
924
+ hostCalls.set(target, name);
925
+ return name;
926
+ };
927
+ // a region with a parameter-bounded loop compares its estimate with the threshold per call
928
+ const routes = new Map();
929
+ for (const name of enqueued) {
930
+ const entry = enqueueFor.get(name);
931
+ const terms = guarded.get(name);
932
+ if (!terms) {
933
+ routes.set(name, { callee: entry, encoded: true });
934
+ continue;
935
+ }
936
+ const f = functions.get(name);
937
+ const params = binaryen.expandType(f.params);
938
+ const local = (i) => m.local.get(i, params[i]);
939
+ let work = m.f64.const(0);
940
+ for (const term of terms) {
941
+ if (!netWork(term))
942
+ continue;
943
+ let product = m.f64.const(netWork(term));
944
+ for (const parameter of term.params)
945
+ product = m.f64.mul(product, m.f64.convert_u.i32(local(parameter)));
946
+ work = m.f64.add(work, product);
947
+ }
948
+ const queue = m.call(entry, params.map((t, i) => t === binaryen.f32
949
+ ? m.i32.reinterpret(local(i))
950
+ : t === binaryen.f64
951
+ ? m.i64.reinterpret(local(i))
952
+ : local(i)), binaryen.none);
953
+ const native = m.call(hostCall(name), params.map((_, i) => local(i)), f.results);
954
+ const dispatch = unique(`__folio_dispatch_${routes.size}`);
955
+ m.addFunction(dispatch, binaryen.createType(params), binaryen.none, [], m.if(m.f64.ge(work, m.f64.const(minimumWork)), queue, f.results === binaryen.none ? native : m.drop(native)));
956
+ routes.set(name, { callee: dispatch, encoded: false });
957
+ }
958
+ const helper = (expression, operands, setters, opaque = false) => {
959
+ const v = info(expression);
960
+ const resultType = v.id === binaryen.CallIndirectId ? v.results : v.type;
961
+ const types = operands.map((e) => info(e).type);
962
+ if (types.some((type) => !numeric.has(type)))
963
+ throw new Error('non-scalar helper operand');
964
+ // One memory is admitted. Retain every opcode attribute; only operands become parameters.
965
+ const memoryKey = v.id === binaryen.LoadId || v.id === binaryen.StoreId
966
+ ? JSON.stringify([
967
+ types,
968
+ Object.entries(v).filter(([key]) => key !== 'ptr' && key !== 'value')
969
+ ])
970
+ : undefined;
971
+ if (memoryKey !== undefined) {
972
+ const existing = memoryHelpers.get(memoryKey);
973
+ if (existing)
974
+ return existing;
975
+ }
976
+ const body = v.id === binaryen.CallIndirectId && v.isReturn
977
+ ? m.call_indirect(v.table, v.target, v.operands, v.params, v.results)
978
+ : m.copyExpression(expression);
979
+ for (let i = 0; i < setters.length; i++) {
980
+ if (setters[i].startsWith('operand:')) {
981
+ const index = Number(setters[i].slice(8));
982
+ raw._BinaryenCallIndirectSetOperandAt(body, index, m.local.get(i, types[i]));
983
+ }
984
+ else
985
+ raw[setters[i]](body, m.local.get(i, types[i]));
986
+ }
987
+ const name = unique(`__folio_control_helper_${helperIndex++}`);
988
+ let code;
989
+ const vars = [];
990
+ if (!opaque)
991
+ code = m.block(null, [drain(), body], resultType);
992
+ else {
993
+ const prefix = [drain(), m.global.set(serial, m.i32.const(1))];
994
+ if (resultType === binaryen.none || resultType === binaryen.unreachable)
995
+ code = m.block(null, [...prefix, body, m.global.set(serial, m.i32.const(0))], resultType);
996
+ else {
997
+ vars.push(resultType);
998
+ code = m.block(null, [
999
+ ...prefix,
1000
+ m.local.set(types.length, body),
1001
+ m.global.set(serial, m.i32.const(0)),
1002
+ m.local.get(types.length, resultType)
1003
+ ], resultType);
1004
+ }
1005
+ }
1006
+ const result = resultType === binaryen.unreachable ? binaryen.none : resultType;
1007
+ m.addFunction(name, binaryen.createType(types), result, vars, code);
1008
+ const reference = { name, result };
1009
+ if (memoryKey !== undefined)
1010
+ memoryHelpers.set(memoryKey, reference);
1011
+ return reference;
1012
+ };
1013
+ const lower = (expression, owner) => {
1014
+ const v = info(expression);
1015
+ const label = (name) => labels.get(owner).get(name) ?? name;
1016
+ const callHelper = (operands, setters, opaque = false) => {
1017
+ const h = helper(expression, operands, setters, opaque);
1018
+ const values = operands.map((e) => lower(e, owner));
1019
+ return v.id === binaryen.CallIndirectId && v.isReturn
1020
+ ? m.return_call(h.name, values, h.result)
1021
+ : m.call(h.name, values, h.result);
1022
+ };
1023
+ const enqueue = (call) => {
1024
+ const route = routes.get(call.target);
1025
+ const values = call.operands.map((e) => {
1026
+ const value = lower(e, owner);
1027
+ const type = info(e).type;
1028
+ return !route.encoded
1029
+ ? value
1030
+ : type === binaryen.f32
1031
+ ? m.i32.reinterpret(value)
1032
+ : type === binaryen.f64
1033
+ ? m.i64.reinterpret(value)
1034
+ : value;
1035
+ });
1036
+ return m.call(route.callee, values, binaryen.none);
1037
+ };
1038
+ switch (v.id) {
1039
+ case binaryen.BlockId:
1040
+ return m.block(label(v.name), v.children.map((e) => lower(e, owner)), v.type);
1041
+ case binaryen.IfId:
1042
+ return m.if(lower(v.condition, owner), lower(v.ifTrue, owner), v.ifFalse ? lower(v.ifFalse, owner) : undefined);
1043
+ case binaryen.LoopId:
1044
+ return m.loop(label(v.name), m.block(null, [joinPoll(), lower(v.body, owner)], info(v.body).type));
1045
+ case binaryen.BreakId:
1046
+ return m.br(label(v.name), v.condition ? lower(v.condition, owner) : undefined, v.value ? lower(v.value, owner) : undefined);
1047
+ case binaryen.SwitchId:
1048
+ return m.switch(v.names.map(label), label(v.defaultName), lower(v.condition, owner), v.value ? lower(v.value, owner) : undefined);
1049
+ case binaryen.CallId: {
1050
+ if (!v.isReturn && v.type === binaryen.none && enqueueFor.has(v.target))
1051
+ return enqueue(v);
1052
+ const result = functions.get(v.target).results;
1053
+ const args = v.operands.map((e) => lower(e, owner));
1054
+ if (controllers.has(v.target))
1055
+ return v.isReturn
1056
+ ? m.return_call(v.target, args, result)
1057
+ : m.call(v.target, args, result);
1058
+ const target = hostCall(v.target);
1059
+ return v.isReturn
1060
+ ? m.return_call(target, args, result)
1061
+ : m.call(target, args, result);
1062
+ }
1063
+ case binaryen.CallIndirectId:
1064
+ return callHelper([...v.operands, v.target], [
1065
+ ...v.operands.map((_, i) => `operand:${i}`),
1066
+ '_BinaryenCallIndirectSetTarget'
1067
+ ], true);
1068
+ case binaryen.LocalSetId:
1069
+ return v.isTee
1070
+ ? m.local.tee(v.index, lower(v.value, owner), v.type)
1071
+ : m.local.set(v.index, lower(v.value, owner));
1072
+ case binaryen.LoadId:
1073
+ return callHelper([v.ptr], ['_BinaryenLoadSetPtr']);
1074
+ case binaryen.StoreId:
1075
+ return callHelper([v.ptr, v.value], ['_BinaryenStoreSetPtr', '_BinaryenStoreSetValue']);
1076
+ case binaryen.GlobalGetId:
1077
+ case binaryen.MemorySizeId:
1078
+ case binaryen.TableSizeId:
1079
+ case binaryen.DataDropId:
1080
+ return callHelper([], []);
1081
+ case binaryen.GlobalSetId:
1082
+ return callHelper([v.value], ['_BinaryenGlobalSetSetValue']);
1083
+ case binaryen.MemoryGrowId:
1084
+ return callHelper([v.delta], ['_BinaryenMemoryGrowSetDelta']);
1085
+ case binaryen.MemoryCopyId:
1086
+ return callHelper([v.dest, v.source, v.size], [
1087
+ '_BinaryenMemoryCopySetDest',
1088
+ '_BinaryenMemoryCopySetSource',
1089
+ '_BinaryenMemoryCopySetSize'
1090
+ ]);
1091
+ case binaryen.MemoryFillId:
1092
+ return callHelper([v.dest, v.value, v.size], [
1093
+ '_BinaryenMemoryFillSetDest',
1094
+ '_BinaryenMemoryFillSetValue',
1095
+ '_BinaryenMemoryFillSetSize'
1096
+ ]);
1097
+ case binaryen.MemoryInitId:
1098
+ return callHelper([v.dest, v.offset, v.size], [
1099
+ '_BinaryenMemoryInitSetDest',
1100
+ '_BinaryenMemoryInitSetOffset',
1101
+ '_BinaryenMemoryInitSetSize'
1102
+ ]);
1103
+ case binaryen.UnaryId:
1104
+ return trappedUnary.has(v.op)
1105
+ ? callHelper([v.value], ['_BinaryenUnarySetValue'])
1106
+ : raw._BinaryenUnary(m.ptr, v.op, lower(v.value, owner));
1107
+ case binaryen.BinaryId:
1108
+ return trappedBinary.has(v.op)
1109
+ ? callHelper([v.left, v.right], ['_BinaryenBinarySetLeft', '_BinaryenBinarySetRight'])
1110
+ : raw._BinaryenBinary(m.ptr, v.op, lower(v.left, owner), lower(v.right, owner));
1111
+ case binaryen.SelectId:
1112
+ return m.select(lower(v.condition, owner), lower(v.ifTrue, owner), lower(v.ifFalse, owner));
1113
+ case binaryen.DropId: {
1114
+ const child = info(v.value);
1115
+ return child.id === binaryen.CallId &&
1116
+ !child.isReturn &&
1117
+ enqueueFor.has(child.target)
1118
+ ? enqueue(child)
1119
+ : m.drop(lower(v.value, owner));
1120
+ }
1121
+ case binaryen.ReturnId:
1122
+ return m.return(v.value ? lower(v.value, owner) : undefined);
1123
+ case binaryen.UnreachableId:
1124
+ return m.block(null, [drain(), m.unreachable()]);
1125
+ default:
1126
+ return m.copyExpression(expression);
1127
+ }
1128
+ };
1129
+ for (const name of controllers) {
1130
+ const f = functions.get(name);
1131
+ const transformed = m.block(null, [joinPoll(), lower(f.body, name)], f.results);
1132
+ raw._BinaryenFunctionSetBody(m.getFunction(name), m.if(m.global.get(serial, binaryen.i32), m.copyExpression(originalBodies.get(name) ?? f.body), transformed));
1133
+ }
1134
+ const entries = [];
1135
+ for (let i = 0; i < m.getNumExports(); i++) {
1136
+ const exported = binaryen.getExportInfo(m.getExportByIndex(i));
1137
+ if (exported.kind === binaryen.ExternalFunction &&
1138
+ functions.has(exported.value) &&
1139
+ queued.has(exported.value))
1140
+ entries.push(exported.name);
1141
+ }
1142
+ if (!entries.length) {
1143
+ options.refused?.('no exported function reaches an admitted region');
1144
+ return;
1145
+ }
1146
+ if (!m.validate() || !w.validate())
1147
+ throw new Error('invalid control extraction');
1148
+ const coordinator = restoreImportOrder(m.emitBinary(), WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(original))));
1149
+ const workerOriginal = w.emitBinary();
1150
+ new WebAssembly.Module(Uint8Array.from(coordinator));
1151
+ new WebAssembly.Module(Uint8Array.from(workerOriginal));
1152
+ const transactional = prepareTracked(workerOriginal).transactional;
1153
+ if (!transactional)
1154
+ throw new Error('control worker transactional lowering unavailable');
1155
+ new WebAssembly.Module(Uint8Array.from(transactional));
1156
+ return {
1157
+ coordinator,
1158
+ workerOriginal,
1159
+ transactional,
1160
+ namespace,
1161
+ serialGlobal: 'serial',
1162
+ pendingGlobal: 'pending',
1163
+ memoryExport,
1164
+ shared: memory.shared,
1165
+ initial: memory.initial,
1166
+ maximum,
1167
+ entries,
1168
+ regions,
1169
+ diagnostics
1170
+ };
1171
+ }
1172
+ finally {
1173
+ worker?.dispose();
1174
+ module?.dispose();
1175
+ }
1176
+ }