@onda-lang/wasm-compiler 0.9.1 → 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/api.md +325 -310
- package/bin/onda-wasm.js +4 -0
- package/dist/backend/compiler/core.js +175 -289
- package/dist/backend/compiler/expression-tree.js +108 -0
- package/dist/backend/compiler/guarded-addresses.js +243 -0
- package/dist/backend/compiler/index.js +41 -30
- package/dist/backend/compiler/inlining.js +62 -0
- package/dist/backend/compiler/lowering.js +16 -7
- package/dist/backend/compiler/shared.js +15 -9
- package/dist/backend/compiler/simd-reductions.js +229 -0
- package/dist/build.json +5 -5
- package/dist/frontend/onda_compiler_web_bg.wasm +0 -0
- package/dist/frontend/package.json +1 -1
- package/dist/licenses/RUST-DEPENDENCIES.txt +8 -8
- package/dist/version.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import binaryen from "binaryen";
|
|
2
|
+
|
|
3
|
+
// Children are listed in Wasm evaluation order. A missing layout means the
|
|
4
|
+
// pass cannot prove it has seen every access in this function.
|
|
5
|
+
function fields(api, ...names) {
|
|
6
|
+
return names.map(name => ({ get: api["get" + name], set: api["set" + name] }));
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function indexed(api, count, element) {
|
|
10
|
+
return {
|
|
11
|
+
count: api["getNum" + count],
|
|
12
|
+
get: api["get" + element + "At"],
|
|
13
|
+
set: api["set" + element + "At"],
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const layouts = new Map([
|
|
18
|
+
[binaryen.BlockId, [indexed(binaryen.Block, "Children", "Child")]],
|
|
19
|
+
[binaryen.IfId, fields(binaryen.If, "Condition", "IfTrue", "IfFalse")],
|
|
20
|
+
[binaryen.LoopId, fields(binaryen.Loop, "Body")],
|
|
21
|
+
[binaryen.BreakId, fields(binaryen.Break, "Value", "Condition")],
|
|
22
|
+
[binaryen.SwitchId, fields(binaryen.Switch, "Value", "Condition")],
|
|
23
|
+
[binaryen.CallId, [indexed(binaryen.Call, "Operands", "Operand")]],
|
|
24
|
+
[binaryen.CallIndirectId, [
|
|
25
|
+
indexed(binaryen.CallIndirect, "Operands", "Operand"), ...fields(binaryen.CallIndirect, "Target"),
|
|
26
|
+
]],
|
|
27
|
+
[binaryen.LocalSetId, fields(binaryen.LocalSet, "Value")],
|
|
28
|
+
[binaryen.GlobalSetId, fields(binaryen.GlobalSet, "Value")],
|
|
29
|
+
[binaryen.LoadId, fields(binaryen.Load, "Ptr")],
|
|
30
|
+
[binaryen.StoreId, fields(binaryen.Store, "Ptr", "Value")],
|
|
31
|
+
[binaryen.UnaryId, fields(binaryen.Unary, "Value")],
|
|
32
|
+
[binaryen.BinaryId, fields(binaryen.Binary, "Left", "Right")],
|
|
33
|
+
[binaryen.SelectId, fields(binaryen.Select, "IfTrue", "IfFalse", "Condition")],
|
|
34
|
+
[binaryen.DropId, fields(binaryen.Drop, "Value")],
|
|
35
|
+
[binaryen.ReturnId, fields(binaryen.Return, "Value")],
|
|
36
|
+
[binaryen.MemoryCopyId, fields(binaryen.MemoryCopy, "Dest", "Source", "Size")],
|
|
37
|
+
[binaryen.MemoryFillId, fields(binaryen.MemoryFill, "Dest", "Value", "Size")],
|
|
38
|
+
[binaryen.SIMDExtractId, fields(binaryen.SIMDExtract, "Vec")],
|
|
39
|
+
[binaryen.SIMDReplaceId, fields(binaryen.SIMDReplace, "Vec", "Value")],
|
|
40
|
+
[binaryen.SIMDShuffleId, fields(binaryen.SIMDShuffle, "Left", "Right")],
|
|
41
|
+
[binaryen.SIMDTernaryId, fields(binaryen.SIMDTernary, "A", "B", "C")],
|
|
42
|
+
[binaryen.SIMDShiftId, fields(binaryen.SIMDShift, "Vec", "Shift")],
|
|
43
|
+
[binaryen.SIMDLoadId, fields(binaryen.SIMDLoad, "Ptr")],
|
|
44
|
+
[binaryen.SIMDLoadStoreLaneId, fields(binaryen.SIMDLoadStoreLane, "Ptr", "Vec")],
|
|
45
|
+
[binaryen.TupleMakeId, [indexed(binaryen.TupleMake, "Operands", "Operand")]],
|
|
46
|
+
[binaryen.TupleExtractId, fields(binaryen.TupleExtract, "Tuple")],
|
|
47
|
+
...[binaryen.ConstId, binaryen.LocalGetId, binaryen.GlobalGetId, binaryen.NopId,
|
|
48
|
+
binaryen.UnreachableId, binaryen.MemorySizeId, binaryen.DataDropId].map(id => [id, []]),
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
// A visitor can return a replacement for a child. Read-only passes leave the
|
|
52
|
+
// tree untouched. Unknown node kinds invalidate whole-function analyses.
|
|
53
|
+
export function rewriteExpressionChildren(expr, visit) {
|
|
54
|
+
const layout = layouts.get(binaryen.getExpressionId(expr));
|
|
55
|
+
if (!layout) return false;
|
|
56
|
+
for (const slot of layout) {
|
|
57
|
+
if (slot.count) {
|
|
58
|
+
const count = slot.count(expr);
|
|
59
|
+
for (let i = 0; i < count; i++) {
|
|
60
|
+
const child = slot.get(expr, i);
|
|
61
|
+
const value = visit(child);
|
|
62
|
+
if (value !== undefined && value !== child) slot.set(expr, i, value);
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
const child = slot.get(expr);
|
|
66
|
+
if (!child) continue;
|
|
67
|
+
const value = visit(child);
|
|
68
|
+
if (value !== undefined && value !== child) slot.set(expr, value);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Leave headroom for the recursive JS optimization passes and Binaryen 132's
|
|
75
|
+
// emitter. Inspect one level at a time so even a fully inlined tree is safe.
|
|
76
|
+
const MAX_EXPRESSION_DEPTH = 256;
|
|
77
|
+
|
|
78
|
+
function inspectBody(body) {
|
|
79
|
+
let level = [body];
|
|
80
|
+
let next = [];
|
|
81
|
+
let supported = true;
|
|
82
|
+
const enqueue = child => { next.push(child); };
|
|
83
|
+
for (let depth = 1; level.length; depth++) {
|
|
84
|
+
if (depth > MAX_EXPRESSION_DEPTH) return "deep";
|
|
85
|
+
for (const expr of level) {
|
|
86
|
+
if (!rewriteExpressionChildren(expr, enqueue)) supported = false;
|
|
87
|
+
}
|
|
88
|
+
level.length = 0;
|
|
89
|
+
[level, next] = [next, level];
|
|
90
|
+
}
|
|
91
|
+
return supported ? "supported" : "unknown";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function prepareFunctionBody(module, func) {
|
|
95
|
+
let body = binaryen.Function.getBody(func);
|
|
96
|
+
if (!body) return 0;
|
|
97
|
+
let shape = inspectBody(body);
|
|
98
|
+
if (shape === "deep") {
|
|
99
|
+
// Keep operands flat. Drop unused temporaries before coalescing so the
|
|
100
|
+
// interference analysis only sees locals that still occur in the body.
|
|
101
|
+
module.runPassesOnFunction(func, [
|
|
102
|
+
"flatten", "simplify-locals-nonesting", "reorder-locals", "coalesce-locals", "vacuum",
|
|
103
|
+
]);
|
|
104
|
+
body = binaryen.Function.getBody(func);
|
|
105
|
+
shape = inspectBody(body);
|
|
106
|
+
}
|
|
107
|
+
return shape === "supported" ? body : 0;
|
|
108
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import binaryen from "binaryen";
|
|
2
|
+
import { prepareFunctionBody, rewriteExpressionChildren } from "./expression-tree.js";
|
|
3
|
+
|
|
4
|
+
// Duplicating a few additions can slow compact loops. Reserve this pass for
|
|
5
|
+
// decisions that keep a group of pointer temporaries live across the branch.
|
|
6
|
+
const MIN_LIVE_ADDRESSES = 12;
|
|
7
|
+
|
|
8
|
+
// Binaryen can push a set into one arm. When both arms read the pointer,
|
|
9
|
+
// find the innermost guard enclosing all dereferences on each side.
|
|
10
|
+
function guardedDecision(definition, reads) {
|
|
11
|
+
const targets = new Map();
|
|
12
|
+
for (const read of reads) {
|
|
13
|
+
// A statement dominates its later siblings and their children. Staying
|
|
14
|
+
// in the same loop also prevents moving work across iterations.
|
|
15
|
+
if (!read.memoryAccess || read.loop !== definition.loop ||
|
|
16
|
+
read.position <= definition.start || read.position > definition.block.end) {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
let outer = read.arm;
|
|
20
|
+
while (outer && outer.parent !== definition.arm) outer = outer.parent;
|
|
21
|
+
if (!outer || outer.start <= definition.start) return null;
|
|
22
|
+
|
|
23
|
+
// Reads are in traversal order. Widen the first read's arm just enough
|
|
24
|
+
// to enclose each subsequent read on this side of the decision.
|
|
25
|
+
let target = targets.get(outer) ?? read.arm;
|
|
26
|
+
while (target.end < read.position) target = target.parent;
|
|
27
|
+
targets.set(outer, target);
|
|
28
|
+
}
|
|
29
|
+
if (targets.size !== 2) return null;
|
|
30
|
+
const [left, right] = targets.keys();
|
|
31
|
+
// Duplicating at the entry to both arms would still run the addition
|
|
32
|
+
// on every path. At least one arm must have a deeper guard.
|
|
33
|
+
if (left.owner !== right.owner ||
|
|
34
|
+
(targets.get(left) === left && targets.get(right) === right)) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return left.owner;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function addressSum(set) {
|
|
41
|
+
if (binaryen.LocalSet.isTee(set)) return 0;
|
|
42
|
+
const value = binaryen.LocalSet.getValue(set);
|
|
43
|
+
if (binaryen.getExpressionId(value) !== binaryen.BinaryId ||
|
|
44
|
+
binaryen.Binary.getOp(value) !== binaryen.AddInt32 ||
|
|
45
|
+
binaryen.getExpressionId(binaryen.Binary.getLeft(value)) !== binaryen.LocalGetId ||
|
|
46
|
+
binaryen.getExpressionId(binaryen.Binary.getRight(value)) !== binaryen.LocalGetId) return 0;
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function sinkGuardedAddresses(module, body) {
|
|
51
|
+
const reads = new Map();
|
|
52
|
+
const writes = new Map();
|
|
53
|
+
const definitions = [];
|
|
54
|
+
const constantStores = new Map();
|
|
55
|
+
let position = 0;
|
|
56
|
+
let complete = true;
|
|
57
|
+
|
|
58
|
+
function scan(expr, loop, arm, block = null, childIndex = -1, memoryAccess = 0) {
|
|
59
|
+
const start = ++position;
|
|
60
|
+
const id = binaryen.getExpressionId(expr);
|
|
61
|
+
if (id === binaryen.LocalGetId) {
|
|
62
|
+
const index = binaryen.LocalGet.getIndex(expr);
|
|
63
|
+
if (!reads.has(index)) reads.set(index, []);
|
|
64
|
+
reads.get(index).push({ position, arm, loop, memoryAccess });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (id === binaryen.LocalSetId) {
|
|
68
|
+
const index = binaryen.LocalSet.getIndex(expr);
|
|
69
|
+
writes.set(index, writes.has(index) ? Infinity : start);
|
|
70
|
+
const value = block && loop && addressSum(expr);
|
|
71
|
+
if (value) {
|
|
72
|
+
const operands = [binaryen.Binary.getLeft(value), binaryen.Binary.getRight(value)]
|
|
73
|
+
.map(input => binaryen.LocalGet.getIndex(input));
|
|
74
|
+
definitions.push({ index, value, operands, start, block, childIndex, loop, arm });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (id === binaryen.BlockId) {
|
|
78
|
+
const scope = { expr, end: 0 };
|
|
79
|
+
const children = binaryen.Block.getChildren(expr);
|
|
80
|
+
children.forEach((child, i) => scan(child, loop, arm, scope, i));
|
|
81
|
+
scope.end = position;
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (id === binaryen.IfId) {
|
|
85
|
+
const decision = { condition: binaryen.If.getCondition(expr), block, start };
|
|
86
|
+
scan(decision.condition, loop, arm);
|
|
87
|
+
for (const whenTrue of [true, false]) {
|
|
88
|
+
const child = whenTrue ? binaryen.If.getIfTrue(expr) : binaryen.If.getIfFalse(expr);
|
|
89
|
+
if (!child) continue;
|
|
90
|
+
const branch = { parent: arm, owner: decision, start: position + 1, end: 0 };
|
|
91
|
+
scan(child, loop, branch);
|
|
92
|
+
branch.end = position;
|
|
93
|
+
}
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (id === binaryen.LoopId) loop = expr;
|
|
97
|
+
const ptr = id === binaryen.LoadId ? binaryen.Load.getPtr(expr)
|
|
98
|
+
: id === binaryen.StoreId ? binaryen.Store.getPtr(expr) : 0;
|
|
99
|
+
if (block && id === binaryen.StoreId && binaryen.getExpressionId(ptr) === binaryen.LocalSetId &&
|
|
100
|
+
binaryen.getExpressionId(binaryen.Store.getValue(expr)) === binaryen.ConstId) {
|
|
101
|
+
constantStores.set(binaryen.LocalSet.getIndex(ptr), {
|
|
102
|
+
block, start, offset: binaryen.Store.getOffset(expr),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
if (!rewriteExpressionChildren(expr, child => {
|
|
106
|
+
scan(child, loop, arm, null, -1, child === ptr ? expr : 0);
|
|
107
|
+
return child;
|
|
108
|
+
})) complete = false;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
scan(body, null, null);
|
|
112
|
+
// An unsupported subtree could hide a write to the index or base.
|
|
113
|
+
if (!complete || definitions.length < MIN_LIVE_ADDRESSES) return;
|
|
114
|
+
const decisions = new Map();
|
|
115
|
+
for (const def of definitions) {
|
|
116
|
+
// A single earlier write (or a parameter) keeps the base and index
|
|
117
|
+
// stable until all uses.
|
|
118
|
+
if (writes.get(def.index) !== def.start ||
|
|
119
|
+
def.operands.some(index => (writes.get(index) ?? 0) >= def.start)) {
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const decision = guardedDecision(def, reads.get(def.index) ?? []);
|
|
123
|
+
if (!decision) continue;
|
|
124
|
+
if (!decisions.has(decision)) decisions.set(decision, []);
|
|
125
|
+
decisions.get(decision).push(def);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
let fieldBases;
|
|
129
|
+
for (const [decision, group] of decisions) {
|
|
130
|
+
if (group.length < MIN_LIVE_ADDRESSES) continue;
|
|
131
|
+
// An inlined setter may test a field it just assigned a literal. Keep
|
|
132
|
+
// addresses shared when that pattern suggests a predictable branch.
|
|
133
|
+
if (testsConstantStore(decision, constantStores)) continue;
|
|
134
|
+
fieldBases ??= entryFieldBases(body);
|
|
135
|
+
for (const def of group) {
|
|
136
|
+
const pointer = indexedFieldAddress(module, def, fieldBases, writes);
|
|
137
|
+
for (const { memoryAccess } of reads.get(def.index)) {
|
|
138
|
+
const address = module.copyExpression(pointer);
|
|
139
|
+
if (binaryen.getExpressionId(memoryAccess) === binaryen.LoadId) {
|
|
140
|
+
binaryen.Load.setPtr(memoryAccess, address);
|
|
141
|
+
} else {
|
|
142
|
+
binaryen.Store.setPtr(memoryAccess, address);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
binaryen.Block.setChildAt(def.block.expr, def.childIndex, module.nop());
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// State layout exposes fixed field bases as consecutive entry assignments of
|
|
151
|
+
// the form "base = global + offset". One snapshot can address every field in
|
|
152
|
+
// such a run. Any intervening statement or change of global ends the run.
|
|
153
|
+
function entryFieldBases(body) {
|
|
154
|
+
const bases = new Map();
|
|
155
|
+
if (binaryen.getExpressionId(body) !== binaryen.BlockId) return bases;
|
|
156
|
+
let run;
|
|
157
|
+
for (const statement of binaryen.Block.getChildren(body)) {
|
|
158
|
+
const field = fixedFieldBase(statement);
|
|
159
|
+
if (!field) {
|
|
160
|
+
run = null;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (run?.global !== field.global) run = { global: field.global, lowest: field };
|
|
164
|
+
if (field.offset < run.lowest.offset) run.lowest = field;
|
|
165
|
+
bases.set(field.index, { field, run });
|
|
166
|
+
}
|
|
167
|
+
return bases;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function fixedFieldBase(statement) {
|
|
171
|
+
if (binaryen.getExpressionId(statement) !== binaryen.LocalSetId) return null;
|
|
172
|
+
const add = binaryen.LocalSet.getValue(statement);
|
|
173
|
+
if (binaryen.getExpressionId(add) !== binaryen.BinaryId ||
|
|
174
|
+
binaryen.Binary.getOp(add) !== binaryen.AddInt32) return null;
|
|
175
|
+
const base = binaryen.Binary.getLeft(add);
|
|
176
|
+
const offset = binaryen.Binary.getRight(add);
|
|
177
|
+
if (binaryen.getExpressionId(base) !== binaryen.GlobalGetId ||
|
|
178
|
+
binaryen.getExpressionId(offset) !== binaryen.ConstId) return null;
|
|
179
|
+
return {
|
|
180
|
+
index: binaryen.LocalSet.getIndex(statement),
|
|
181
|
+
global: binaryen.GlobalGet.getName(base),
|
|
182
|
+
offset: binaryen.Const.getValueI32(offset),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function indexedFieldAddress(module, def, bases, writes) {
|
|
187
|
+
const side = def.operands.findIndex(index => bases.has(index));
|
|
188
|
+
if (side < 0) return def.value;
|
|
189
|
+
const { field, run } = bases.get(def.operands[side]);
|
|
190
|
+
if (writes.get(run.lowest.index) >= def.start) return def.value;
|
|
191
|
+
const get = index => module.local.get(index, binaryen.i32);
|
|
192
|
+
const common = module.i32.add(get(def.operands[1 - side]), get(run.lowest.index));
|
|
193
|
+
// Keep the displacement in i32 arithmetic so the effective address wraps
|
|
194
|
+
// exactly as it did before, including at the end of the address space.
|
|
195
|
+
const delta = field.offset - run.lowest.offset;
|
|
196
|
+
return delta ? module.i32.add(common, module.i32.const(delta)) : common;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function testsConstantStore({ condition, block, start }, stores) {
|
|
200
|
+
if (binaryen.getExpressionId(condition) !== binaryen.BinaryId) return false;
|
|
201
|
+
const left = binaryen.Binary.getLeft(condition);
|
|
202
|
+
const right = binaryen.Binary.getRight(condition);
|
|
203
|
+
const load = binaryen.getExpressionId(left) === binaryen.ConstId ? right
|
|
204
|
+
: binaryen.getExpressionId(right) === binaryen.ConstId ? left : 0;
|
|
205
|
+
if (!load || binaryen.getExpressionId(load) !== binaryen.LoadId) return false;
|
|
206
|
+
const ptr = binaryen.Load.getPtr(load);
|
|
207
|
+
if (binaryen.getExpressionId(ptr) !== binaryen.LocalGetId) return false;
|
|
208
|
+
const store = stores.get(binaryen.LocalGet.getIndex(ptr));
|
|
209
|
+
return store && store.block === block && store.start < start &&
|
|
210
|
+
store.offset === binaryen.Load.getOffset(load);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// SSA gives each write a fresh local but preserves the address additions.
|
|
214
|
+
// Count those definitions first so only candidate functions pay for SSA and cleanup.
|
|
215
|
+
function hasAddressGroup(body) {
|
|
216
|
+
let found = false;
|
|
217
|
+
function visit(expr, loop) {
|
|
218
|
+
const id = binaryen.getExpressionId(expr);
|
|
219
|
+
if (id === binaryen.LoopId) loop = { addresses: 0, decision: false };
|
|
220
|
+
if (loop) {
|
|
221
|
+
if (id === binaryen.LocalSetId && addressSum(expr)) loop.addresses++;
|
|
222
|
+
if (id === binaryen.IfId && binaryen.If.getIfFalse(expr)) loop.decision = true;
|
|
223
|
+
if (loop.decision && loop.addresses >= MIN_LIVE_ADDRESSES) {
|
|
224
|
+
found = true;
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
rewriteExpressionChildren(expr, child => { if (!found) visit(child, loop); });
|
|
229
|
+
}
|
|
230
|
+
visit(body, null);
|
|
231
|
+
return found;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function optimizeGuardedAddresses(module, func) {
|
|
235
|
+
// Also bounds expression depth for Binaryen's emitter on the skipped path.
|
|
236
|
+
const body = prepareFunctionBody(module, func);
|
|
237
|
+
if (!body || binaryen.Function.getNumLocals(func) < MIN_LIVE_ADDRESSES || !hasAddressGroup(body)) return;
|
|
238
|
+
module.runPassesOnFunction(func, ["ssa-nomerge"]);
|
|
239
|
+
const ssa = prepareFunctionBody(module, func);
|
|
240
|
+
if (ssa) sinkGuardedAddresses(module, ssa);
|
|
241
|
+
module.runPassesOnFunction(func, ["code-pushing", "simplify-locals", "coalesce-locals", "vacuum"]);
|
|
242
|
+
prepareFunctionBody(module, func);
|
|
243
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { defineFunction } from "./inlining.js";
|
|
1
2
|
import binaryen from "binaryen";
|
|
2
3
|
import { MirCompilerLowering } from "./lowering.js";
|
|
3
4
|
import {
|
|
@@ -12,6 +13,7 @@ import {
|
|
|
12
13
|
PRINT_RECORD_HEADER_SIZE,
|
|
13
14
|
POINTER_GLOBALS,
|
|
14
15
|
typeName,
|
|
16
|
+
roundHelperName,
|
|
15
17
|
decodeI64Literal,
|
|
16
18
|
decodeFloatLiteral,
|
|
17
19
|
} from "./shared.js";
|
|
@@ -890,10 +892,7 @@ export class MirCompiler extends MirCompilerLowering {
|
|
|
890
892
|
const layout = this.stateLayout[place.base.data];
|
|
891
893
|
if (!layout) this.fail(`state id ${place.base.data} is out of range`);
|
|
892
894
|
typeId = this.mir.state[place.base.data].ty;
|
|
893
|
-
address = this.
|
|
894
|
-
this.module.global.get(POINTER_GLOBALS.state, binaryen.i32),
|
|
895
|
-
this.module.i32.const(layout.offset),
|
|
896
|
-
);
|
|
895
|
+
address = this.stateAddress(place.base.data, context);
|
|
897
896
|
break;
|
|
898
897
|
}
|
|
899
898
|
case "param": {
|
|
@@ -948,6 +947,23 @@ export class MirCompiler extends MirCompilerLowering {
|
|
|
948
947
|
return address;
|
|
949
948
|
}
|
|
950
949
|
|
|
950
|
+
stateAddress(stateId, context) {
|
|
951
|
+
const cache = context.stateAddressCache;
|
|
952
|
+
const existing = cache?.get(stateId);
|
|
953
|
+
if (existing !== undefined) return this.module.local.get(existing, binaryen.i32);
|
|
954
|
+
|
|
955
|
+
const address = this.module.i32.add(
|
|
956
|
+
this.module.global.get(POINTER_GLOBALS.state, binaryen.i32),
|
|
957
|
+
this.module.i32.const(this.stateLayout[stateId].offset),
|
|
958
|
+
);
|
|
959
|
+
if (!cache) return address;
|
|
960
|
+
|
|
961
|
+
const local = this.allocateGeneratedLocal(context, "i32", `state.${stateId}.address`);
|
|
962
|
+
cache.set(stateId, local);
|
|
963
|
+
context.entryInitializers.push(this.module.local.set(local, address));
|
|
964
|
+
return this.module.local.get(local, binaryen.i32);
|
|
965
|
+
}
|
|
966
|
+
|
|
951
967
|
compileBoundedIndex(value, length, bounds, context) {
|
|
952
968
|
if (!Number.isInteger(length) || length <= 0) {
|
|
953
969
|
this.fail("array and port lengths must be positive integers");
|
|
@@ -1297,7 +1313,7 @@ export class MirCompiler extends MirCompilerLowering {
|
|
|
1297
1313
|
case "pow":
|
|
1298
1314
|
return this.compileMathKernelCall(data.intrinsic, scalar, args);
|
|
1299
1315
|
case "round":
|
|
1300
|
-
return this.
|
|
1316
|
+
return this.module.call(roundHelperName(scalar), args, this.wasmType(scalar));
|
|
1301
1317
|
default:
|
|
1302
1318
|
this.fail(`unknown intrinsic '${String(data.intrinsic)}'`);
|
|
1303
1319
|
}
|
|
@@ -1305,7 +1321,7 @@ export class MirCompiler extends MirCompilerLowering {
|
|
|
1305
1321
|
|
|
1306
1322
|
compileMathKernelCall(intrinsic, scalar, args) {
|
|
1307
1323
|
const name = `onda_math_${intrinsic}_${scalar}`;
|
|
1308
|
-
if (!this.
|
|
1324
|
+
if (!this.mathHelpers.kernel.has(name)) {
|
|
1309
1325
|
this.fail(`math kernel was not reserved for helper '${name}'`);
|
|
1310
1326
|
}
|
|
1311
1327
|
return this.module.call(
|
|
@@ -1315,31 +1331,26 @@ export class MirCompiler extends MirCompilerLowering {
|
|
|
1315
1331
|
);
|
|
1316
1332
|
}
|
|
1317
1333
|
|
|
1318
|
-
|
|
1319
|
-
const
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1334
|
+
addRoundHelper(scalar) {
|
|
1335
|
+
const wasm = this.module[scalar];
|
|
1336
|
+
const get = () => this.module.local.get(0, this.wasmType(scalar));
|
|
1337
|
+
const trunc = () => wasm.trunc(get());
|
|
1338
|
+
const magnitude = wasm.abs(wasm.sub(get(), trunc()));
|
|
1339
|
+
const rounded = wasm.add(
|
|
1340
|
+
trunc(),
|
|
1341
|
+
wasm.copysign(wasm.const(1), get()),
|
|
1342
|
+
);
|
|
1343
|
+
defineFunction(
|
|
1344
|
+
this.module, this.signatureTypes, roundHelperName(scalar),
|
|
1345
|
+
this.wasmType(scalar),
|
|
1346
|
+
this.wasmType(scalar),
|
|
1347
|
+
[],
|
|
1348
|
+
this.module.select(
|
|
1349
|
+
wasm.ge(magnitude, wasm.const(0.5)),
|
|
1350
|
+
rounded,
|
|
1326
1351
|
trunc(),
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
this.module.addFunction(
|
|
1330
|
-
name,
|
|
1331
|
-
this.wasmType(scalar),
|
|
1332
|
-
this.wasmType(scalar),
|
|
1333
|
-
[],
|
|
1334
|
-
this.module.select(
|
|
1335
|
-
wasm.ge(magnitude, wasm.const(0.5)),
|
|
1336
|
-
rounded,
|
|
1337
|
-
trunc(),
|
|
1338
|
-
),
|
|
1339
|
-
);
|
|
1340
|
-
this.internalHelpers.add(name);
|
|
1341
|
-
}
|
|
1342
|
-
return this.module.call(name, args, this.wasmType(scalar));
|
|
1352
|
+
),
|
|
1353
|
+
);
|
|
1343
1354
|
}
|
|
1344
1355
|
|
|
1345
1356
|
loadScalar(scalar, address) {
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import binaryen from "binaryen";
|
|
2
|
+
|
|
3
|
+
// Binaryen's inline annotation encodes the inlining preference in one byte.
|
|
4
|
+
const NEVER = "00";
|
|
5
|
+
const ALWAYS = "7f";
|
|
6
|
+
|
|
7
|
+
// Binaryen 132 accepts inline annotations on declarations in WAT. Its JS API
|
|
8
|
+
// can fill in their signatures, locals and bodies, but cannot set the hint.
|
|
9
|
+
export function createModuleWithInlineHints(functions, names, hintOnlyPass, kernel, roundHelpers) {
|
|
10
|
+
const never = [];
|
|
11
|
+
const heuristic = [];
|
|
12
|
+
const always = [];
|
|
13
|
+
for (const [id, func] of functions.entries()) {
|
|
14
|
+
switch (func.attributes.inline) {
|
|
15
|
+
case "never": never.push(names[id]); break;
|
|
16
|
+
case "always": always.push(names[id]); break;
|
|
17
|
+
default: heuristic.push(names[id]); break;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const declarations = [];
|
|
21
|
+
function declare(name, hint) {
|
|
22
|
+
const annotation = hint ? `(@binaryen.inline "\\${hint}") ` : "";
|
|
23
|
+
declarations.push(`${annotation}(func $${name})`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Binaryen keeps the first identical definition. A call that survives the
|
|
27
|
+
// early inliner must keep the more conservative policy when bodies merge.
|
|
28
|
+
for (const name of never) declare(name, NEVER);
|
|
29
|
+
if (always.length) {
|
|
30
|
+
// Low optimization levels run the early inliner solely for MIR 'always'.
|
|
31
|
+
const hint = hintOnlyPass ? NEVER : null;
|
|
32
|
+
for (const name of heuristic) declare(name, hint);
|
|
33
|
+
const count = kernel?.getNumFunctions() ?? 0;
|
|
34
|
+
for (let i = 0; i < count; i++) {
|
|
35
|
+
declare(binaryen.Function.getName(kernel.getFunctionByIndex(i)), hint);
|
|
36
|
+
}
|
|
37
|
+
for (const name of roundHelpers) declare(name, hint);
|
|
38
|
+
for (const name of always) declare(name, ALWAYS);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return declarations.length
|
|
42
|
+
? binaryen.parseText(`(module\n${declarations.join("\n")}\n)`)
|
|
43
|
+
: new binaryen.Module();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function defineFunction(module, signatureTypes, name, params, results, vars, body) {
|
|
47
|
+
const declaration = module.getFunction(name);
|
|
48
|
+
if (!declaration) return module.addFunction(name, params, results, vars, body);
|
|
49
|
+
|
|
50
|
+
const key = `${params}:${results}`;
|
|
51
|
+
let signature = signatureTypes.get(key);
|
|
52
|
+
if (signature === undefined) {
|
|
53
|
+
const types = new binaryen.TypeBuilder(1);
|
|
54
|
+
types.setSignatureType(0, params, results);
|
|
55
|
+
[signature] = types.buildAndDispose();
|
|
56
|
+
signatureTypes.set(key, signature);
|
|
57
|
+
}
|
|
58
|
+
binaryen._BinaryenFunctionSetType(declaration, signature);
|
|
59
|
+
for (const type of vars) binaryen._BinaryenFunctionAddVar(declaration, type);
|
|
60
|
+
binaryen.Function.setBody(declaration, body);
|
|
61
|
+
return declaration;
|
|
62
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import binaryen from "binaryen";
|
|
2
|
+
import { vectorizeBankReduction } from "./simd-reductions.js";
|
|
2
3
|
import { vectorizeSampleLoop } from "./simd.js";
|
|
3
4
|
import { MirCompilerCore } from "./core.js";
|
|
4
5
|
import {
|
|
@@ -19,16 +20,16 @@ import {
|
|
|
19
20
|
} from "./shared.js";
|
|
20
21
|
|
|
21
22
|
export class MirCompilerLowering extends MirCompilerCore {
|
|
22
|
-
compileBlock(block, context) {
|
|
23
|
+
compileBlock(block, context, competingLoop = false) {
|
|
23
24
|
return this.module.block(
|
|
24
25
|
null,
|
|
25
26
|
block.statements.map((statement) =>
|
|
26
|
-
this.compileStatement(statement, context),
|
|
27
|
+
this.compileStatement(statement, context, competingLoop),
|
|
27
28
|
),
|
|
28
29
|
);
|
|
29
30
|
}
|
|
30
31
|
|
|
31
|
-
compileStatement(statement, context) {
|
|
32
|
+
compileStatement(statement, context, competingLoop) {
|
|
32
33
|
const kind = statement.kind?.kind;
|
|
33
34
|
const data = statement.kind?.data;
|
|
34
35
|
switch (kind) {
|
|
@@ -87,12 +88,15 @@ export class MirCompilerLowering extends MirCompilerCore {
|
|
|
87
88
|
return this.compileOutputStore(data, context);
|
|
88
89
|
case "control_output_store":
|
|
89
90
|
return this.compileControlOutputStore(data, context);
|
|
90
|
-
case "if":
|
|
91
|
+
case "if": {
|
|
92
|
+
const hasScalarLoop = (block) => block.statements.some(statement =>
|
|
93
|
+
statement.kind.kind === "loop" && !this.orderedReductions.has(statement));
|
|
91
94
|
return this.module.if(
|
|
92
95
|
this.compileValue(data.condition, context),
|
|
93
|
-
this.compileBlock(data.then_block, context),
|
|
94
|
-
this.compileBlock(data.else_block, context),
|
|
96
|
+
this.compileBlock(data.then_block, context, competingLoop || hasScalarLoop(data.else_block)),
|
|
97
|
+
this.compileBlock(data.else_block, context, competingLoop || hasScalarLoop(data.then_block)),
|
|
95
98
|
);
|
|
99
|
+
}
|
|
96
100
|
case "loop": {
|
|
97
101
|
const id = this.nextLabel++;
|
|
98
102
|
const breakLabel = `$onda.break.${id}`;
|
|
@@ -108,7 +112,12 @@ export class MirCompilerLowering extends MirCompilerCore {
|
|
|
108
112
|
this.module.block(null, [body, this.module.br(continueLabel)]),
|
|
109
113
|
),
|
|
110
114
|
]);
|
|
111
|
-
|
|
115
|
+
if (!context.allowLocalOptimizations) return scalarLoop;
|
|
116
|
+
const vectorLoop = vectorizeSampleLoop(this, statement, context, scalarLoop)
|
|
117
|
+
?? vectorizeBankReduction(this, statement, context, scalarLoop, competingLoop);
|
|
118
|
+
if (vectorLoop == null) return scalarLoop;
|
|
119
|
+
context.vectorizedLoop = true;
|
|
120
|
+
return vectorLoop;
|
|
112
121
|
}
|
|
113
122
|
case "break":
|
|
114
123
|
return this.module.br(this.currentLabel(context.breakLabels, "break"));
|
|
@@ -111,8 +111,13 @@ export const TRAPPING_DESCRIPTOR_BINARY_OPS = new Set([
|
|
|
111
111
|
binaryen.RemUInt64,
|
|
112
112
|
]);
|
|
113
113
|
|
|
114
|
-
export function
|
|
115
|
-
|
|
114
|
+
export function roundHelperName(scalar) {
|
|
115
|
+
return `$onda.math.round.${scalar}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function collectMathHelpers(mir) {
|
|
119
|
+
const kernel = new Set();
|
|
120
|
+
const round = new Set();
|
|
116
121
|
for (const func of mir?.functions ?? []) {
|
|
117
122
|
const localScalars = (func.locals ?? []).map((local) => {
|
|
118
123
|
const type = mir.types?.[local.ty];
|
|
@@ -130,11 +135,12 @@ export function collectMathKernelHelpers(mir) {
|
|
|
130
135
|
if (kind === "assign" && data?.value?.kind === "intrinsic") {
|
|
131
136
|
const intrinsic = data.value.data?.intrinsic;
|
|
132
137
|
const scalar = valueScalar(data.value.data?.args?.[0]);
|
|
133
|
-
if (
|
|
134
|
-
MATH_KERNEL_INTRINSICS.has(intrinsic)
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
+
if (scalar === "f32" || scalar === "f64") {
|
|
139
|
+
if (MATH_KERNEL_INTRINSICS.has(intrinsic)) {
|
|
140
|
+
kernel.add(`onda_math_${intrinsic}_${scalar}`);
|
|
141
|
+
} else if (intrinsic === "round") {
|
|
142
|
+
round.add(scalar);
|
|
143
|
+
}
|
|
138
144
|
}
|
|
139
145
|
} else if (
|
|
140
146
|
kind === "assign"
|
|
@@ -143,7 +149,7 @@ export function collectMathKernelHelpers(mir) {
|
|
|
143
149
|
) {
|
|
144
150
|
const scalar = valueScalar(data.value.data?.lhs);
|
|
145
151
|
if (scalar === "f32" || scalar === "f64") {
|
|
146
|
-
|
|
152
|
+
kernel.add(`onda_math_remainder_${scalar}`);
|
|
147
153
|
}
|
|
148
154
|
} else if (kind === "if") {
|
|
149
155
|
visitBlock(data?.then_block);
|
|
@@ -155,7 +161,7 @@ export function collectMathKernelHelpers(mir) {
|
|
|
155
161
|
};
|
|
156
162
|
visitBlock(func.body);
|
|
157
163
|
}
|
|
158
|
-
return
|
|
164
|
+
return { kernel, round };
|
|
159
165
|
}
|
|
160
166
|
|
|
161
167
|
export function alignUp(value, alignment) {
|