@gmitch215/folio 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -19
- package/dist/bake.d.ts +8 -3
- package/dist/bake.js +5 -2
- package/dist/compiler.d.ts +37 -1
- package/dist/compiler.js +116 -1
- package/dist/context.d.ts +33 -0
- package/dist/context.js +93 -0
- package/dist/coordinator.d.ts +1 -1
- package/dist/coordinator.js +4 -2
- package/dist/extract.d.ts +95 -1
- package/dist/extract.js +883 -242
- package/dist/frames.d.ts +15 -1
- package/dist/frames.js +49 -1
- 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 +6 -0
- package/dist/managed.js +33 -10
- package/dist/node.d.ts +19 -5
- package/dist/node.js +344 -22
- package/dist/tasks.js +16 -3
- package/package.json +6 -2
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** Why the rest of a loop ran serially after the pooled path was tried or refused. */
|
|
2
|
+
export type IterationStop = 'no-admission' | 'log-exhausted' | 'frame-carried dependence' | 'dependency';
|
|
3
|
+
/** What the admission decision saw and chose for one owner call's loop. */
|
|
4
|
+
export interface IterationAdmission {
|
|
5
|
+
/** Time of iteration 0 on the owner thread, on a plain instance and the real frame. */
|
|
6
|
+
plainIterationMs: number;
|
|
7
|
+
/** Serial time of the iterations after iteration 0, from `plainIterationMs`. */
|
|
8
|
+
remainingSerialMs: number;
|
|
9
|
+
/** The least remaining serial time worth dispatching: `fixedMs * margin`. */
|
|
10
|
+
floorMs: number;
|
|
11
|
+
/** The decision before the first dispatch. A later stop is `IterationReport.stopped`. */
|
|
12
|
+
admitted: boolean;
|
|
13
|
+
/** Wall of the last batch, dispatch to the end of its replays. */
|
|
14
|
+
batchWallMs?: number;
|
|
15
|
+
/** The same iterations at `plainIterationMs` each. */
|
|
16
|
+
batchSerialMs?: number;
|
|
17
|
+
}
|
|
18
|
+
/** The constants of the decision. A re-calibration changes these and nothing else. */
|
|
19
|
+
export interface IterationAdmissionConstants {
|
|
20
|
+
/** Wall of the pooled path that does not shrink with the loop: dispatch, join, validation. */
|
|
21
|
+
fixedMs: number;
|
|
22
|
+
/** The pooled path has to beat the serial one by this factor, before and after each batch. */
|
|
23
|
+
margin: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Fitted on a Mac sweep of `scripts/research/iteration-admission.ts` and checked on the rig at widths
|
|
27
|
+
* 8 and 4; a re-calibration updates only these two numbers.
|
|
28
|
+
*
|
|
29
|
+
* `fixedMs` 2 is the smallest value at which no cell of the Mac sweep (18 cells, 4 KiB to 4 MiB
|
|
30
|
+
* by 8 to 128 iterations, width 8) dispatched and lost. The pooled wall minus the batch time
|
|
31
|
+
* measured 0.1 to 2.9 ms there with the input copy left out of the timing; the prototype's rows
|
|
32
|
+
* bracket 3 to 8 ms but include that copy. The loop is not worth dispatching when the serial time
|
|
33
|
+
* of its remaining iterations is below `fixedMs * margin`.
|
|
34
|
+
*
|
|
35
|
+
* `margin` 1.25 is the speedup a batch has to show over the serial time of its iterations for
|
|
36
|
+
* the loop to keep dispatching. A batch that misses it twice in a row ends the dispatch, and so
|
|
37
|
+
* does one batch whose wall passes `batchCollapse` times that serial time.
|
|
38
|
+
*/
|
|
39
|
+
export declare const iterationAdmissionConstants: IterationAdmissionConstants;
|
|
40
|
+
export interface AdmitInput {
|
|
41
|
+
plainIterationMs: number;
|
|
42
|
+
trip: number;
|
|
43
|
+
width: number;
|
|
44
|
+
constants?: IterationAdmissionConstants;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Decides before the first dispatch from the measured serial time of iteration 0, which has
|
|
48
|
+
* already run. Admits when at least two iterations are left for at least two workers and their
|
|
49
|
+
* serial time exceeds `fixedMs * margin`. Whether dispatch pays is then checked per batch.
|
|
50
|
+
*/
|
|
51
|
+
export declare function admitIteration({ plainIterationMs: t0, trip, width, constants }: AdmitInput): IterationAdmission;
|
|
52
|
+
/** True when a batch did not beat the serial time of its iterations by the margin. */
|
|
53
|
+
export declare function batchLoses(batchWallMs: number, batchSerialMs: number, constants?: IterationAdmissionConstants): boolean;
|
|
54
|
+
/** Batch wall over serial time past which one batch is a verdict, with no second batch to confirm. */
|
|
55
|
+
export declare const batchCollapse = 1.5;
|
|
56
|
+
/** True when a batch took clearly longer than the serial time of its iterations. */
|
|
57
|
+
export declare function batchCollapses(batchWallMs: number, batchSerialMs: number): boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Test and sweep seam, module state and not an option. `scale` multiplies the measured time of
|
|
60
|
+
* iteration 0 before the first decision and `batchScale` the wall of each batch before the batch
|
|
61
|
+
* rule; `force` admits any loop with an iteration left after iteration 0 and never stops on the
|
|
62
|
+
* batch rule. The structural stops (`log-exhausted`, `frame-carried dependence`, `dependency`)
|
|
63
|
+
* are not affected.
|
|
64
|
+
* @internal
|
|
65
|
+
*/
|
|
66
|
+
export declare const admissionSeam: {
|
|
67
|
+
scale: number;
|
|
68
|
+
batchScale: number;
|
|
69
|
+
force: boolean;
|
|
70
|
+
};
|
|
71
|
+
/** `admitIteration` through the seam; what the host function calls. */
|
|
72
|
+
export declare function decideAdmission(plainIterationMs: number, trip: number, width: number): IterationAdmission;
|
|
73
|
+
/** `batchLoses` through the seam; what the host function passes the pool. */
|
|
74
|
+
export declare function decideBatch(batchWallMs: number, batchSerialMs: number): boolean;
|
|
75
|
+
/** `batchCollapses` through the seam; what the host function passes the pool. */
|
|
76
|
+
export declare function decideCollapse(batchWallMs: number, batchSerialMs: number): boolean;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fitted on a Mac sweep of `scripts/research/iteration-admission.ts` and checked on the rig at widths
|
|
3
|
+
* 8 and 4; a re-calibration updates only these two numbers.
|
|
4
|
+
*
|
|
5
|
+
* `fixedMs` 2 is the smallest value at which no cell of the Mac sweep (18 cells, 4 KiB to 4 MiB
|
|
6
|
+
* by 8 to 128 iterations, width 8) dispatched and lost. The pooled wall minus the batch time
|
|
7
|
+
* measured 0.1 to 2.9 ms there with the input copy left out of the timing; the prototype's rows
|
|
8
|
+
* bracket 3 to 8 ms but include that copy. The loop is not worth dispatching when the serial time
|
|
9
|
+
* of its remaining iterations is below `fixedMs * margin`.
|
|
10
|
+
*
|
|
11
|
+
* `margin` 1.25 is the speedup a batch has to show over the serial time of its iterations for
|
|
12
|
+
* the loop to keep dispatching. A batch that misses it twice in a row ends the dispatch, and so
|
|
13
|
+
* does one batch whose wall passes `batchCollapse` times that serial time.
|
|
14
|
+
*/
|
|
15
|
+
export const iterationAdmissionConstants = {
|
|
16
|
+
fixedMs: 2,
|
|
17
|
+
margin: 1.25
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Decides before the first dispatch from the measured serial time of iteration 0, which has
|
|
21
|
+
* already run. Admits when at least two iterations are left for at least two workers and their
|
|
22
|
+
* serial time exceeds `fixedMs * margin`. Whether dispatch pays is then checked per batch.
|
|
23
|
+
*/
|
|
24
|
+
export function admitIteration({ plainIterationMs: t0, trip, width, constants = iterationAdmissionConstants }) {
|
|
25
|
+
const remaining = trip - 1;
|
|
26
|
+
const remainingSerialMs = remaining * t0;
|
|
27
|
+
const floorMs = constants.fixedMs * constants.margin;
|
|
28
|
+
const admitted = Number.isFinite(t0) && remaining >= 2 && width >= 2 && remainingSerialMs > floorMs;
|
|
29
|
+
return { plainIterationMs: t0, remainingSerialMs, floorMs, admitted };
|
|
30
|
+
}
|
|
31
|
+
/** True when a batch did not beat the serial time of its iterations by the margin. */
|
|
32
|
+
export function batchLoses(batchWallMs, batchSerialMs, constants = iterationAdmissionConstants) {
|
|
33
|
+
return batchWallMs * constants.margin > batchSerialMs;
|
|
34
|
+
}
|
|
35
|
+
/** Batch wall over serial time past which one batch is a verdict, with no second batch to confirm. */
|
|
36
|
+
export const batchCollapse = 1.5;
|
|
37
|
+
/** True when a batch took clearly longer than the serial time of its iterations. */
|
|
38
|
+
export function batchCollapses(batchWallMs, batchSerialMs) {
|
|
39
|
+
return batchWallMs > batchSerialMs * batchCollapse;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Test and sweep seam, module state and not an option. `scale` multiplies the measured time of
|
|
43
|
+
* iteration 0 before the first decision and `batchScale` the wall of each batch before the batch
|
|
44
|
+
* rule; `force` admits any loop with an iteration left after iteration 0 and never stops on the
|
|
45
|
+
* batch rule. The structural stops (`log-exhausted`, `frame-carried dependence`, `dependency`)
|
|
46
|
+
* are not affected.
|
|
47
|
+
* @internal
|
|
48
|
+
*/
|
|
49
|
+
export const admissionSeam = { scale: 1, batchScale: 1, force: false };
|
|
50
|
+
/** `admitIteration` through the seam; what the host function calls. */
|
|
51
|
+
export function decideAdmission(plainIterationMs, trip, width) {
|
|
52
|
+
const decision = admitIteration({
|
|
53
|
+
plainIterationMs: plainIterationMs * admissionSeam.scale,
|
|
54
|
+
trip,
|
|
55
|
+
width
|
|
56
|
+
});
|
|
57
|
+
if (admissionSeam.force && trip >= 2 && width >= 2)
|
|
58
|
+
decision.admitted = true;
|
|
59
|
+
return decision;
|
|
60
|
+
}
|
|
61
|
+
/** `batchLoses` through the seam; what the host function passes the pool. */
|
|
62
|
+
export function decideBatch(batchWallMs, batchSerialMs) {
|
|
63
|
+
if (admissionSeam.force)
|
|
64
|
+
return false;
|
|
65
|
+
return batchLoses(batchWallMs * admissionSeam.batchScale, batchSerialMs);
|
|
66
|
+
}
|
|
67
|
+
/** `batchCollapses` through the seam; what the host function passes the pool. */
|
|
68
|
+
export function decideCollapse(batchWallMs, batchSerialMs) {
|
|
69
|
+
if (admissionSeam.force)
|
|
70
|
+
return false;
|
|
71
|
+
return batchCollapses(batchWallMs * admissionSeam.batchScale, batchSerialMs);
|
|
72
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { IterationLocal } from './extract.ts';
|
|
2
|
+
/** Granule sizes of the inline lowering the iteration executor runs. */
|
|
3
|
+
export declare const iterationGranules: {
|
|
4
|
+
readonly read: 64;
|
|
5
|
+
readonly write: 32;
|
|
6
|
+
};
|
|
7
|
+
/** Bytes of one undo entry: granule address, stamp, then the prior bytes of the granule. */
|
|
8
|
+
export declare const iterationEntryBytes: number;
|
|
9
|
+
/** Sizes of the per-batch arena. Every field has a default. */
|
|
10
|
+
export interface IterationArenaOptions {
|
|
11
|
+
/** Iterations in flight at once, one slot, bitmap pair and undo log each. Default 32. */
|
|
12
|
+
batch?: number;
|
|
13
|
+
/** Undo entries one iteration may log, the budget in write granules. Default 2048. */
|
|
14
|
+
logCapacity?: number;
|
|
15
|
+
/** Bytes of one private stack slot, a multiple of 64. Default 32768. */
|
|
16
|
+
slotBytes?: number;
|
|
17
|
+
/** Size of the owner frame whose reads the executor tracks, for the per-slot shadow. Default 0. */
|
|
18
|
+
frameBytes?: number;
|
|
19
|
+
}
|
|
20
|
+
/** Absolute addresses of the arena parts. Slot 0 sits above one unused guard slot. */
|
|
21
|
+
export interface IterationArena {
|
|
22
|
+
base: number;
|
|
23
|
+
bytes: number;
|
|
24
|
+
memoryBytes: number;
|
|
25
|
+
batch: number;
|
|
26
|
+
logCapacity: number;
|
|
27
|
+
slotBytes: number;
|
|
28
|
+
slots: number;
|
|
29
|
+
stamp: number;
|
|
30
|
+
logs: number;
|
|
31
|
+
logBytes: number;
|
|
32
|
+
rmaps: number;
|
|
33
|
+
rsize: number;
|
|
34
|
+
wmaps: number;
|
|
35
|
+
wsize: number;
|
|
36
|
+
/** Start of the frame shadows, one per slot, after the write bitmaps. */
|
|
37
|
+
frameShadow: number;
|
|
38
|
+
/** Bytes of one slot's frame shadow; 0 without a tracked frame. */
|
|
39
|
+
frameSlotBytes: number;
|
|
40
|
+
/** The tracked frame size. */
|
|
41
|
+
frameBytes: number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Shadow of one tracked frame: `4 * ceil(size / 32)` bytes of written bits, one per frame byte
|
|
45
|
+
* (the bits of frame granule `g`, 32 bytes, are the i32 at `4 * g`), 4 pad bytes, the exposed bits
|
|
46
|
+
* in the same layout, and 4 pad bytes.
|
|
47
|
+
*/
|
|
48
|
+
export declare function iterationFrameShadow(frameBytes: number): {
|
|
49
|
+
exposed: number;
|
|
50
|
+
bytes: number;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Lays out slots, the stamp word, undo logs and bitmaps from `base`. The bitmaps cover the whole
|
|
54
|
+
* memory, arena included, so `bytes` depends on `memoryBytes` and not on `base`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function iterationArena(base: number, memoryBytes: number, options?: IterationArenaOptions): IterationArena;
|
|
57
|
+
/** Bytes the caller must keep free for a pool over a memory of `memoryBytes`. */
|
|
58
|
+
export declare const iterationArenaBytes: (memoryBytes: number, options?: IterationArenaOptions) => number;
|
|
59
|
+
/**
|
|
60
|
+
* Smallest memory of whole pages that holds the arena above `startBytes`. The bitmaps cover the
|
|
61
|
+
* whole memory, so the size is a fixed point: it grows until the arena it needs fits. Undefined
|
|
62
|
+
* when the result would pass 65,536 pages.
|
|
63
|
+
*/
|
|
64
|
+
export declare function iterationFit(startBytes: number, options?: IterationArenaOptions): {
|
|
65
|
+
base: number;
|
|
66
|
+
pages: number;
|
|
67
|
+
bytes: number;
|
|
68
|
+
memoryBytes: number;
|
|
69
|
+
} | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Arguments of `iterate` for iteration `k`. A strided local is `entry + k * stride` modulo 2^32, or
|
|
72
|
+
* `entry + k * stride * entry[strideLocal]` when its step is held in a local, an invariant local
|
|
73
|
+
* keeps its entry value, and the frame local takes `frame`.
|
|
74
|
+
*/
|
|
75
|
+
export declare function iterationArguments(locals: readonly Pick<IterationLocal, 'local' | 'kind' | 'argument' | 'stride' | 'strideLocal'>[], entry: Readonly<Record<number, number | bigint>>, k: number, frame: number): (number | bigint)[];
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** Granule sizes of the inline lowering the iteration executor runs. */
|
|
2
|
+
export const iterationGranules = { read: 64, write: 32 };
|
|
3
|
+
/** Bytes of one undo entry: granule address, stamp, then the prior bytes of the granule. */
|
|
4
|
+
export const iterationEntryBytes = 8 + iterationGranules.write;
|
|
5
|
+
const align = (value, to) => Math.ceil(value / to) * to;
|
|
6
|
+
/**
|
|
7
|
+
* Shadow of one tracked frame: `4 * ceil(size / 32)` bytes of written bits, one per frame byte
|
|
8
|
+
* (the bits of frame granule `g`, 32 bytes, are the i32 at `4 * g`), 4 pad bytes, the exposed bits
|
|
9
|
+
* in the same layout, and 4 pad bytes.
|
|
10
|
+
*/
|
|
11
|
+
export function iterationFrameShadow(frameBytes) {
|
|
12
|
+
if (!frameBytes)
|
|
13
|
+
return { exposed: 0, bytes: 0 };
|
|
14
|
+
const granules = Math.ceil(frameBytes / 32);
|
|
15
|
+
const exposed = 4 * granules + 4;
|
|
16
|
+
return { exposed, bytes: align(exposed + 4 * granules + 4, 64) };
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Lays out slots, the stamp word, undo logs and bitmaps from `base`. The bitmaps cover the whole
|
|
20
|
+
* memory, arena included, so `bytes` depends on `memoryBytes` and not on `base`.
|
|
21
|
+
*/
|
|
22
|
+
export function iterationArena(base, memoryBytes, options = {}) {
|
|
23
|
+
const batch = options.batch ?? 32;
|
|
24
|
+
const logCapacity = options.logCapacity ?? 2048;
|
|
25
|
+
const slotBytes = options.slotBytes ?? 32768;
|
|
26
|
+
const frameBytes = options.frameBytes ?? 0;
|
|
27
|
+
if (!Number.isSafeInteger(frameBytes) || frameBytes < 0)
|
|
28
|
+
throw new RangeError('invalid frame');
|
|
29
|
+
if (!Number.isSafeInteger(base) || base < 0 || base % 64)
|
|
30
|
+
throw new RangeError('invalid base');
|
|
31
|
+
if (!Number.isSafeInteger(memoryBytes) || memoryBytes <= 0)
|
|
32
|
+
throw new RangeError('invalid memory size');
|
|
33
|
+
if (!Number.isSafeInteger(batch) || batch < 1 || batch > 1024)
|
|
34
|
+
throw new RangeError('invalid batch');
|
|
35
|
+
if (!Number.isSafeInteger(logCapacity) || logCapacity < 1)
|
|
36
|
+
throw new RangeError('invalid log capacity');
|
|
37
|
+
if (!Number.isSafeInteger(slotBytes) || slotBytes < 64 || slotBytes % 64)
|
|
38
|
+
throw new RangeError('invalid slot size');
|
|
39
|
+
const slots = base + slotBytes;
|
|
40
|
+
const stamp = slots + batch * slotBytes;
|
|
41
|
+
const logs = stamp + 64;
|
|
42
|
+
const logBytes = align(logCapacity * iterationEntryBytes, 64);
|
|
43
|
+
const rmaps = logs + batch * logBytes;
|
|
44
|
+
const rsize = align(Math.ceil(memoryBytes / (iterationGranules.read * 8)), 64);
|
|
45
|
+
const wmaps = rmaps + batch * rsize;
|
|
46
|
+
const wsize = align(Math.ceil(memoryBytes / (iterationGranules.write * 8)), 64);
|
|
47
|
+
const frameShadow = wmaps + batch * wsize;
|
|
48
|
+
const frameSlotBytes = iterationFrameShadow(frameBytes).bytes;
|
|
49
|
+
const end = frameShadow + batch * frameSlotBytes;
|
|
50
|
+
return {
|
|
51
|
+
base,
|
|
52
|
+
bytes: end - base,
|
|
53
|
+
memoryBytes,
|
|
54
|
+
batch,
|
|
55
|
+
logCapacity,
|
|
56
|
+
slotBytes,
|
|
57
|
+
slots,
|
|
58
|
+
stamp,
|
|
59
|
+
logs,
|
|
60
|
+
logBytes,
|
|
61
|
+
rmaps,
|
|
62
|
+
rsize,
|
|
63
|
+
wmaps,
|
|
64
|
+
wsize,
|
|
65
|
+
frameShadow,
|
|
66
|
+
frameSlotBytes,
|
|
67
|
+
frameBytes
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** Bytes the caller must keep free for a pool over a memory of `memoryBytes`. */
|
|
71
|
+
export const iterationArenaBytes = (memoryBytes, options = {}) => iterationArena(0, memoryBytes, options).bytes;
|
|
72
|
+
const PAGE = 65536;
|
|
73
|
+
/**
|
|
74
|
+
* Smallest memory of whole pages that holds the arena above `startBytes`. The bitmaps cover the
|
|
75
|
+
* whole memory, so the size is a fixed point: it grows until the arena it needs fits. Undefined
|
|
76
|
+
* when the result would pass 65,536 pages.
|
|
77
|
+
*/
|
|
78
|
+
export function iterationFit(startBytes, options = {}) {
|
|
79
|
+
const base = align(startBytes, 64);
|
|
80
|
+
let pages = Math.ceil((base + PAGE) / PAGE);
|
|
81
|
+
for (;;) {
|
|
82
|
+
if (pages > PAGE)
|
|
83
|
+
return;
|
|
84
|
+
const bytes = iterationArenaBytes(pages * PAGE, options);
|
|
85
|
+
if (base + bytes <= pages * PAGE)
|
|
86
|
+
return { base, pages, bytes, memoryBytes: pages * PAGE };
|
|
87
|
+
pages = Math.ceil((base + bytes) / PAGE);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Arguments of `iterate` for iteration `k`. A strided local is `entry + k * stride` modulo 2^32, or
|
|
92
|
+
* `entry + k * stride * entry[strideLocal]` when its step is held in a local, an invariant local
|
|
93
|
+
* keeps its entry value, and the frame local takes `frame`.
|
|
94
|
+
*/
|
|
95
|
+
export function iterationArguments(locals, entry, k, frame) {
|
|
96
|
+
const values = [];
|
|
97
|
+
for (const item of locals) {
|
|
98
|
+
if (item.argument === undefined)
|
|
99
|
+
continue;
|
|
100
|
+
if (item.kind === 'frame') {
|
|
101
|
+
values[item.argument] = frame;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const from = entry[item.local];
|
|
105
|
+
if (from === undefined)
|
|
106
|
+
throw new RangeError(`no loop-entry value for local ${item.local}`);
|
|
107
|
+
if (item.strideLocal !== undefined) {
|
|
108
|
+
const step = entry[item.strideLocal];
|
|
109
|
+
if (step === undefined)
|
|
110
|
+
throw new RangeError(`no loop-entry value for local ${item.strideLocal}`);
|
|
111
|
+
const advance = Math.imul(k, Number(step));
|
|
112
|
+
values[item.argument] = (Number(from) + (item.stride < 0 ? -advance : advance)) | 0;
|
|
113
|
+
}
|
|
114
|
+
else
|
|
115
|
+
values[item.argument] = item.stride ? (Number(from) + k * item.stride) | 0 : from;
|
|
116
|
+
}
|
|
117
|
+
return values;
|
|
118
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { IterationRoute } from './extract.ts';
|
|
2
|
+
/** Why the iteration route is not used, in `ExecutionReport.reason`. */
|
|
3
|
+
export type IterationReason = 'no-arena' | 'memory-size-observed' | 'import-order' | 'workers-unavailable' | 'trip-zero' | 'no-admission' | 'log-exhausted' | 'frame-carried dependence';
|
|
4
|
+
/** The owner module with its loop handed to `iterate`, and what the host needs to bind it. */
|
|
5
|
+
export interface IterationOwner {
|
|
6
|
+
module: Uint8Array;
|
|
7
|
+
/** import module of the host function; the function is `iterate` */
|
|
8
|
+
namespace: string;
|
|
9
|
+
/** the owner local passed as each argument of `iterate`, in order */
|
|
10
|
+
locals: number[];
|
|
11
|
+
/** export of the owner's stack global, when the module has one */
|
|
12
|
+
stackExport?: string;
|
|
13
|
+
/** the memory import, as declared by the original module */
|
|
14
|
+
memory: {
|
|
15
|
+
module: string;
|
|
16
|
+
name: string;
|
|
17
|
+
initial: number;
|
|
18
|
+
maximum?: number;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Builds the owner module of an iteration route: the memory import is shared, and the one loop
|
|
23
|
+
* of the owner function becomes `if (iterate(entry locals...)) { final values } else { the loop }`.
|
|
24
|
+
* The host function returns 1 after it ran every iteration and 0 to leave the original loop to
|
|
25
|
+
* run in the owner. A refusal names its reason and never throws.
|
|
26
|
+
*/
|
|
27
|
+
export declare function iterationOwner(original: Uint8Array, route: IterationRoute, stack?: string): {
|
|
28
|
+
owner: IterationOwner;
|
|
29
|
+
} | {
|
|
30
|
+
reason: IterationReason;
|
|
31
|
+
detail: string;
|
|
32
|
+
};
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import binaryen from 'binaryen';
|
|
2
|
+
import { restoreImportOrder } from "./import-order.js";
|
|
3
|
+
const PAGE_LIMIT = 65536;
|
|
4
|
+
function uleb(value) {
|
|
5
|
+
const out = [];
|
|
6
|
+
do {
|
|
7
|
+
let byte = value % 128;
|
|
8
|
+
value = Math.floor(value / 128);
|
|
9
|
+
if (value)
|
|
10
|
+
byte |= 128;
|
|
11
|
+
out.push(byte);
|
|
12
|
+
} while (value);
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
/** Reads the one imported memory's limits from the import section. */
|
|
16
|
+
function importedMemory(bytes) {
|
|
17
|
+
let at = 8;
|
|
18
|
+
const uint = () => {
|
|
19
|
+
let value = 0, shift = 0, byte;
|
|
20
|
+
do {
|
|
21
|
+
byte = bytes[at++];
|
|
22
|
+
value += (byte & 127) * 2 ** shift;
|
|
23
|
+
shift += 7;
|
|
24
|
+
} while (byte & 128);
|
|
25
|
+
return value;
|
|
26
|
+
};
|
|
27
|
+
const name = () => {
|
|
28
|
+
const length = uint();
|
|
29
|
+
const text = new TextDecoder().decode(bytes.subarray(at, at + length));
|
|
30
|
+
at += length;
|
|
31
|
+
return text;
|
|
32
|
+
};
|
|
33
|
+
const reference = () => {
|
|
34
|
+
const type = bytes[at++];
|
|
35
|
+
if (type === 0x63 || type === 0x64)
|
|
36
|
+
uint();
|
|
37
|
+
};
|
|
38
|
+
while (at < bytes.length) {
|
|
39
|
+
const header = at;
|
|
40
|
+
const id = bytes[at++];
|
|
41
|
+
const length = uint();
|
|
42
|
+
const sectionEnd = at + length;
|
|
43
|
+
const sectionStart = at;
|
|
44
|
+
if (id !== 2) {
|
|
45
|
+
at = sectionEnd;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const count = uint();
|
|
49
|
+
const found = [];
|
|
50
|
+
for (let i = 0; i < count; i++) {
|
|
51
|
+
const module = name();
|
|
52
|
+
const base = name();
|
|
53
|
+
const kind = bytes[at++];
|
|
54
|
+
if (kind === 0)
|
|
55
|
+
uint();
|
|
56
|
+
else if (kind === 1) {
|
|
57
|
+
reference();
|
|
58
|
+
const flags = uint();
|
|
59
|
+
uint();
|
|
60
|
+
if (flags & 1)
|
|
61
|
+
uint();
|
|
62
|
+
}
|
|
63
|
+
else if (kind === 2) {
|
|
64
|
+
const from = at;
|
|
65
|
+
const flags = uint();
|
|
66
|
+
const initial = uint();
|
|
67
|
+
const maximum = flags & 1 ? uint() : undefined;
|
|
68
|
+
found.push({
|
|
69
|
+
module,
|
|
70
|
+
name: base,
|
|
71
|
+
flags,
|
|
72
|
+
initial,
|
|
73
|
+
maximum,
|
|
74
|
+
limits: [from, at],
|
|
75
|
+
header,
|
|
76
|
+
body: [sectionStart, sectionEnd]
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
else if (kind === 3) {
|
|
80
|
+
reference();
|
|
81
|
+
at++;
|
|
82
|
+
}
|
|
83
|
+
else if (kind === 4) {
|
|
84
|
+
at++;
|
|
85
|
+
uint();
|
|
86
|
+
}
|
|
87
|
+
else
|
|
88
|
+
throw new TypeError('unsupported import descriptor');
|
|
89
|
+
}
|
|
90
|
+
return found;
|
|
91
|
+
}
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
/** Rewrites the memory import limits to shared with the largest maximum. */
|
|
95
|
+
function shareMemory(bytes, memory) {
|
|
96
|
+
const { limits, header, body } = memory;
|
|
97
|
+
const content = [
|
|
98
|
+
...bytes.subarray(body[0], limits[0]),
|
|
99
|
+
3,
|
|
100
|
+
...uleb(memory.initial),
|
|
101
|
+
...uleb(PAGE_LIMIT),
|
|
102
|
+
...bytes.subarray(limits[1], body[1])
|
|
103
|
+
];
|
|
104
|
+
return Uint8Array.from([
|
|
105
|
+
...bytes.subarray(0, header),
|
|
106
|
+
2,
|
|
107
|
+
...uleb(content.length),
|
|
108
|
+
...content,
|
|
109
|
+
...bytes.subarray(body[1])
|
|
110
|
+
]);
|
|
111
|
+
}
|
|
112
|
+
const refusal = (reason, detail) => ({ reason, detail });
|
|
113
|
+
/**
|
|
114
|
+
* Builds the owner module of an iteration route: the memory import is shared, and the one loop
|
|
115
|
+
* of the owner function becomes `if (iterate(entry locals...)) { final values } else { the loop }`.
|
|
116
|
+
* The host function returns 1 after it ran every iteration and 0 to leave the original loop to
|
|
117
|
+
* run in the owner. A refusal names its reason and never throws.
|
|
118
|
+
*/
|
|
119
|
+
export function iterationOwner(original, route, stack) {
|
|
120
|
+
let module;
|
|
121
|
+
try {
|
|
122
|
+
if (!route.eligible || !route.owner || !route.trip)
|
|
123
|
+
return refusal('no-arena', 'route is not eligible');
|
|
124
|
+
const memories = importedMemory(original);
|
|
125
|
+
if (memories.length !== 1)
|
|
126
|
+
return refusal('no-arena', 'iteration needs exactly one imported memory');
|
|
127
|
+
const declared = memories[0];
|
|
128
|
+
if (declared.flags & ~3)
|
|
129
|
+
return refusal('no-arena', 'wasm64 or unsupported memory limits');
|
|
130
|
+
const shared = shareMemory(original, declared);
|
|
131
|
+
module = binaryen.readBinary(shared);
|
|
132
|
+
const compactImports = binaryen.Features
|
|
133
|
+
.CompactImports;
|
|
134
|
+
module.setFeatures(binaryen.Features.All & ~compactImports);
|
|
135
|
+
const m = module;
|
|
136
|
+
if (m.getMemoryInfo().is64)
|
|
137
|
+
return refusal('no-arena', 'wasm64 memory');
|
|
138
|
+
if (/\bmemory\.(size|grow)\b/.test(m.emitText()))
|
|
139
|
+
return refusal('memory-size-observed', 'the module executes memory.size or memory.grow, which would observe the arena');
|
|
140
|
+
const owner = m.getFunction(route.owner);
|
|
141
|
+
if (!owner)
|
|
142
|
+
return refusal('no-arena', `owner ${route.owner} not found`);
|
|
143
|
+
const f = binaryen.getFunctionInfo(owner);
|
|
144
|
+
const types = [...binaryen.expandType(f.params), ...f.vars];
|
|
145
|
+
const id = (e) => binaryen.getExpressionId(e);
|
|
146
|
+
const locate = (e) => {
|
|
147
|
+
if (id(e) === binaryen.LoopId)
|
|
148
|
+
return { index: -1, loop: e };
|
|
149
|
+
if (id(e) !== binaryen.BlockId)
|
|
150
|
+
return;
|
|
151
|
+
const kids = binaryen.getExpressionInfo(e).children;
|
|
152
|
+
for (let i = 0; i < kids.length; i++) {
|
|
153
|
+
if (id(kids[i]) === binaryen.LoopId)
|
|
154
|
+
return { parent: e, index: i, loop: kids[i] };
|
|
155
|
+
const inner = locate(kids[i]);
|
|
156
|
+
if (inner)
|
|
157
|
+
return inner;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
const place = locate(f.body);
|
|
161
|
+
if (!place)
|
|
162
|
+
return refusal('no-arena', 'loop not found in the owner');
|
|
163
|
+
const imports = WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(original)));
|
|
164
|
+
let namespace = '__folio_iteration';
|
|
165
|
+
while (imports.some((item) => item.module === namespace))
|
|
166
|
+
namespace += '_';
|
|
167
|
+
let call = '__folio_iterate';
|
|
168
|
+
while (m.getFunction(call))
|
|
169
|
+
call += '_';
|
|
170
|
+
const locals = route.locals.map((item) => item.local);
|
|
171
|
+
m.addFunctionImport(call, namespace, 'iterate', binaryen.createType(locals.map((local) => types[local])), binaryen.i32);
|
|
172
|
+
const get = (local) => m.local.get(local, types[local]);
|
|
173
|
+
const counter = route.trip.local;
|
|
174
|
+
const done = [];
|
|
175
|
+
for (const item of route.locals)
|
|
176
|
+
if (item.kind === 'stride')
|
|
177
|
+
done.push(m.local.set(item.local, m.i32.add(get(item.local), m.i32.mul(get(counter), m.i32.const(item.stride | 0)))));
|
|
178
|
+
done.push(m.local.set(counter, m.i32.const(0)));
|
|
179
|
+
const replacement = m.if(m.call(call, locals.map((local) => get(local)), binaryen.i32), m.block(null, done), place.loop);
|
|
180
|
+
const raw = binaryen;
|
|
181
|
+
if (place.parent)
|
|
182
|
+
raw._BinaryenBlockSetChildAt(place.parent, place.index, replacement);
|
|
183
|
+
else
|
|
184
|
+
raw._BinaryenFunctionSetBody(owner, replacement);
|
|
185
|
+
let stackExport;
|
|
186
|
+
if (stack !== undefined && m.getGlobal(stack)) {
|
|
187
|
+
stackExport = '__folio_owner_stack';
|
|
188
|
+
while (m.getExport(stackExport))
|
|
189
|
+
stackExport += '_';
|
|
190
|
+
m.addGlobalExport(stack, stackExport);
|
|
191
|
+
}
|
|
192
|
+
if (!m.validate())
|
|
193
|
+
throw new Error('invalid iteration owner');
|
|
194
|
+
let bytes;
|
|
195
|
+
try {
|
|
196
|
+
bytes = restoreImportOrder(m.emitBinary(), imports);
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
return refusal('import-order', `import order cannot be kept: ${error instanceof Error ? error.message : String(error)}`);
|
|
200
|
+
}
|
|
201
|
+
new WebAssembly.Module(Uint8Array.from(bytes));
|
|
202
|
+
return {
|
|
203
|
+
owner: {
|
|
204
|
+
module: bytes,
|
|
205
|
+
namespace,
|
|
206
|
+
locals,
|
|
207
|
+
stackExport,
|
|
208
|
+
memory: {
|
|
209
|
+
module: declared.module,
|
|
210
|
+
name: declared.name,
|
|
211
|
+
initial: declared.initial,
|
|
212
|
+
maximum: declared.maximum
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
return refusal('no-arena', `iteration owner unavailable: ${error instanceof Error ? error.message : String(error)}`);
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
module?.dispose();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|