@gmitch215/folio 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +541 -2
- package/dist/bake.d.ts +179 -0
- package/dist/bake.js +704 -0
- package/dist/browser-worker.d.ts +9 -0
- package/dist/browser-worker.js +37 -0
- package/dist/browser.d.ts +68 -0
- package/dist/browser.js +274 -0
- package/dist/compiler.d.ts +79 -0
- package/dist/compiler.js +620 -0
- package/dist/context.d.ts +33 -0
- package/dist/context.js +93 -0
- package/dist/coordinator.d.ts +27 -0
- package/dist/coordinator.js +191 -0
- package/dist/extract.d.ts +165 -0
- package/dist/extract.js +1817 -0
- package/dist/frames.d.ts +33 -0
- package/dist/frames.js +159 -0
- package/dist/guards.d.ts +12 -0
- package/dist/guards.js +202 -0
- package/dist/host.d.ts +60 -0
- package/dist/host.js +374 -0
- package/dist/import-order.d.ts +2 -0
- package/dist/import-order.js +114 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/inline.d.ts +68 -0
- package/dist/inline.js +503 -0
- package/dist/iteration-admission.d.ts +76 -0
- package/dist/iteration-admission.js +72 -0
- package/dist/iteration-layout.d.ts +75 -0
- package/dist/iteration-layout.js +118 -0
- package/dist/iteration-owner.d.ts +32 -0
- package/dist/iteration-owner.js +223 -0
- package/dist/iteration-worker.d.ts +1 -0
- package/dist/iteration-worker.js +150 -0
- package/dist/iteration.d.ts +163 -0
- package/dist/iteration.js +435 -0
- package/dist/managed.d.ts +92 -0
- package/dist/managed.js +421 -0
- package/dist/memory.d.ts +10 -0
- package/dist/memory.js +89 -0
- package/dist/node.d.ts +138 -0
- package/dist/node.js +1153 -0
- package/dist/pages.d.ts +109 -0
- package/dist/pages.js +339 -0
- package/dist/remote.d.ts +86 -0
- package/dist/remote.js +255 -0
- package/dist/tasks.d.ts +107 -0
- package/dist/tasks.js +330 -0
- package/dist/transaction.d.ts +23 -0
- package/dist/transaction.js +93 -0
- package/dist/values.d.ts +3 -0
- package/dist/values.js +25 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +86 -0
- package/package.json +130 -5
package/dist/compiler.js
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
import binaryen from 'binaryen';
|
|
2
|
+
import { admission, extract, iterationRoute, stackRoute } from "./extract.js";
|
|
3
|
+
import { nativePlan } from "./guards.js";
|
|
4
|
+
/**
|
|
5
|
+
* Exposes Wasm memories, mutable globals and tables for private-context reset. This adds exports
|
|
6
|
+
* only; start functions and code run normally. Unsupported metadata retains the original module.
|
|
7
|
+
* Host effects, passive segment drop state and objects behind references require recreation or
|
|
8
|
+
* a caller-owned reset. Modules using segment drop are refused for checkpoint reuse.
|
|
9
|
+
* @since 1.0.1
|
|
10
|
+
*/
|
|
11
|
+
export function prepareContext(input) {
|
|
12
|
+
const original = Uint8Array.from(input), native = new WebAssembly.Module(original);
|
|
13
|
+
const result = {
|
|
14
|
+
original,
|
|
15
|
+
bytes: original,
|
|
16
|
+
memories: [],
|
|
17
|
+
globals: [],
|
|
18
|
+
tables: [],
|
|
19
|
+
reasons: []
|
|
20
|
+
};
|
|
21
|
+
let mod;
|
|
22
|
+
try {
|
|
23
|
+
mod = binaryen.readBinary(original);
|
|
24
|
+
mod.setFeatures(binaryen.Features.All);
|
|
25
|
+
// passive segment and gc state cannot be restored through exported bindings
|
|
26
|
+
const text = mod.emitText();
|
|
27
|
+
if (/\((?:data|elem)\.drop(?:\s|\))/.test(text))
|
|
28
|
+
throw new TypeError('passive segment drop state requires recreation');
|
|
29
|
+
if (/\((?:struct|array)\./.test(text))
|
|
30
|
+
throw new TypeError('Wasm GC object state requires recreation');
|
|
31
|
+
const exports = new Set(WebAssembly.Module.exports(native).map((item) => item.name));
|
|
32
|
+
let prefix = '__folio_context_';
|
|
33
|
+
while ([...exports].some((name) => name.startsWith(prefix)))
|
|
34
|
+
prefix += '_';
|
|
35
|
+
const additions = [];
|
|
36
|
+
const leb = (value) => {
|
|
37
|
+
const out = [];
|
|
38
|
+
do {
|
|
39
|
+
const byte = value & 127;
|
|
40
|
+
value = Math.floor(value / 128);
|
|
41
|
+
out.push(byte | (value ? 128 : 0));
|
|
42
|
+
} while (value);
|
|
43
|
+
return out;
|
|
44
|
+
};
|
|
45
|
+
const add = (kind, index, names, label) => {
|
|
46
|
+
const name = `${prefix}${label}${index}`, encoded = new TextEncoder().encode(name);
|
|
47
|
+
additions.push(...leb(encoded.length), ...encoded, kind, ...leb(index));
|
|
48
|
+
names.push(name);
|
|
49
|
+
};
|
|
50
|
+
let cursor = 8, definedMemories = 0;
|
|
51
|
+
const unsigned = () => {
|
|
52
|
+
let value = 0, shift = 0, byte;
|
|
53
|
+
do {
|
|
54
|
+
byte = original[cursor++];
|
|
55
|
+
value += (byte & 127) * 2 ** shift;
|
|
56
|
+
shift += 7;
|
|
57
|
+
} while (byte & 128);
|
|
58
|
+
return value;
|
|
59
|
+
};
|
|
60
|
+
const sections = [];
|
|
61
|
+
while (cursor < original.length) {
|
|
62
|
+
const start = cursor, kind = original[cursor++], length = unsigned(), payload = cursor, end = cursor + length;
|
|
63
|
+
if (kind === 5)
|
|
64
|
+
definedMemories = unsigned();
|
|
65
|
+
sections.push({ kind, start, payload, end });
|
|
66
|
+
cursor = end;
|
|
67
|
+
}
|
|
68
|
+
const memoryCount = definedMemories +
|
|
69
|
+
WebAssembly.Module.imports(native).filter((item) => item.kind === 'memory').length;
|
|
70
|
+
for (let index = 0; index < memoryCount; index++)
|
|
71
|
+
add(2, index, result.memories, 'memory');
|
|
72
|
+
for (let index = 0; index < mod.getNumGlobals(); index++) {
|
|
73
|
+
const global = binaryen.getGlobalInfo(mod.getGlobalByIndex(index));
|
|
74
|
+
if (![binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64, binaryen.v128].includes(global.type))
|
|
75
|
+
throw new TypeError('reference global state requires recreation');
|
|
76
|
+
if (!global.mutable)
|
|
77
|
+
continue;
|
|
78
|
+
if (global.type === binaryen.v128)
|
|
79
|
+
throw new TypeError('v128 globals require recreation');
|
|
80
|
+
add(3, index, result.globals, 'global');
|
|
81
|
+
}
|
|
82
|
+
for (let index = 0; index < mod.getNumTables(); index++)
|
|
83
|
+
add(1, index, result.tables, 'table');
|
|
84
|
+
const prior = sections.find((section) => section.kind === 7);
|
|
85
|
+
let count = 0, records = new Uint8Array();
|
|
86
|
+
if (prior) {
|
|
87
|
+
cursor = prior.payload;
|
|
88
|
+
count = unsigned();
|
|
89
|
+
records = original.subarray(cursor, prior.end);
|
|
90
|
+
}
|
|
91
|
+
const addedCount = result.memories.length + result.globals.length + result.tables.length;
|
|
92
|
+
const payload = Uint8Array.from([...leb(count + addedCount), ...records, ...additions]);
|
|
93
|
+
const header = Uint8Array.from([7, ...leb(payload.length)]);
|
|
94
|
+
const position = prior?.start ??
|
|
95
|
+
sections.find((section) => [8, 9, 12, 10, 11].includes(section.kind))?.start ??
|
|
96
|
+
original.length;
|
|
97
|
+
const rest = prior?.end ?? position;
|
|
98
|
+
const bytes = new Uint8Array(position + header.length + payload.length + original.length - rest);
|
|
99
|
+
bytes.set(original.subarray(0, position));
|
|
100
|
+
bytes.set(header, position);
|
|
101
|
+
bytes.set(payload, position + header.length);
|
|
102
|
+
bytes.set(original.subarray(rest), position + header.length + payload.length);
|
|
103
|
+
new WebAssembly.Module(bytes);
|
|
104
|
+
result.bytes = bytes;
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
result.memories = [];
|
|
108
|
+
result.globals = [];
|
|
109
|
+
result.tables = [];
|
|
110
|
+
result.reasons.push(error instanceof Error ? error.message : String(error));
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
mod?.dispose();
|
|
114
|
+
}
|
|
115
|
+
return result;
|
|
116
|
+
}
|
|
117
|
+
const info = (expression) => {
|
|
118
|
+
const id = binaryen.getExpressionId(expression);
|
|
119
|
+
if (id === binaryen.UnreachableId || id === binaryen.NopId) {
|
|
120
|
+
return { id, type: binaryen.getExpressionType(expression) };
|
|
121
|
+
}
|
|
122
|
+
return binaryen.getExpressionInfo(expression);
|
|
123
|
+
};
|
|
124
|
+
function walk(expression, visit) {
|
|
125
|
+
const value = info(expression);
|
|
126
|
+
visit(value);
|
|
127
|
+
for (const key of ['children', 'operands']) {
|
|
128
|
+
for (const child of value[key] ?? [])
|
|
129
|
+
walk(child, visit);
|
|
130
|
+
}
|
|
131
|
+
for (const key of [
|
|
132
|
+
'body',
|
|
133
|
+
'condition',
|
|
134
|
+
'ifTrue',
|
|
135
|
+
'ifFalse',
|
|
136
|
+
'ptr',
|
|
137
|
+
'value',
|
|
138
|
+
'left',
|
|
139
|
+
'right',
|
|
140
|
+
'dest',
|
|
141
|
+
'source',
|
|
142
|
+
'size'
|
|
143
|
+
]) {
|
|
144
|
+
if (key === 'value' && value.id === binaryen.ConstId)
|
|
145
|
+
continue;
|
|
146
|
+
if (typeof value[key] === 'number' && value[key])
|
|
147
|
+
walk(value[key], visit);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function loopPlan(module, fn, diagnostic) {
|
|
151
|
+
const f = binaryen.getFunctionInfo(fn);
|
|
152
|
+
if (f.results !== binaryen.none) {
|
|
153
|
+
diagnostic.reason = 'non-void entry requires a result merge';
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const parameters = binaryen.expandType(f.params);
|
|
157
|
+
if (parameters.some((type) => type !== binaryen.i32)) {
|
|
158
|
+
diagnostic.reason = 'non-i32 loop parameters';
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const root = info(f.body);
|
|
162
|
+
if (root.id !== binaryen.BlockId || root.children.length !== 2)
|
|
163
|
+
return;
|
|
164
|
+
const guard = info(root.children[0]);
|
|
165
|
+
const loop = info(root.children[1]);
|
|
166
|
+
if (guard.id !== binaryen.BreakId ||
|
|
167
|
+
guard.name !== root.name ||
|
|
168
|
+
guard.value ||
|
|
169
|
+
!guard.condition)
|
|
170
|
+
return;
|
|
171
|
+
if (loop.id !== binaryen.LoopId)
|
|
172
|
+
return;
|
|
173
|
+
const zero = info(guard.condition);
|
|
174
|
+
if (zero.id !== binaryen.UnaryId || zero.op !== binaryen.EqZInt32)
|
|
175
|
+
return;
|
|
176
|
+
const counter = info(zero.value);
|
|
177
|
+
if (counter.id !== binaryen.LocalGetId || counter.index >= parameters.length)
|
|
178
|
+
return;
|
|
179
|
+
const body = info(loop.body);
|
|
180
|
+
if (body.id !== binaryen.BlockId || body.children.length < 2)
|
|
181
|
+
return;
|
|
182
|
+
const last = info(body.children.at(-1));
|
|
183
|
+
if (last.id !== binaryen.BreakId || last.name !== loop.name || last.value || !last.condition)
|
|
184
|
+
return;
|
|
185
|
+
const decrement = info(last.condition);
|
|
186
|
+
if (decrement.id !== binaryen.LocalSetId || !decrement.isTee)
|
|
187
|
+
return;
|
|
188
|
+
if (decrement.index !== counter.index)
|
|
189
|
+
return;
|
|
190
|
+
const add = info(decrement.value);
|
|
191
|
+
if (add.id !== binaryen.BinaryId || add.op !== binaryen.AddInt32)
|
|
192
|
+
return;
|
|
193
|
+
const left = info(add.left), right = info(add.right);
|
|
194
|
+
if (left.id !== binaryen.LocalGetId || left.index !== counter.index)
|
|
195
|
+
return;
|
|
196
|
+
if (right.id !== binaryen.ConstId || right.value !== -1)
|
|
197
|
+
return;
|
|
198
|
+
const steps = [];
|
|
199
|
+
const updates = new Set();
|
|
200
|
+
let end = body.children.length - 1;
|
|
201
|
+
while (end > 0) {
|
|
202
|
+
const set = info(body.children[end - 1]);
|
|
203
|
+
if (set.id !== binaryen.LocalSetId || set.isTee || set.index === counter.index)
|
|
204
|
+
break;
|
|
205
|
+
if (set.index >= parameters.length)
|
|
206
|
+
break;
|
|
207
|
+
const update = info(set.value);
|
|
208
|
+
if (update.id !== binaryen.BinaryId || update.op !== binaryen.AddInt32)
|
|
209
|
+
break;
|
|
210
|
+
const source = info(update.left), delta = info(update.right);
|
|
211
|
+
if (source.id !== binaryen.LocalGetId || source.index !== set.index)
|
|
212
|
+
break;
|
|
213
|
+
if (delta.id !== binaryen.ConstId || updates.has(set.index))
|
|
214
|
+
break;
|
|
215
|
+
updates.add(set.index);
|
|
216
|
+
steps.push({ parameter: set.index, step: delta.value });
|
|
217
|
+
end--;
|
|
218
|
+
}
|
|
219
|
+
if (!steps.length || end === 0)
|
|
220
|
+
return;
|
|
221
|
+
const payload = body.children.slice(0, end);
|
|
222
|
+
const written = new Set();
|
|
223
|
+
let safe = true;
|
|
224
|
+
for (const expression of payload) {
|
|
225
|
+
walk(expression, (value) => {
|
|
226
|
+
if (value.id === binaryen.LocalSetId) {
|
|
227
|
+
written.add(value.index);
|
|
228
|
+
if (value.index === counter.index || updates.has(value.index)) {
|
|
229
|
+
diagnostic.reason = 'loop control modified inside the iteration';
|
|
230
|
+
safe = false;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (value.id === binaryen.LocalGetId && value.index === counter.index) {
|
|
234
|
+
diagnostic.reason = 'iteration reads the remaining count';
|
|
235
|
+
safe = false;
|
|
236
|
+
}
|
|
237
|
+
if ([binaryen.BreakId, binaryen.SwitchId, binaryen.ReturnId, binaryen.LoopId].includes(value.id) ||
|
|
238
|
+
(value.id === binaryen.CallId && value.isReturn)) {
|
|
239
|
+
diagnostic.reason = 'nested or escaping control flow';
|
|
240
|
+
safe = false;
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
if (!safe)
|
|
245
|
+
return;
|
|
246
|
+
function visit(expression, assigned) {
|
|
247
|
+
const value = info(expression);
|
|
248
|
+
const children = (...expressions) => expressions.every((child) => visit(child, assigned));
|
|
249
|
+
switch (value.id) {
|
|
250
|
+
case binaryen.LocalGetId:
|
|
251
|
+
if (written.has(value.index) && !assigned.has(value.index)) {
|
|
252
|
+
diagnostic.reason = 'loop-carried scalar state';
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
return true;
|
|
256
|
+
case binaryen.LocalSetId:
|
|
257
|
+
if (!visit(value.value, assigned))
|
|
258
|
+
return false;
|
|
259
|
+
assigned.add(value.index);
|
|
260
|
+
return true;
|
|
261
|
+
case binaryen.BlockId:
|
|
262
|
+
return children(...value.children);
|
|
263
|
+
case binaryen.IfId: {
|
|
264
|
+
if (!visit(value.condition, assigned))
|
|
265
|
+
return false;
|
|
266
|
+
const yes = new Set(assigned), no = new Set(assigned);
|
|
267
|
+
if (!visit(value.ifTrue, yes) || (value.ifFalse && !visit(value.ifFalse, no)))
|
|
268
|
+
return false;
|
|
269
|
+
for (const index of yes)
|
|
270
|
+
if (no.has(index))
|
|
271
|
+
assigned.add(index);
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
case binaryen.SelectId:
|
|
275
|
+
return children(value.ifTrue, value.ifFalse, value.condition);
|
|
276
|
+
case binaryen.CallId:
|
|
277
|
+
return children(...value.operands);
|
|
278
|
+
case binaryen.UnaryId:
|
|
279
|
+
case binaryen.DropId:
|
|
280
|
+
return children(value.value);
|
|
281
|
+
case binaryen.BinaryId:
|
|
282
|
+
return children(value.left, value.right);
|
|
283
|
+
case binaryen.LoadId:
|
|
284
|
+
return children(value.ptr);
|
|
285
|
+
case binaryen.StoreId:
|
|
286
|
+
return children(value.ptr, value.value);
|
|
287
|
+
case binaryen.MemoryCopyId:
|
|
288
|
+
return children(value.dest, value.source, value.size);
|
|
289
|
+
case binaryen.MemoryFillId:
|
|
290
|
+
return children(value.dest, value.value, value.size);
|
|
291
|
+
case binaryen.ConstId:
|
|
292
|
+
case binaryen.GlobalGetId:
|
|
293
|
+
case binaryen.NopId:
|
|
294
|
+
case binaryen.UnreachableId:
|
|
295
|
+
return true;
|
|
296
|
+
default:
|
|
297
|
+
diagnostic.reason = 'iteration analysis does not support this expression';
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const assigned = new Set();
|
|
302
|
+
return payload.every((expression) => visit(expression, assigned))
|
|
303
|
+
? { countParameter: counter.index, steps }
|
|
304
|
+
: undefined;
|
|
305
|
+
}
|
|
306
|
+
/** Prepares guarded parallel paths; unsupported features retain the original module. */
|
|
307
|
+
function prepareTracked(bytes, options = {}) {
|
|
308
|
+
const original = Uint8Array.from(bytes);
|
|
309
|
+
const native = new WebAssembly.Module(original);
|
|
310
|
+
if (options.parallel === 'off')
|
|
311
|
+
return { original, loops: {}, reasons: ['parallel preparation disabled'] };
|
|
312
|
+
const reasons = [];
|
|
313
|
+
const imports = WebAssembly.Module.imports(native);
|
|
314
|
+
if (imports.some((item) => item.kind !== 'memory'))
|
|
315
|
+
reasons.push('host or non-memory imports');
|
|
316
|
+
if (imports.some((item) => item.module === 'folio'))
|
|
317
|
+
reasons.push('reserved import namespace');
|
|
318
|
+
if (imports.filter((item) => item.kind === 'memory').length !== 1)
|
|
319
|
+
reasons.push('one imported memory required');
|
|
320
|
+
let cursor = 8;
|
|
321
|
+
const unsigned = () => {
|
|
322
|
+
let value = 0, shift = 0, byte;
|
|
323
|
+
do {
|
|
324
|
+
byte = original[cursor++];
|
|
325
|
+
value += (byte & 127) * 2 ** shift;
|
|
326
|
+
shift += 7;
|
|
327
|
+
} while (byte & 128);
|
|
328
|
+
return value;
|
|
329
|
+
};
|
|
330
|
+
while (cursor < original.length) {
|
|
331
|
+
const section = original[cursor++];
|
|
332
|
+
const size = unsigned();
|
|
333
|
+
const end = cursor + size;
|
|
334
|
+
if (section === 5 && unsigned() !== 0)
|
|
335
|
+
reasons.push('additional defined memory');
|
|
336
|
+
cursor = end;
|
|
337
|
+
}
|
|
338
|
+
if (reasons.length)
|
|
339
|
+
return { original, loops: {}, reasons };
|
|
340
|
+
let analysisModule;
|
|
341
|
+
const loops = {};
|
|
342
|
+
const loopReasons = {};
|
|
343
|
+
const nativePlans = {};
|
|
344
|
+
try {
|
|
345
|
+
const module = (analysisModule = binaryen.readBinary(original));
|
|
346
|
+
// Native validation already established the source instruction set. Binaryen
|
|
347
|
+
// does not infer every proposal flag from a binary's instruction bodies.
|
|
348
|
+
const compactImports = binaryen.Features
|
|
349
|
+
.CompactImports;
|
|
350
|
+
module.setFeatures(binaryen.Features.All & ~compactImports);
|
|
351
|
+
if (module.getStart())
|
|
352
|
+
reasons.push('start function');
|
|
353
|
+
const raw = module;
|
|
354
|
+
if (raw.getNumDataSegments())
|
|
355
|
+
reasons.push('data segments require initialization isolation');
|
|
356
|
+
const memory = module.hasMemory() ? module.getMemoryInfo() : undefined;
|
|
357
|
+
if (!memory?.shared || memory.is64)
|
|
358
|
+
reasons.push('shared wasm32 memory required');
|
|
359
|
+
if (memory?.shared)
|
|
360
|
+
module.setFeatures(module.getFeatures() | binaryen.Features.Atomics);
|
|
361
|
+
const allowed = new Set([
|
|
362
|
+
binaryen.BlockId,
|
|
363
|
+
binaryen.IfId,
|
|
364
|
+
binaryen.LoopId,
|
|
365
|
+
binaryen.BreakId,
|
|
366
|
+
binaryen.SwitchId,
|
|
367
|
+
binaryen.CallId,
|
|
368
|
+
binaryen.LocalGetId,
|
|
369
|
+
binaryen.LocalSetId,
|
|
370
|
+
binaryen.GlobalGetId,
|
|
371
|
+
binaryen.LoadId,
|
|
372
|
+
binaryen.StoreId,
|
|
373
|
+
binaryen.MemoryCopyId,
|
|
374
|
+
binaryen.MemoryFillId,
|
|
375
|
+
binaryen.ConstId,
|
|
376
|
+
binaryen.UnaryId,
|
|
377
|
+
binaryen.BinaryId,
|
|
378
|
+
binaryen.SelectId,
|
|
379
|
+
binaryen.DropId,
|
|
380
|
+
binaryen.ReturnId,
|
|
381
|
+
binaryen.NopId,
|
|
382
|
+
binaryen.UnreachableId
|
|
383
|
+
]);
|
|
384
|
+
const calls = new Map();
|
|
385
|
+
const exportedFunctions = new Map();
|
|
386
|
+
for (let index = 0; index < module.getNumExports(); index++) {
|
|
387
|
+
const exported = binaryen.getExportInfo(module.getExportByIndex(index));
|
|
388
|
+
if (exported.kind !== binaryen.ExternalFunction)
|
|
389
|
+
continue;
|
|
390
|
+
const names = exportedFunctions.get(exported.value) ?? [];
|
|
391
|
+
names.push(exported.name);
|
|
392
|
+
exportedFunctions.set(exported.value, names);
|
|
393
|
+
}
|
|
394
|
+
for (let index = 0; index < module.getNumFunctions(); index++) {
|
|
395
|
+
const fn = module.getFunctionByIndex(index);
|
|
396
|
+
const f = binaryen.getFunctionInfo(fn);
|
|
397
|
+
if ([...binaryen.expandType(f.params), ...binaryen.expandType(f.results)].some((type) => ![binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64].includes(type)))
|
|
398
|
+
reasons.push('reference or vector function signature');
|
|
399
|
+
if (!f.body)
|
|
400
|
+
continue;
|
|
401
|
+
const targets = new Set();
|
|
402
|
+
calls.set(f.name, targets);
|
|
403
|
+
walk(f.body, (value) => {
|
|
404
|
+
if (value.id === binaryen.CallId)
|
|
405
|
+
targets.add(value.target);
|
|
406
|
+
if (!allowed.has(value.id))
|
|
407
|
+
reasons.push(`unsupported expression ${value.id}`);
|
|
408
|
+
if (value.id === binaryen.GlobalGetId)
|
|
409
|
+
reasons.push('global state');
|
|
410
|
+
if (value.isAtomic)
|
|
411
|
+
reasons.push('atomic access');
|
|
412
|
+
if ([binaryen.LoadId, binaryen.StoreId].includes(value.id)) {
|
|
413
|
+
const type = value.id === binaryen.LoadId ? value.type : info(value.value).type;
|
|
414
|
+
if (![binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64].includes(type))
|
|
415
|
+
reasons.push('unsupported memory value type');
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
const diagnostic = { reason: 'loop shape not recognized' };
|
|
419
|
+
const plan = loopPlan(module, fn, diagnostic);
|
|
420
|
+
const names = exportedFunctions.get(f.name) ?? [];
|
|
421
|
+
const proved = names.length && plan ? nativePlan(module, fn) : undefined;
|
|
422
|
+
for (const name of names) {
|
|
423
|
+
if (plan) {
|
|
424
|
+
Object.defineProperty(loops, name, {
|
|
425
|
+
value: plan,
|
|
426
|
+
enumerable: true,
|
|
427
|
+
configurable: true,
|
|
428
|
+
writable: true
|
|
429
|
+
});
|
|
430
|
+
if (proved)
|
|
431
|
+
Object.defineProperty(nativePlans, name, {
|
|
432
|
+
value: proved,
|
|
433
|
+
enumerable: true,
|
|
434
|
+
configurable: true,
|
|
435
|
+
writable: true
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
else
|
|
439
|
+
Object.defineProperty(loopReasons, name, {
|
|
440
|
+
value: diagnostic.reason,
|
|
441
|
+
enumerable: true,
|
|
442
|
+
configurable: true,
|
|
443
|
+
writable: true
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
const visiting = new Set(), visited = new Set();
|
|
448
|
+
const recursive = (name) => {
|
|
449
|
+
if (visiting.has(name))
|
|
450
|
+
return true;
|
|
451
|
+
if (visited.has(name))
|
|
452
|
+
return false;
|
|
453
|
+
visiting.add(name);
|
|
454
|
+
if ([...(calls.get(name) ?? [])].some(recursive))
|
|
455
|
+
return true;
|
|
456
|
+
visiting.delete(name);
|
|
457
|
+
visited.add(name);
|
|
458
|
+
return false;
|
|
459
|
+
};
|
|
460
|
+
if ([...calls.keys()].some(recursive))
|
|
461
|
+
reasons.push('recursive call graph retains original owner stack');
|
|
462
|
+
if (reasons.length)
|
|
463
|
+
return { original, loops: {}, reasons: [...new Set(reasons)] };
|
|
464
|
+
const reserved = [
|
|
465
|
+
'__folio_load',
|
|
466
|
+
'__folio_store',
|
|
467
|
+
'__folio_exhausted',
|
|
468
|
+
'__folio_set_fuel',
|
|
469
|
+
'__folio_load64',
|
|
470
|
+
'__folio_store64',
|
|
471
|
+
'__folio_copy',
|
|
472
|
+
'__folio_fill'
|
|
473
|
+
];
|
|
474
|
+
if (reserved.some((name) => module.getFunction(name) || module.getExport(name)) ||
|
|
475
|
+
module.getGlobal('__folio_fuel')) {
|
|
476
|
+
return { original, loops: {}, reasons: ['reserved function name'] };
|
|
477
|
+
}
|
|
478
|
+
module.addGlobal('__folio_fuel', binaryen.i32, true, module.i32.const(0));
|
|
479
|
+
const lowered = module;
|
|
480
|
+
function tick() {
|
|
481
|
+
const module = lowered;
|
|
482
|
+
return module.block(null, [
|
|
483
|
+
module.global.set('__folio_fuel', module.i32.sub(module.global.get('__folio_fuel', binaryen.i32), module.i32.const(1))),
|
|
484
|
+
module.if(module.i32.le_s(module.global.get('__folio_fuel', binaryen.i32), module.i32.const(0)), module.call(reserved[2], [], binaryen.none))
|
|
485
|
+
]);
|
|
486
|
+
}
|
|
487
|
+
function lower(expression) {
|
|
488
|
+
const module = lowered;
|
|
489
|
+
const v = info(expression);
|
|
490
|
+
switch (v.id) {
|
|
491
|
+
case binaryen.BlockId:
|
|
492
|
+
return module.block(v.name, v.children.map(lower), v.type);
|
|
493
|
+
case binaryen.IfId:
|
|
494
|
+
return module.if(lower(v.condition), lower(v.ifTrue), v.ifFalse ? lower(v.ifFalse) : undefined);
|
|
495
|
+
case binaryen.LoopId:
|
|
496
|
+
return module.loop(v.name, module.block(null, [tick(), lower(v.body)], v.type));
|
|
497
|
+
case binaryen.BreakId:
|
|
498
|
+
return module.br(v.name, v.condition ? lower(v.condition) : undefined, v.value ? lower(v.value) : undefined);
|
|
499
|
+
case binaryen.SwitchId:
|
|
500
|
+
return module.switch(v.names, v.defaultName, lower(v.condition), v.value ? lower(v.value) : undefined);
|
|
501
|
+
case binaryen.CallId:
|
|
502
|
+
return v.isReturn
|
|
503
|
+
? module.return_call(v.target, v.operands.map(lower), v.type)
|
|
504
|
+
: module.call(v.target, v.operands.map(lower), v.type);
|
|
505
|
+
case binaryen.LocalSetId:
|
|
506
|
+
return v.isTee
|
|
507
|
+
? module.local.tee(v.index, lower(v.value), v.type)
|
|
508
|
+
: module.local.set(v.index, lower(v.value));
|
|
509
|
+
case binaryen.LoadId: {
|
|
510
|
+
const wide = v.type === binaryen.i64 || v.type === binaryen.f64;
|
|
511
|
+
const loaded = module.call(reserved[wide ? 4 : 0], [
|
|
512
|
+
lower(v.ptr),
|
|
513
|
+
module.i32.const(v.offset),
|
|
514
|
+
module.i32.const(v.bytes),
|
|
515
|
+
module.i32.const(Number(v.isSigned))
|
|
516
|
+
], wide ? binaryen.i64 : binaryen.i32);
|
|
517
|
+
return v.type === binaryen.f32
|
|
518
|
+
? module.f32.reinterpret(loaded)
|
|
519
|
+
: v.type === binaryen.f64
|
|
520
|
+
? module.f64.reinterpret(loaded)
|
|
521
|
+
: loaded;
|
|
522
|
+
}
|
|
523
|
+
case binaryen.StoreId: {
|
|
524
|
+
const type = info(v.value).type;
|
|
525
|
+
const wide = type === binaryen.i64 || type === binaryen.f64;
|
|
526
|
+
const value = lower(v.value);
|
|
527
|
+
return module.call(reserved[wide ? 5 : 1], [
|
|
528
|
+
lower(v.ptr),
|
|
529
|
+
type === binaryen.f32
|
|
530
|
+
? module.i32.reinterpret(value)
|
|
531
|
+
: type === binaryen.f64
|
|
532
|
+
? module.i64.reinterpret(value)
|
|
533
|
+
: value,
|
|
534
|
+
module.i32.const(v.offset),
|
|
535
|
+
module.i32.const(v.bytes)
|
|
536
|
+
], binaryen.none);
|
|
537
|
+
}
|
|
538
|
+
case binaryen.MemoryCopyId:
|
|
539
|
+
return module.call(reserved[6], [lower(v.dest), lower(v.source), lower(v.size)], binaryen.none);
|
|
540
|
+
case binaryen.MemoryFillId:
|
|
541
|
+
return module.call(reserved[7], [lower(v.dest), lower(v.value), lower(v.size)], binaryen.none);
|
|
542
|
+
case binaryen.UnaryId:
|
|
543
|
+
return binaryen._BinaryenUnary(module.ptr, v.op, lower(v.value));
|
|
544
|
+
case binaryen.BinaryId:
|
|
545
|
+
return binaryen._BinaryenBinary(module.ptr, v.op, lower(v.left), lower(v.right));
|
|
546
|
+
case binaryen.SelectId:
|
|
547
|
+
return module.select(lower(v.condition), lower(v.ifTrue), lower(v.ifFalse));
|
|
548
|
+
case binaryen.DropId:
|
|
549
|
+
return module.drop(lower(v.value));
|
|
550
|
+
case binaryen.ReturnId:
|
|
551
|
+
return module.return(v.value ? lower(v.value) : undefined);
|
|
552
|
+
default:
|
|
553
|
+
return expression;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const count = module.getNumFunctions();
|
|
557
|
+
for (let index = 0; index < count; index++) {
|
|
558
|
+
const fn = module.getFunctionByIndex(index);
|
|
559
|
+
const body = binaryen.getFunctionInfo(fn).body;
|
|
560
|
+
if (body)
|
|
561
|
+
binaryen._BinaryenFunctionSetBody(fn, module.block(null, [tick(), lower(body)], info(body).type));
|
|
562
|
+
}
|
|
563
|
+
const fourI32 = binaryen.createType(Array(4).fill(binaryen.i32));
|
|
564
|
+
module.addFunctionImport(reserved[0], 'folio', 'load', fourI32, binaryen.i32);
|
|
565
|
+
module.addFunctionImport(reserved[1], 'folio', 'store', fourI32, binaryen.none);
|
|
566
|
+
module.addFunctionImport(reserved[4], 'folio', 'load64', fourI32, binaryen.i64);
|
|
567
|
+
module.addFunctionImport(reserved[5], 'folio', 'store64', binaryen.createType([binaryen.i32, binaryen.i64, binaryen.i32, binaryen.i32]), binaryen.none);
|
|
568
|
+
const threeI32 = binaryen.createType(Array(3).fill(binaryen.i32));
|
|
569
|
+
module.addFunctionImport(reserved[6], 'folio', 'copy', threeI32, binaryen.none);
|
|
570
|
+
module.addFunctionImport(reserved[7], 'folio', 'fill', threeI32, binaryen.none);
|
|
571
|
+
module.addFunctionImport(reserved[2], 'folio', 'exhausted', binaryen.none, binaryen.none);
|
|
572
|
+
module.addFunction(reserved[3], binaryen.i32, binaryen.none, [], module.global.set('__folio_fuel', module.local.get(0, binaryen.i32)));
|
|
573
|
+
module.addFunctionExport(reserved[3], reserved[3]);
|
|
574
|
+
if (!module.validate())
|
|
575
|
+
throw new Error('invalid transactional lowering');
|
|
576
|
+
return {
|
|
577
|
+
original,
|
|
578
|
+
transactional: module.emitBinary(),
|
|
579
|
+
loops,
|
|
580
|
+
loopReasons,
|
|
581
|
+
native: nativePlans,
|
|
582
|
+
reasons: []
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
return {
|
|
587
|
+
original,
|
|
588
|
+
loops: {},
|
|
589
|
+
reasons: [
|
|
590
|
+
`parallel preparation unavailable: ${error instanceof Error ? error.message : String(error)}`
|
|
591
|
+
]
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
finally {
|
|
595
|
+
analysisModule?.dispose();
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Keeps the original native module and adds independently validated optimizations. A module
|
|
600
|
+
* with no region above `minimumRegionWork` gets no control plan and runs untouched.
|
|
601
|
+
*/
|
|
602
|
+
export function prepare(bytes, options = {}) {
|
|
603
|
+
admission(options);
|
|
604
|
+
const prepared = prepareTracked(bytes, options);
|
|
605
|
+
if (options.parallel !== 'off') {
|
|
606
|
+
try {
|
|
607
|
+
prepared.control = extract(prepared.original, prepareTracked, {
|
|
608
|
+
minimumRegionWork: options.minimumRegionWork,
|
|
609
|
+
assumedTripCount: options.assumedTripCount,
|
|
610
|
+
refused: (reason) => (prepared.controlReasons ??= []).push(reason)
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
catch (error) {
|
|
614
|
+
prepared.reasons.push(`control-flow extraction unavailable: ${error instanceof Error ? error.message : String(error)}`);
|
|
615
|
+
}
|
|
616
|
+
prepared.stackRoute = stackRoute(prepared.original, options);
|
|
617
|
+
prepared.iterationRoute = iterationRoute(prepared.original, prepared.stackRoute);
|
|
618
|
+
}
|
|
619
|
+
return prepared;
|
|
620
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { PreparedContext } from './compiler.ts';
|
|
2
|
+
/** A changed memory or table size requires a newly instantiated context. */
|
|
3
|
+
export declare class ContextResetError extends Error {
|
|
4
|
+
/** Which binding changed size. */
|
|
5
|
+
readonly kind: 'memory-size' | 'table-size';
|
|
6
|
+
constructor(kind: 'memory-size' | 'table-size');
|
|
7
|
+
}
|
|
8
|
+
/** Memory traffic and state restored by a checkpoint operation. */
|
|
9
|
+
export interface ContextResetReport {
|
|
10
|
+
/** Bytes compared; zero for a full restore. */
|
|
11
|
+
checkedBytes: number;
|
|
12
|
+
/** Bytes written back to memory. */
|
|
13
|
+
copiedBytes: number;
|
|
14
|
+
/** 64 KiB pages written back. */
|
|
15
|
+
changedPages: number;
|
|
16
|
+
/** Globals whose value was restored. */
|
|
17
|
+
globals: number;
|
|
18
|
+
/** Table slots whose reference was restored. */
|
|
19
|
+
tableSlots: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Captures private Wasm state after initialization. `prepareContext` exposes hidden bindings.
|
|
23
|
+
* Each restore checks current bytes, so different inputs may dirty different pages. Callers own
|
|
24
|
+
* exclusive access and reset host resources and objects behind externref values separately.
|
|
25
|
+
* Memory/table growth requires recreation because Wasm cannot shrink those bindings.
|
|
26
|
+
* @since 1.0.1
|
|
27
|
+
*/
|
|
28
|
+
export declare class InstanceCheckpoint {
|
|
29
|
+
#private;
|
|
30
|
+
constructor(instance: WebAssembly.Instance, plan: PreparedContext);
|
|
31
|
+
/** Restores all mutable bindings. `full` skips page comparison and copies every memory byte. */
|
|
32
|
+
restore(strategy?: 'changed' | 'full'): ContextResetReport;
|
|
33
|
+
}
|