@go-go-golems/compiler-toolkit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +565 -2
- package/docs/design.md +748 -0
- package/docs/guide.md +1672 -0
- package/package.json +30 -4
- package/src/context.js +17 -0
- package/src/data.js +24 -0
- package/src/diag.js +116 -0
- package/src/frag.js +194 -0
- package/src/index.js +41 -0
- package/src/ir.js +1204 -0
- package/src/lower.js +101 -0
- package/src/pass.js +182 -0
- package/src/rules.js +236 -0
- package/src/stages.js +68 -0
- package/src/std/asm.js +65 -0
- package/src/std/dataflow.js +67 -0
- package/src/std/graph.js +197 -0
- package/src/std/lattice.js +23 -0
- package/src/std/passes.js +76 -0
package/src/ir.js
ADDED
|
@@ -0,0 +1,1204 @@
|
|
|
1
|
+
// ir.js — the core: an IR is a set of ops; values are instances of ops; functions hold blocks of values (or, for an IR
|
|
2
|
+
// without blocks, a free expression graph); modules hold functions. Everything a pass does goes through five
|
|
3
|
+
// mutations (create, replace, erase, move, set an argument), and each one records who did it: that record is the
|
|
4
|
+
// provenance. Analyses are cached per function revision and refuse to be read once the function has changed.
|
|
5
|
+
|
|
6
|
+
import { TkError, strict, checks, didYouMean, describe, memberNames, PROBES } from './diag.js';
|
|
7
|
+
import { currentBy, withBy } from './context.js';
|
|
8
|
+
|
|
9
|
+
/** Attribute types: a name and a predicate. */
|
|
10
|
+
export const ATTR_TYPES = {
|
|
11
|
+
i32: v => Number.isInteger(v) && v >= -0x80000000 && v <= 0xffffffff,
|
|
12
|
+
i12: v => Number.isInteger(v) && v >= -2048 && v < 2048,
|
|
13
|
+
i8: v => Number.isInteger(v) && v >= -128 && v < 128,
|
|
14
|
+
u8: v => Number.isInteger(v) && v >= 0 && v < 256,
|
|
15
|
+
u5: v => Number.isInteger(v) && v >= 0 && v < 32,
|
|
16
|
+
u16: v => Number.isInteger(v) && v >= 0 && v < 65536,
|
|
17
|
+
int: v => Number.isInteger(v),
|
|
18
|
+
num: v => typeof v === 'number',
|
|
19
|
+
str: v => typeof v === 'string',
|
|
20
|
+
bool: v => typeof v === 'boolean',
|
|
21
|
+
any: () => true,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const baseType = t => (t.endsWith('?') ? t.slice(0, -1) : t);
|
|
25
|
+
const typeOk = (t, v) => (v === undefined ? t.endsWith('?') : ATTR_TYPES[baseType(t)](v));
|
|
26
|
+
|
|
27
|
+
/** Side tables (tk.attr) whose entries follow a value to its replacement, and all side tables (copied by clones). */
|
|
28
|
+
export const FOLLOWING = new Set();
|
|
29
|
+
export const ALL_ATTRS = new Set();
|
|
30
|
+
|
|
31
|
+
const RESERVED = new Set([
|
|
32
|
+
'id',
|
|
33
|
+
'op',
|
|
34
|
+
'args',
|
|
35
|
+
'attrs',
|
|
36
|
+
'uses',
|
|
37
|
+
'block',
|
|
38
|
+
'fn',
|
|
39
|
+
'targets',
|
|
40
|
+
'incomingBlocks',
|
|
41
|
+
'edgeArgc',
|
|
42
|
+
'name',
|
|
43
|
+
'loc',
|
|
44
|
+
'params',
|
|
45
|
+
]);
|
|
46
|
+
/** a deep copy of plain data (arrays, plain objects, primitives): structuredClone is missing in QuickJS */
|
|
47
|
+
const copyData = x =>
|
|
48
|
+
Array.isArray(x)
|
|
49
|
+
? x.map(copyData)
|
|
50
|
+
: x !== null && typeof x === 'object'
|
|
51
|
+
? Object.fromEntries(Object.entries(x).map(([k, v]) => [k, copyData(v)]))
|
|
52
|
+
: x;
|
|
53
|
+
const isPlain = x => x !== null && typeof x === 'object' && Object.getPrototypeOf(x) === Object.prototype;
|
|
54
|
+
const fmt = x => (typeof x === 'string' ? JSON.stringify(x) : String(x));
|
|
55
|
+
|
|
56
|
+
// ------------------------------------------------------------------ fragments
|
|
57
|
+
/** A fragment adds members to values (`op`), to builders (`builder`), or ops and setup to an IR (`define`). */
|
|
58
|
+
export class Fragment {
|
|
59
|
+
constructor(name) {
|
|
60
|
+
this.name = name;
|
|
61
|
+
this._op = {};
|
|
62
|
+
this._builder = {};
|
|
63
|
+
this._setup = [];
|
|
64
|
+
return strict(this, t => `fragment ${t.name}`);
|
|
65
|
+
}
|
|
66
|
+
/** members (methods, getters, fields) of every value the fragment is applied to; `this` is the value */
|
|
67
|
+
op(members) {
|
|
68
|
+
Object.assign(this._op, Object.getOwnPropertyDescriptors(members));
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
71
|
+
/** members of the IR's builders; `this` is the builder */
|
|
72
|
+
builder(members) {
|
|
73
|
+
Object.assign(this._builder, Object.getOwnPropertyDescriptors(members));
|
|
74
|
+
return this;
|
|
75
|
+
}
|
|
76
|
+
/** setup run once on the IR that uses the fragment, e.g. to define ops */
|
|
77
|
+
define(f) {
|
|
78
|
+
this._setup.push(f);
|
|
79
|
+
return this;
|
|
80
|
+
}
|
|
81
|
+
_install(ir) {
|
|
82
|
+
if (ir.fragments.includes(this)) return;
|
|
83
|
+
ir.fragments.push(this);
|
|
84
|
+
for (const f of this._setup) f(ir);
|
|
85
|
+
Object.defineProperties(ir.valueProto, this._op);
|
|
86
|
+
Object.defineProperties(ir.builderProto, this._builder);
|
|
87
|
+
}
|
|
88
|
+
_installOn(op) {
|
|
89
|
+
Object.defineProperties(op.proto, this._op);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ------------------------------------------------------------------ IR and ops
|
|
94
|
+
class Op {
|
|
95
|
+
constructor(ir, name, spec) {
|
|
96
|
+
this.ir = ir;
|
|
97
|
+
this.name = name;
|
|
98
|
+
this.spec = { ...spec };
|
|
99
|
+
this.proto = Object.create(ir.valueProto);
|
|
100
|
+
for (const a of Object.keys(spec.attrs ?? {}))
|
|
101
|
+
Object.defineProperty(this.proto, a, {
|
|
102
|
+
get() {
|
|
103
|
+
return this.attrs[a];
|
|
104
|
+
},
|
|
105
|
+
configurable: true,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
get args() {
|
|
109
|
+
return this.spec.args ?? 0;
|
|
110
|
+
}
|
|
111
|
+
get attrs() {
|
|
112
|
+
return this.spec.attrs ?? {};
|
|
113
|
+
}
|
|
114
|
+
get attrNames() {
|
|
115
|
+
return Object.keys(this.attrs);
|
|
116
|
+
}
|
|
117
|
+
get terminator() {
|
|
118
|
+
return !!this.spec.terminator;
|
|
119
|
+
}
|
|
120
|
+
/** does a value of this op (with these attrs) define a result? (spec.result: a boolean or a function of the attrs) */
|
|
121
|
+
hasResult(attrs) {
|
|
122
|
+
const r = this.spec.result;
|
|
123
|
+
if (r === undefined) return !this.spec.terminator;
|
|
124
|
+
return typeof r === 'function' ? !!r(attrs) : !!r;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export class IR {
|
|
129
|
+
constructor(name) {
|
|
130
|
+
this.name = name;
|
|
131
|
+
this.ops = new Map();
|
|
132
|
+
this.fragments = [];
|
|
133
|
+
this.valueProto = Object.create(Value.prototype);
|
|
134
|
+
// a builder's methods: Builder's, then one per op (opsProto), then the fragments' (builderProto), each layer
|
|
135
|
+
// hiding the one below, so a fragment's jump(edge) wins over the op jump, and an op cannot hide at(), id(), …
|
|
136
|
+
this.opsProto = Object.create(Builder.prototype);
|
|
137
|
+
this.builderProto = Object.create(this.opsProto);
|
|
138
|
+
this.hasBlocks = false;
|
|
139
|
+
this.machine = null;
|
|
140
|
+
this.constOp = null;
|
|
141
|
+
// everything refers to the IR through its proxy (ops, values, fragments): define the built-in param op through it
|
|
142
|
+
const self = strict(this, t => `IR ${t.name}`);
|
|
143
|
+
self._defineOp('param', { attrs: { index: 'int' } });
|
|
144
|
+
return self;
|
|
145
|
+
}
|
|
146
|
+
/** define an op: { args: count | '*', attrs: { name: type }, eval(args, attrs, ctx), effect, terminator, … } */
|
|
147
|
+
op(name, spec = {}) {
|
|
148
|
+
if (typeof name !== 'string' || !/^[A-Za-z_][\w.]*$/.test(name))
|
|
149
|
+
throw new TypeError(`op name ${describe(name)} is not an identifier`);
|
|
150
|
+
if (this.ops.has(name))
|
|
151
|
+
throw new TypeError(`${this.name} already has op '${name}': use .extend('${name}', { … })`);
|
|
152
|
+
this._defineOp(name, spec);
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
_defineOp(name, spec) {
|
|
156
|
+
const args = spec.args ?? 0;
|
|
157
|
+
if (args !== '*' && !(Number.isInteger(args) && args >= 0))
|
|
158
|
+
throw new TypeError(`op ${name}: args is a count or '*', got ${describe(args)}`);
|
|
159
|
+
for (const [a, t] of Object.entries(spec.attrs ?? {})) {
|
|
160
|
+
if (typeof t !== 'string' || !ATTR_TYPES[baseType(t)])
|
|
161
|
+
throw new TypeError(
|
|
162
|
+
`op ${name}: attr '${a}' has unknown type '${t}'${didYouMean(t, Object.keys(ATTR_TYPES))} ` +
|
|
163
|
+
`(types: ${Object.keys(ATTR_TYPES).join(', ')})`,
|
|
164
|
+
);
|
|
165
|
+
if (a in Value.prototype || RESERVED.has(a))
|
|
166
|
+
throw new TypeError(`op ${name}: attr '${a}' would hide the value member '${a}'`);
|
|
167
|
+
}
|
|
168
|
+
if (spec.eval !== undefined && typeof spec.eval !== 'function')
|
|
169
|
+
throw new TypeError(
|
|
170
|
+
`op ${name}: eval is a function (args, attrs, ctx) => value, got ${describe(spec.eval)}`,
|
|
171
|
+
);
|
|
172
|
+
const op = new Op(this, name, spec);
|
|
173
|
+
this.ops.set(name, op);
|
|
174
|
+
if (name !== 'param' && !(name in Builder.prototype))
|
|
175
|
+
this.opsProto[name] = function (...a) {
|
|
176
|
+
return this._make(op, a);
|
|
177
|
+
};
|
|
178
|
+
if (!this.constOp && (spec.constant || name === 'const') && args === 0 && op.attrNames.length === 1)
|
|
179
|
+
this.constOp = op;
|
|
180
|
+
}
|
|
181
|
+
get opNames() {
|
|
182
|
+
return [...this.ops.keys()].filter(n => n !== 'param');
|
|
183
|
+
}
|
|
184
|
+
opNamed(name) {
|
|
185
|
+
const op = this.ops.get(name);
|
|
186
|
+
if (!op)
|
|
187
|
+
throw new TypeError(
|
|
188
|
+
`${this.name} has no op '${name}'${didYouMean(name, this.opNames)} (ops: ${this.opNames.join(', ')})`,
|
|
189
|
+
);
|
|
190
|
+
return op;
|
|
191
|
+
}
|
|
192
|
+
/** apply fragments to every op of the IR */
|
|
193
|
+
use(...frags) {
|
|
194
|
+
for (const f of frags) {
|
|
195
|
+
if (!(f instanceof Fragment))
|
|
196
|
+
throw new TypeError(`use(…) takes fragments (tk.fragment(…), tk.frag.*), got ${describe(f)}`);
|
|
197
|
+
f._install(this);
|
|
198
|
+
}
|
|
199
|
+
return this;
|
|
200
|
+
}
|
|
201
|
+
/** add to some ops: a fragment (members), or a plain object (spec fields such as { cost: 3 }) */
|
|
202
|
+
extend(names, x) {
|
|
203
|
+
for (const n of [].concat(names)) {
|
|
204
|
+
const op = this.opNamed(n);
|
|
205
|
+
if (x instanceof Fragment) x._installOn(op);
|
|
206
|
+
else if (isPlain(x)) Object.assign(op.spec, x);
|
|
207
|
+
else throw new TypeError(`extend('${n}', …) takes a fragment or a plain object, got ${describe(x)}`);
|
|
208
|
+
}
|
|
209
|
+
return this;
|
|
210
|
+
}
|
|
211
|
+
/** a builder of free expressions (an IR without blocks) */
|
|
212
|
+
builder() {
|
|
213
|
+
return makeBuilder(this, Fn._expression(this), null, {});
|
|
214
|
+
}
|
|
215
|
+
module() {
|
|
216
|
+
return new Module(this);
|
|
217
|
+
}
|
|
218
|
+
/** evaluate a free expression with the ops' eval lambdas */
|
|
219
|
+
eval(v, ctx = {}) {
|
|
220
|
+
const memo = new Map();
|
|
221
|
+
const go = x => {
|
|
222
|
+
if (memo.has(x)) return memo.get(x);
|
|
223
|
+
const f = x.op.spec.eval;
|
|
224
|
+
if (!f) throw new TkError(`${this.name} op '${x.kind}' has no eval: give it one to run it`);
|
|
225
|
+
const r = f(x.args.map(go), x.attrs, ctx);
|
|
226
|
+
memo.set(x, r);
|
|
227
|
+
return r;
|
|
228
|
+
};
|
|
229
|
+
return go(v);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ------------------------------------------------------------------ values
|
|
234
|
+
const valueWhat = t => `${t.op.ir.name} value ${t.ref} (${t.op.name})`;
|
|
235
|
+
|
|
236
|
+
function newValue(op, fields) {
|
|
237
|
+
const raw = Object.create(op.proto);
|
|
238
|
+
Object.assign(
|
|
239
|
+
raw,
|
|
240
|
+
{
|
|
241
|
+
id: 0,
|
|
242
|
+
op,
|
|
243
|
+
args: [],
|
|
244
|
+
attrs: {},
|
|
245
|
+
uses: [],
|
|
246
|
+
block: null,
|
|
247
|
+
fn: null,
|
|
248
|
+
targets: null,
|
|
249
|
+
incomingBlocks: null,
|
|
250
|
+
edgeArgc: null,
|
|
251
|
+
name: null,
|
|
252
|
+
loc: null,
|
|
253
|
+
_origin: [],
|
|
254
|
+
_history: [],
|
|
255
|
+
_erased: false,
|
|
256
|
+
_cloneOf: null,
|
|
257
|
+
},
|
|
258
|
+
fields,
|
|
259
|
+
);
|
|
260
|
+
return strict(raw, valueWhat);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export class Value {
|
|
264
|
+
get kind() {
|
|
265
|
+
return this.op.name;
|
|
266
|
+
}
|
|
267
|
+
get spec() {
|
|
268
|
+
return this.op.spec;
|
|
269
|
+
}
|
|
270
|
+
get ir() {
|
|
271
|
+
return this.op.ir;
|
|
272
|
+
}
|
|
273
|
+
/** no effect and not a terminator: removable when unused, movable */
|
|
274
|
+
get pure() {
|
|
275
|
+
return (
|
|
276
|
+
!this.op.spec.effect && !this.op.spec.terminator && this.op.name !== 'phi' && this.op.name !== 'arg'
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
/** does this value define a result? (terminators, stores and the like do not, and take no id) */
|
|
280
|
+
get hasResult() {
|
|
281
|
+
return this.id !== null;
|
|
282
|
+
}
|
|
283
|
+
get ref() {
|
|
284
|
+
return this.name === null && this.id === null ? this.kind : '%' + (this.name ?? this.id);
|
|
285
|
+
}
|
|
286
|
+
get erased() {
|
|
287
|
+
return this._erased;
|
|
288
|
+
}
|
|
289
|
+
arg(i) {
|
|
290
|
+
if (!(i >= 0 && i < this.args.length))
|
|
291
|
+
throw new TypeError(
|
|
292
|
+
`${this.ref} (${this.kind}) has ${this.args.length} args: arg(${i}) does not exist`,
|
|
293
|
+
);
|
|
294
|
+
return this.args[i];
|
|
295
|
+
}
|
|
296
|
+
/** v.is('const'), v.is('const', { value: 2 }) */
|
|
297
|
+
is(kind, attrs) {
|
|
298
|
+
if (this.op.name !== kind) {
|
|
299
|
+
if (!this.ir.ops.has(kind))
|
|
300
|
+
throw new TypeError(
|
|
301
|
+
`is('${kind}'): ${this.ir.name} has no op '${kind}'${didYouMean(kind, this.ir.opNames)}`,
|
|
302
|
+
);
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
if (attrs) for (const k of Object.keys(attrs)) if (this.attrs[k] !== attrs[k]) return false;
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
named(n) {
|
|
309
|
+
this.name = n;
|
|
310
|
+
return this;
|
|
311
|
+
}
|
|
312
|
+
/** replace every use with x (a value, or a function of a builder placed before this value); then erase this */
|
|
313
|
+
replaceWith(x) {
|
|
314
|
+
const fn = this.fn;
|
|
315
|
+
fn._writable();
|
|
316
|
+
if (this._erased) throw new TkError(`${this.ref} (${this.kind}) was erased: it cannot be replaced`);
|
|
317
|
+
const by = currentBy();
|
|
318
|
+
const r =
|
|
319
|
+
typeof x === 'function'
|
|
320
|
+
? x(makeBuilder(this.ir, fn, this.block, { before: this, origin: [this], by }))
|
|
321
|
+
: x;
|
|
322
|
+
if (!(r instanceof Value))
|
|
323
|
+
throw new TypeError(`replaceWith(…) needs a value or a function returning one, got ${describe(r)}`);
|
|
324
|
+
if (r.fn !== fn) throw new TkError(`replaceWith: ${r.ref} belongs to ${r.fn.name}, not ${fn.name}`);
|
|
325
|
+
if (r === this) return r;
|
|
326
|
+
for (const u of [...this.uses]) u._swapArg(this, r);
|
|
327
|
+
for (const a of FOLLOWING) if (a.has(this) && !a.has(r)) a.set(r, a.get(this));
|
|
328
|
+
if (this.name && !r.name) r.name = this.name; // a name belongs to what the value computes
|
|
329
|
+
if (fn.root === this) fn.root = r;
|
|
330
|
+
this._detach(by, `replaced by ${r.ref}`);
|
|
331
|
+
fn._log(by, 'replace', this);
|
|
332
|
+
return r;
|
|
333
|
+
}
|
|
334
|
+
/** every use of this value reads x instead; this value stays, unused, for dce (replaceWith erases it at once) */
|
|
335
|
+
replaceUses(x) {
|
|
336
|
+
const fn = this.fn;
|
|
337
|
+
fn._writable();
|
|
338
|
+
if (!(x instanceof Value)) throw new TypeError(`replaceUses(…) needs a value, got ${describe(x)}`);
|
|
339
|
+
if (x.fn !== fn) throw new TkError(`replaceUses: ${x.ref} belongs to ${x.fn.name}, not ${fn.name}`);
|
|
340
|
+
if (x === this || !this.uses.length) return this;
|
|
341
|
+
const by = currentBy();
|
|
342
|
+
for (const u of [...this.uses]) u._swapArg(this, x);
|
|
343
|
+
this._history.push({ by, what: `uses moved to ${x.ref}` });
|
|
344
|
+
fn._log(by, 'replace-uses', this);
|
|
345
|
+
return this;
|
|
346
|
+
}
|
|
347
|
+
/** remove a value nothing uses */
|
|
348
|
+
erase() {
|
|
349
|
+
const fn = this.fn;
|
|
350
|
+
fn._writable();
|
|
351
|
+
if (this._erased) return;
|
|
352
|
+
if (this.uses.length) {
|
|
353
|
+
const users = this.uses.map(
|
|
354
|
+
u => (u.op.terminator ? u.kind : `${u.ref} (${u.kind})`) + (u.block ? ` in ${u.block.name}` : ''),
|
|
355
|
+
);
|
|
356
|
+
const n = this.uses.length;
|
|
357
|
+
throw new TkError(
|
|
358
|
+
`cannot erase ${this.ref} (${this.kind}): ${n === 1 ? '1 use remains' : `${n} uses remain`} ` +
|
|
359
|
+
`(${users.join(', ')}): replaceWith(…) first`,
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
const by = currentBy();
|
|
363
|
+
this._detach(by, 'erased');
|
|
364
|
+
fn._log(by, 'erase', this);
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* move to a block: before its terminator (or last, while it has none), or at { before: value } of that block. With
|
|
368
|
+
* { before }, the block may be the value's own (a move within the block).
|
|
369
|
+
*/
|
|
370
|
+
moveTo(block, at = {}) {
|
|
371
|
+
const fn = this.fn;
|
|
372
|
+
fn._writable();
|
|
373
|
+
if (block.fn !== fn)
|
|
374
|
+
throw new TkError(`moveTo: block ${block.name} is in ${block.fn.name}, not ${fn.name}`);
|
|
375
|
+
const before = at.before;
|
|
376
|
+
if (before !== undefined && (!(before instanceof Value) || before.block !== block))
|
|
377
|
+
throw new TkError(`moveTo: ${describe(before)} is not a value of block ${block.name}`);
|
|
378
|
+
if (before === this) return this;
|
|
379
|
+
if (this.block === block && before === undefined) return this;
|
|
380
|
+
this.block._values.splice(this.block._values.indexOf(this), 1);
|
|
381
|
+
const t = before ?? block.terminator;
|
|
382
|
+
if (t) block._values.splice(block._values.indexOf(t), 0, this);
|
|
383
|
+
else block._values.push(this);
|
|
384
|
+
this.block = block;
|
|
385
|
+
const by = currentBy();
|
|
386
|
+
this._history.push({ by, what: `moved to ${block.name}` });
|
|
387
|
+
fn._log(by, 'move', this);
|
|
388
|
+
return this;
|
|
389
|
+
}
|
|
390
|
+
/** set an attribute (undefined removes an optional one), checked against the op's attrs */
|
|
391
|
+
setAttr(name, v) {
|
|
392
|
+
this.fn._writable();
|
|
393
|
+
const names = this.op.attrNames;
|
|
394
|
+
if (!names.includes(name))
|
|
395
|
+
throw new TypeError(
|
|
396
|
+
`${this.kind} has no attr '${name}'${didYouMean(name, names)} (attrs: ${names.join(', ') || 'none'})`,
|
|
397
|
+
);
|
|
398
|
+
const t = this.op.attrs[name];
|
|
399
|
+
if (v === undefined ? !t.endsWith('?') : !typeOk(t, v))
|
|
400
|
+
throw new TypeError(`${this.kind}.${name} is ${t}, got ${describe(v)}`);
|
|
401
|
+
if (v === undefined) delete this.attrs[name];
|
|
402
|
+
else this.attrs[name] = v;
|
|
403
|
+
const by = currentBy();
|
|
404
|
+
this._history.push({ by, what: `attr ${name} set` });
|
|
405
|
+
this.fn._log(by, 'set-attr', this);
|
|
406
|
+
return this;
|
|
407
|
+
}
|
|
408
|
+
setArg(i, v) {
|
|
409
|
+
this.fn._writable();
|
|
410
|
+
const old = this.arg(i);
|
|
411
|
+
old.uses.splice(old.uses.indexOf(this), 1);
|
|
412
|
+
this.args[i] = v;
|
|
413
|
+
v.uses.push(this);
|
|
414
|
+
const by = currentBy();
|
|
415
|
+
this._history.push({ by, what: `arg ${i} set to ${v.ref}` });
|
|
416
|
+
this.fn._log(by, 'set-arg', this);
|
|
417
|
+
return this;
|
|
418
|
+
}
|
|
419
|
+
swapArgs() {
|
|
420
|
+
this.fn._writable();
|
|
421
|
+
if (this.args.length !== 2)
|
|
422
|
+
throw new TypeError(`swapArgs: ${this.ref} (${this.kind}) has ${this.args.length} args, not 2`);
|
|
423
|
+
this.args.reverse();
|
|
424
|
+
const by = currentBy();
|
|
425
|
+
this._history.push({ by, what: 'args swapped' });
|
|
426
|
+
this.fn._log(by, 'set-arg', this);
|
|
427
|
+
return this;
|
|
428
|
+
}
|
|
429
|
+
/** a free expression: run a pass on the graph this value is the root of; returns the (possibly new) root */
|
|
430
|
+
apply(pass) {
|
|
431
|
+
if (!this.fn.expr)
|
|
432
|
+
throw new TypeError(
|
|
433
|
+
`${this.ref} is in function ${this.fn.name}: apply passes to the function or module`,
|
|
434
|
+
);
|
|
435
|
+
this.fn.root = this;
|
|
436
|
+
applyPass(pass, this.fn);
|
|
437
|
+
return this.fn.root;
|
|
438
|
+
}
|
|
439
|
+
/** the values (or source records) this value was made from */
|
|
440
|
+
origin() {
|
|
441
|
+
return [...this._origin];
|
|
442
|
+
}
|
|
443
|
+
/** who did what to this value */
|
|
444
|
+
history() {
|
|
445
|
+
return this._history.map(e => (e.what === 'created' ? `created by ${e.by}` : `${e.by}: ${e.what}`));
|
|
446
|
+
}
|
|
447
|
+
trace() {
|
|
448
|
+
return trace(this);
|
|
449
|
+
}
|
|
450
|
+
_swapArg(old, nu) {
|
|
451
|
+
for (let i = 0; i < this.args.length; i++)
|
|
452
|
+
if (this.args[i] === old) {
|
|
453
|
+
this.args[i] = nu;
|
|
454
|
+
old.uses.splice(old.uses.indexOf(this), 1);
|
|
455
|
+
nu.uses.push(this);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
_detach(by, why) {
|
|
459
|
+
for (const a of this.args) {
|
|
460
|
+
const k = a.uses.indexOf(this);
|
|
461
|
+
if (k >= 0) a.uses.splice(k, 1);
|
|
462
|
+
}
|
|
463
|
+
if (this.block) this.block._values.splice(this.block._values.indexOf(this), 1);
|
|
464
|
+
else if (this.fn.expr) this.fn._exprValues.splice(this.fn._exprValues.indexOf(this), 1);
|
|
465
|
+
this._erased = true;
|
|
466
|
+
this._history.push({ by, what: why });
|
|
467
|
+
}
|
|
468
|
+
/** a free expression as a tree; a value in a function as an instruction */
|
|
469
|
+
toString() {
|
|
470
|
+
if (this.fn && this.fn.expr) {
|
|
471
|
+
const attrs = this.op.attrNames.map(k => fmt(this.attrs[k]));
|
|
472
|
+
if (!this.args.length) return attrs.length ? `${this.kind} ${attrs.join(' ')}` : this.kind;
|
|
473
|
+
return `${this.kind}(${[...this.args.map(a => String(a)), ...attrs].join(', ')})`;
|
|
474
|
+
}
|
|
475
|
+
if (this.op.spec.format) {
|
|
476
|
+
// an op that prints itself: format(value) gives the text after '=' (or the whole line, without a result)
|
|
477
|
+
const body = this.op.spec.format(this);
|
|
478
|
+
return this.hasResult ? `${this.ref} = ${body}` : body;
|
|
479
|
+
}
|
|
480
|
+
let parts;
|
|
481
|
+
if (this.incomingBlocks)
|
|
482
|
+
parts = [`[${this.args.map((a, i) => `${this.incomingBlocks[i].name}: ${a.ref}`).join(', ')}]`];
|
|
483
|
+
else {
|
|
484
|
+
const own = this.edgeArgc
|
|
485
|
+
? this.args.length - this.edgeArgc.reduce((a, b) => a + b, 0)
|
|
486
|
+
: this.args.length;
|
|
487
|
+
parts = this.args.slice(0, own).map(a => a.ref);
|
|
488
|
+
const names = this.op.attrNames.filter(k => this.attrs[k] !== undefined);
|
|
489
|
+
if (names.length === 1 && this.op.attrNames.length === 1) parts.push(fmt(this.attrs[names[0]]));
|
|
490
|
+
else for (const k of names) parts.push(`${k}=${fmt(this.attrs[k])}`);
|
|
491
|
+
}
|
|
492
|
+
if (this.targets) {
|
|
493
|
+
let at = this.args.length - (this.edgeArgc ? this.edgeArgc.reduce((a, b) => a + b, 0) : 0);
|
|
494
|
+
parts.push(
|
|
495
|
+
...this.targets.map((t, k) => {
|
|
496
|
+
if (!this.edgeArgc) return t.name;
|
|
497
|
+
const xs = this.args.slice(at, (at += this.edgeArgc[k]));
|
|
498
|
+
return `${t.name}(${xs.map(x => x.ref).join(', ')})`;
|
|
499
|
+
}),
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
const body = parts.length ? `${this.kind} ${parts.join(', ')}` : this.kind;
|
|
503
|
+
return this.hasResult ? `${this.ref} = ${body}` : body;
|
|
504
|
+
}
|
|
505
|
+
print() {
|
|
506
|
+
console.log(String(this));
|
|
507
|
+
return this;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// ------------------------------------------------------------------ blocks, functions, modules
|
|
512
|
+
export class Block {
|
|
513
|
+
constructor(fn, name) {
|
|
514
|
+
this.fn = fn;
|
|
515
|
+
this.name = name;
|
|
516
|
+
this._values = [];
|
|
517
|
+
return strict(this, t => `block ${t.name}`);
|
|
518
|
+
}
|
|
519
|
+
values() {
|
|
520
|
+
return [...this._values];
|
|
521
|
+
}
|
|
522
|
+
/** remove this block and everything in it (see fn.removeBlocks) */
|
|
523
|
+
remove() {
|
|
524
|
+
this.fn.removeBlocks([this]);
|
|
525
|
+
}
|
|
526
|
+
get terminator() {
|
|
527
|
+
const l = this._values[this._values.length - 1];
|
|
528
|
+
return l && l.op.terminator ? l : null;
|
|
529
|
+
}
|
|
530
|
+
get succs() {
|
|
531
|
+
return this.terminator?.targets ?? [];
|
|
532
|
+
}
|
|
533
|
+
get preds() {
|
|
534
|
+
return this.fn.blocks.filter(b => b.succs.includes(this));
|
|
535
|
+
}
|
|
536
|
+
/** the leading values of one kind (_insert keeps a block's parameters, and its phis, first) */
|
|
537
|
+
_leading(kind) {
|
|
538
|
+
const vs = this._values;
|
|
539
|
+
let n = 0;
|
|
540
|
+
while (n < vs.length && vs[n].kind === kind) n++;
|
|
541
|
+
return vs.slice(0, n);
|
|
542
|
+
}
|
|
543
|
+
get phis() {
|
|
544
|
+
return this._leading('phi');
|
|
545
|
+
}
|
|
546
|
+
/** the block's parameters (tk.frag.edges): values its incoming edges pass */
|
|
547
|
+
get params() {
|
|
548
|
+
return this._leading('arg');
|
|
549
|
+
}
|
|
550
|
+
/** an edge to this block, passing these values to its parameters (tk.frag.edges terminators take edges) */
|
|
551
|
+
to(...args) {
|
|
552
|
+
return { block: this, args };
|
|
553
|
+
}
|
|
554
|
+
_insert(v, before) {
|
|
555
|
+
if (before) {
|
|
556
|
+
const k = this._values.indexOf(before);
|
|
557
|
+
if (k < 0) throw new TkError(`${before.ref} is not in block ${this.name}`);
|
|
558
|
+
this._values.splice(k, 0, v);
|
|
559
|
+
} else if (v.kind === 'arg') {
|
|
560
|
+
this._values.splice(this.params.length, 0, v);
|
|
561
|
+
} else if (v.kind === 'phi') {
|
|
562
|
+
this._values.splice(this.phis.length, 0, v);
|
|
563
|
+
} else {
|
|
564
|
+
const t = this.terminator;
|
|
565
|
+
if (t) throw new TkError(`block ${this.name} already ends with ${t.kind}: b.at(another block) first`);
|
|
566
|
+
this._values.push(v);
|
|
567
|
+
}
|
|
568
|
+
v.block = this;
|
|
569
|
+
}
|
|
570
|
+
toString() {
|
|
571
|
+
return this.name;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
export class Fn {
|
|
576
|
+
constructor(module, name, ir, expr) {
|
|
577
|
+
this.module = module;
|
|
578
|
+
this.name = name;
|
|
579
|
+
this.ir = ir;
|
|
580
|
+
this.expr = expr;
|
|
581
|
+
this.blocks = [];
|
|
582
|
+
this.params = [];
|
|
583
|
+
this.entry = null;
|
|
584
|
+
this.root = null;
|
|
585
|
+
this.revision = 0;
|
|
586
|
+
this.cfgRevision = 0;
|
|
587
|
+
this._exprValues = [];
|
|
588
|
+
/** the id the next value with a result takes */
|
|
589
|
+
this.nextId = 0;
|
|
590
|
+
/** whatever a frontend keeps about the function (return count, flags, …) */
|
|
591
|
+
this.meta = {};
|
|
592
|
+
this._cache = new Map();
|
|
593
|
+
return strict(this, t => (t.expr ? 'expression graph' : `function ${t.name}`));
|
|
594
|
+
}
|
|
595
|
+
static _expression(ir) {
|
|
596
|
+
return new Fn(null, '(expression)', ir, true);
|
|
597
|
+
}
|
|
598
|
+
_writable() {
|
|
599
|
+
this.module?._writable();
|
|
600
|
+
}
|
|
601
|
+
_log(by, what, value) {
|
|
602
|
+
this.revision++;
|
|
603
|
+
if (what === 'block' || (value && value.op.terminator)) this.cfgRevision++;
|
|
604
|
+
if (this.module) {
|
|
605
|
+
this.module.revision++;
|
|
606
|
+
this.module.log.push({ fn: this.name, by, what, value });
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
_create(op, args, attrs, place) {
|
|
610
|
+
this._writable();
|
|
611
|
+
const by = place.by ?? currentBy();
|
|
612
|
+
const v = newValue(op, {
|
|
613
|
+
id: op.hasResult(attrs) ? (place.id ?? this.nextId++) : null,
|
|
614
|
+
args: [...args],
|
|
615
|
+
attrs: { ...attrs },
|
|
616
|
+
fn: this,
|
|
617
|
+
targets: place.targets ?? null,
|
|
618
|
+
edgeArgc: place.edgeArgc ?? null,
|
|
619
|
+
incomingBlocks: op.name === 'phi' ? [] : null,
|
|
620
|
+
loc: place.loc ?? null,
|
|
621
|
+
_origin: [...(place.origin ?? [])],
|
|
622
|
+
_history: [{ by, what: 'created' }],
|
|
623
|
+
});
|
|
624
|
+
for (const a of v.args) a.uses.push(v);
|
|
625
|
+
if (place.block) place.block._insert(v, place.before);
|
|
626
|
+
else if (this.expr) this._exprValues.push(v);
|
|
627
|
+
else if (op.name !== 'param')
|
|
628
|
+
throw new TkError(`no current block to put ${op.name} in: b.at(block) first`);
|
|
629
|
+
this._log(by, 'create', v);
|
|
630
|
+
return v;
|
|
631
|
+
}
|
|
632
|
+
/** erase values together: every use of each must be another of them (a dead set, whatever its order) */
|
|
633
|
+
eraseAll(values) {
|
|
634
|
+
this._writable();
|
|
635
|
+
const set = new Set(values);
|
|
636
|
+
for (const v of set) {
|
|
637
|
+
if (v.fn !== this) throw new TkError(`eraseAll: ${v.ref} belongs to ${v.fn.name}, not ${this.name}`);
|
|
638
|
+
const outside = v.uses.find(u => !set.has(u));
|
|
639
|
+
if (outside)
|
|
640
|
+
throw new TkError(
|
|
641
|
+
`eraseAll: ${v.ref} (${v.kind}) is used by ${outside.ref} (${outside.kind}), which is not erased with it`,
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
const by = currentBy();
|
|
645
|
+
for (const v of set) if (!v._erased) v._detach(by, 'erased');
|
|
646
|
+
for (const v of set) this._log(by, 'erase', v);
|
|
647
|
+
return set.size;
|
|
648
|
+
}
|
|
649
|
+
/** a builder on this function: at the end of a block (default: the entry), or just before a value */
|
|
650
|
+
builder(at = this.entry) {
|
|
651
|
+
this._writable();
|
|
652
|
+
if (at instanceof Value) {
|
|
653
|
+
if (at.fn !== this || !at.block)
|
|
654
|
+
throw new TkError(`builder: ${at.ref} is not a value in ${this.name}'s blocks`);
|
|
655
|
+
return makeBuilder(this.ir, this, at.block, { before: at, by: currentBy() });
|
|
656
|
+
}
|
|
657
|
+
if (!(at instanceof Block) || at.fn !== this)
|
|
658
|
+
throw new TypeError(`builder(…) takes a block or a value of ${this.name}, got ${describe(at)}`);
|
|
659
|
+
return makeBuilder(this.ir, this, at, { by: currentBy() });
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* remove blocks with everything in them. No block that stays may branch to one of them, and a value in them may be
|
|
663
|
+
* used only by values in them (the entry cannot go).
|
|
664
|
+
*/
|
|
665
|
+
removeBlocks(blocks) {
|
|
666
|
+
this._writable();
|
|
667
|
+
const set = new Set(blocks);
|
|
668
|
+
if (!set.size) return 0;
|
|
669
|
+
for (const b of set) {
|
|
670
|
+
if (b.fn !== this)
|
|
671
|
+
throw new TkError(`removeBlocks: block ${b.name} is in ${b.fn.name}, not ${this.name}`);
|
|
672
|
+
if (b === this.entry) throw new TkError(`removeBlocks: ${b.name} is the entry of ${this.name}`);
|
|
673
|
+
}
|
|
674
|
+
for (const b of this.blocks) {
|
|
675
|
+
if (set.has(b)) continue;
|
|
676
|
+
const to = b.succs.find(s => set.has(s));
|
|
677
|
+
if (to) throw new TkError(`removeBlocks: ${b.name} still branches to ${to.name}`);
|
|
678
|
+
}
|
|
679
|
+
this.eraseAll([...set].flatMap(b => b._values));
|
|
680
|
+
this.blocks = this.blocks.filter(b => !set.has(b));
|
|
681
|
+
this._log(currentBy(), 'block');
|
|
682
|
+
return set.size;
|
|
683
|
+
}
|
|
684
|
+
/** put the function's blocks in this order: the same blocks, each once, the entry first */
|
|
685
|
+
orderBlocks(blocks) {
|
|
686
|
+
this._writable();
|
|
687
|
+
const mine = new Set(this.blocks);
|
|
688
|
+
const given = new Set(blocks);
|
|
689
|
+
if (
|
|
690
|
+
blocks.length !== this.blocks.length ||
|
|
691
|
+
given.size !== blocks.length ||
|
|
692
|
+
blocks.some(b => !mine.has(b))
|
|
693
|
+
)
|
|
694
|
+
throw new TkError(`orderBlocks: not an order of the blocks of ${this.name}`);
|
|
695
|
+
if (blocks[0] !== this.entry)
|
|
696
|
+
throw new TkError(`orderBlocks: the entry ${this.entry.name} must stay first`);
|
|
697
|
+
this.blocks.splice(0, this.blocks.length, ...blocks);
|
|
698
|
+
this._log(currentBy(), 'order');
|
|
699
|
+
return this;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* a new block (it does not move the builder), last, or at { before: block } or { after: block }; a block put before
|
|
703
|
+
* the entry becomes the entry
|
|
704
|
+
*/
|
|
705
|
+
addBlock(name, at = {}) {
|
|
706
|
+
this._writable();
|
|
707
|
+
let n = name ?? `b${this.blocks.length}`;
|
|
708
|
+
while (this.blocks.some(b => b.name === n)) n += "'";
|
|
709
|
+
const b = new Block(this, n);
|
|
710
|
+
const ref = at.before ?? at.after;
|
|
711
|
+
if (ref === undefined) this.blocks.push(b);
|
|
712
|
+
else {
|
|
713
|
+
const k = this.blocks.indexOf(ref);
|
|
714
|
+
if (k < 0) throw new TkError(`addBlock: ${describe(ref)} is not a block of ${this.name}`);
|
|
715
|
+
this.blocks.splice(at.before ? k : k + 1, 0, b);
|
|
716
|
+
if (at.before === this.entry) this.entry = b;
|
|
717
|
+
}
|
|
718
|
+
this._log(currentBy(), 'block');
|
|
719
|
+
return b;
|
|
720
|
+
}
|
|
721
|
+
block(name) {
|
|
722
|
+
const b = this.blocks.find(x => x.name === name);
|
|
723
|
+
if (!b)
|
|
724
|
+
throw new TypeError(
|
|
725
|
+
`function ${this.name} has no block '${name}'${didYouMean(
|
|
726
|
+
name,
|
|
727
|
+
this.blocks.map(x => x.name),
|
|
728
|
+
)}`,
|
|
729
|
+
);
|
|
730
|
+
return b;
|
|
731
|
+
}
|
|
732
|
+
/** the values in block order (an expression graph: in creation order), optionally of one op */
|
|
733
|
+
values(kind) {
|
|
734
|
+
if (kind !== undefined) this.ir.opNamed(kind);
|
|
735
|
+
const all = this.expr ? [...this._exprValues] : this.blocks.flatMap(b => b._values);
|
|
736
|
+
return kind === undefined ? all : all.filter(v => v.kind === kind);
|
|
737
|
+
}
|
|
738
|
+
get size() {
|
|
739
|
+
return this.values().length;
|
|
740
|
+
}
|
|
741
|
+
/** the block graph, as a view the standard library's graph algorithms take */
|
|
742
|
+
get graph() {
|
|
743
|
+
return { nodes: this.blocks, entry: this.entry, succ: b => b.succs };
|
|
744
|
+
}
|
|
745
|
+
/** an analysis' result for this revision (computed once, then cached) */
|
|
746
|
+
get(analysis) {
|
|
747
|
+
const compute = typeof analysis === 'function' ? analysis : analysis?.compute;
|
|
748
|
+
if (typeof compute !== 'function')
|
|
749
|
+
throw new TypeError(
|
|
750
|
+
`get(…) needs an analysis (tk.analysis(…) or a function of a function), got ${describe(analysis)}`,
|
|
751
|
+
);
|
|
752
|
+
const name = analysis.analysisName ?? analysis.name ?? 'analysis';
|
|
753
|
+
const rev = () => (analysis.on === 'cfg' ? this.cfgRevision : this.revision);
|
|
754
|
+
const c = this._cache.get(analysis);
|
|
755
|
+
if (c && c.rev === rev()) return c.result;
|
|
756
|
+
const at = rev();
|
|
757
|
+
const result = guard(compute(this), () => {
|
|
758
|
+
if (rev() !== at)
|
|
759
|
+
throw new TkError(
|
|
760
|
+
`${name} of ${this.name} is from revision ${at}, and ${this.name} is now at revision ${rev()}: ` +
|
|
761
|
+
`call ${this.name}.get(${name}) again`,
|
|
762
|
+
);
|
|
763
|
+
});
|
|
764
|
+
this._cache.set(analysis, { rev: at, result });
|
|
765
|
+
return result;
|
|
766
|
+
}
|
|
767
|
+
apply(pass) {
|
|
768
|
+
applyPass(pass, this);
|
|
769
|
+
return this;
|
|
770
|
+
}
|
|
771
|
+
_cloneInto(module) {
|
|
772
|
+
const g = new Fn(module, this.name, this.ir, false);
|
|
773
|
+
const map = new Map();
|
|
774
|
+
const bmap = new Map();
|
|
775
|
+
for (const b of this.blocks) {
|
|
776
|
+
const nb = new Block(g, b.name);
|
|
777
|
+
g.blocks.push(nb);
|
|
778
|
+
bmap.set(b, nb);
|
|
779
|
+
}
|
|
780
|
+
g.entry = bmap.get(this.entry);
|
|
781
|
+
const copy = v => {
|
|
782
|
+
const c = newValue(v.op, {
|
|
783
|
+
id: v.id,
|
|
784
|
+
attrs: { ...v.attrs },
|
|
785
|
+
fn: g,
|
|
786
|
+
name: v.name,
|
|
787
|
+
loc: v.loc,
|
|
788
|
+
_origin: [v],
|
|
789
|
+
_history: [],
|
|
790
|
+
_cloneOf: v,
|
|
791
|
+
});
|
|
792
|
+
for (const a of ALL_ATTRS) if (a.has(v)) a.set(c, a.get(v));
|
|
793
|
+
map.set(v, c);
|
|
794
|
+
return c;
|
|
795
|
+
};
|
|
796
|
+
g.params = this.params.map(copy);
|
|
797
|
+
for (const b of this.blocks)
|
|
798
|
+
for (const v of b._values) {
|
|
799
|
+
const c = copy(v);
|
|
800
|
+
c.block = bmap.get(b);
|
|
801
|
+
c.block._values.push(c);
|
|
802
|
+
}
|
|
803
|
+
for (const [v, c] of map) {
|
|
804
|
+
c.args = v.args.map(a => map.get(a));
|
|
805
|
+
for (const a of c.args) a.uses.push(c);
|
|
806
|
+
c.targets = v.targets ? v.targets.map(t => bmap.get(t)) : null;
|
|
807
|
+
c.incomingBlocks = v.incomingBlocks ? v.incomingBlocks.map(t => bmap.get(t)) : null;
|
|
808
|
+
c.edgeArgc = v.edgeArgc ? [...v.edgeArgc] : null;
|
|
809
|
+
}
|
|
810
|
+
g.nextId = this.nextId;
|
|
811
|
+
g.meta = copyData(this.meta);
|
|
812
|
+
return g;
|
|
813
|
+
}
|
|
814
|
+
toString() {
|
|
815
|
+
const lines = [`fn ${this.name}(${this.params.map(p => p.ref).join(', ')}) {`];
|
|
816
|
+
for (const b of this.blocks) {
|
|
817
|
+
lines.push(` ${b.name}:`);
|
|
818
|
+
for (const v of b._values) lines.push(` ${v}`);
|
|
819
|
+
}
|
|
820
|
+
lines.push('}');
|
|
821
|
+
return lines.join('\n');
|
|
822
|
+
}
|
|
823
|
+
print() {
|
|
824
|
+
console.log(String(this));
|
|
825
|
+
return this;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
export class Module {
|
|
830
|
+
constructor(ir) {
|
|
831
|
+
this.ir = ir;
|
|
832
|
+
this.revision = 0;
|
|
833
|
+
this.log = [];
|
|
834
|
+
this.readOnly = false;
|
|
835
|
+
this.label = 'module';
|
|
836
|
+
this.choices = [];
|
|
837
|
+
this._fns = new Map();
|
|
838
|
+
this._snapFrom = null;
|
|
839
|
+
this._snapLog = 0;
|
|
840
|
+
/** whatever a frontend keeps about the module (globals, …) */
|
|
841
|
+
this.meta = {};
|
|
842
|
+
return strict(this, t => `${t.ir.name} module`);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* fn(name) finds a function; fn(name, params, (b, ...params) => { … }, opts?) defines one. opts.entry names the entry
|
|
846
|
+
* block; opts.ids gives the parameters' ids (as an importer needs).
|
|
847
|
+
*/
|
|
848
|
+
fn(name, params, body, opts = {}) {
|
|
849
|
+
if (params === undefined) {
|
|
850
|
+
const f = this._fns.get(name);
|
|
851
|
+
if (!f)
|
|
852
|
+
throw new TypeError(`module has no function '${name}'${didYouMean(name, [...this._fns.keys()])}`);
|
|
853
|
+
return f;
|
|
854
|
+
}
|
|
855
|
+
if (!this.ir.hasBlocks)
|
|
856
|
+
throw new TypeError(`${this.ir.name} has no blocks: .use(tk.frag.cfg) to define functions`);
|
|
857
|
+
if (this._fns.has(name)) throw new TypeError(`module already has a function '${name}'`);
|
|
858
|
+
const f = new Fn(this, name, this.ir, false);
|
|
859
|
+
withBy('build', () => {
|
|
860
|
+
f.entry = f.addBlock(opts.entry ?? 'entry');
|
|
861
|
+
f.params = params.map((p, i) => {
|
|
862
|
+
const v = f._create(this.ir.ops.get('param'), [], { index: i }, { id: opts.ids?.[i] });
|
|
863
|
+
return p === null ? v : v.named(p);
|
|
864
|
+
});
|
|
865
|
+
if (body) body(makeBuilder(this.ir, f, f.entry, { by: 'build' }), ...f.params);
|
|
866
|
+
});
|
|
867
|
+
this._fns.set(name, f);
|
|
868
|
+
return f;
|
|
869
|
+
}
|
|
870
|
+
get fns() {
|
|
871
|
+
return [...this._fns.values()];
|
|
872
|
+
}
|
|
873
|
+
_writable() {
|
|
874
|
+
if (this.readOnly)
|
|
875
|
+
throw new TkError(`snapshot ${this.label} is read-only: .clone() gives an editable copy`);
|
|
876
|
+
}
|
|
877
|
+
/** remove a function from the module */
|
|
878
|
+
remove(name) {
|
|
879
|
+
this._writable();
|
|
880
|
+
this.fn(name);
|
|
881
|
+
this._fns.delete(name);
|
|
882
|
+
this.revision++;
|
|
883
|
+
this.log.push({ fn: name, by: currentBy(), what: 'remove' });
|
|
884
|
+
return this;
|
|
885
|
+
}
|
|
886
|
+
get size() {
|
|
887
|
+
return this.fns.reduce((n, f) => n + f.size, 0);
|
|
888
|
+
}
|
|
889
|
+
apply(pass) {
|
|
890
|
+
applyPass(pass, this);
|
|
891
|
+
return this;
|
|
892
|
+
}
|
|
893
|
+
/** run a function with the ops' eval lambdas (control flow through the terminators' control lambdas) */
|
|
894
|
+
run(name, args = [], ctx = {}) {
|
|
895
|
+
const f = this.fn(name);
|
|
896
|
+
const env = new Map(f.params.map((p, i) => [p, args[i]]));
|
|
897
|
+
const val = (x, at) => {
|
|
898
|
+
if (!env.has(x)) throw new TkError(`${at.ref} (${at.kind}) reads ${x.ref} before it is computed`);
|
|
899
|
+
return env.get(x);
|
|
900
|
+
};
|
|
901
|
+
let blk = f.entry;
|
|
902
|
+
let prev = null;
|
|
903
|
+
let passed = [];
|
|
904
|
+
let fuel = ctx.fuel ?? 10_000_000;
|
|
905
|
+
for (;;) {
|
|
906
|
+
blk.params.forEach((p, i) => env.set(p, passed[i]));
|
|
907
|
+
const phis = blk.phis;
|
|
908
|
+
const incoming = phis.map(p => {
|
|
909
|
+
const k = p.incomingBlocks.indexOf(prev);
|
|
910
|
+
if (k < 0)
|
|
911
|
+
throw new TkError(
|
|
912
|
+
`phi ${p.ref} in ${blk.name} has no value for the edge from ${prev ? prev.name : 'the start'}`,
|
|
913
|
+
);
|
|
914
|
+
return val(p.args[k], p);
|
|
915
|
+
});
|
|
916
|
+
phis.forEach((p, i) => env.set(p, incoming[i]));
|
|
917
|
+
let next = null;
|
|
918
|
+
for (const v of blk._values) {
|
|
919
|
+
if (v.kind === 'phi' || v.kind === 'arg') continue;
|
|
920
|
+
if (--fuel < 0) throw new TkError(`run ${name}: out of fuel (ctx.fuel) in block ${blk.name}`);
|
|
921
|
+
const a = v.args.map(x => val(x, v));
|
|
922
|
+
if (v.op.terminator) {
|
|
923
|
+
const nEdge = v.edgeArgc ? v.edgeArgc.reduce((x, y) => x + y, 0) : 0;
|
|
924
|
+
const c = v.op.spec.control(a.slice(0, a.length - nEdge), v.targets ?? [], ctx, v);
|
|
925
|
+
if (c && typeof c === 'object' && 'ret' in c) return c.ret;
|
|
926
|
+
if (typeof c === 'number') {
|
|
927
|
+
// an edge index (tk.frag.edges): its values go to the target's parameters
|
|
928
|
+
let at = a.length - nEdge;
|
|
929
|
+
for (let k = 0; k < c; k++) at += v.edgeArgc[k];
|
|
930
|
+
passed = a.slice(at, at + v.edgeArgc[c]);
|
|
931
|
+
next = v.targets[c];
|
|
932
|
+
} else {
|
|
933
|
+
passed = [];
|
|
934
|
+
next = c;
|
|
935
|
+
}
|
|
936
|
+
break;
|
|
937
|
+
}
|
|
938
|
+
if (!v.op.spec.eval)
|
|
939
|
+
throw new TkError(`${this.ir.name} op '${v.kind}' has no eval: give it one to run it`);
|
|
940
|
+
env.set(v, v.op.spec.eval(a, v.attrs, ctx));
|
|
941
|
+
}
|
|
942
|
+
if (!next) throw new TkError(`block ${blk.name} of ${name} has no terminator`);
|
|
943
|
+
prev = blk;
|
|
944
|
+
blk = next;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
/** an editable copy; every value's origin is the value it copies */
|
|
948
|
+
clone() {
|
|
949
|
+
const m = new Module(this.ir);
|
|
950
|
+
for (const f of this.fns) m._fns.set(f.name, f._cloneInto(m));
|
|
951
|
+
m.meta = copyData(this.meta);
|
|
952
|
+
return m;
|
|
953
|
+
}
|
|
954
|
+
/** a read-only copy that diff() compares against */
|
|
955
|
+
snapshot() {
|
|
956
|
+
const s = this.clone();
|
|
957
|
+
s.readOnly = true;
|
|
958
|
+
s.label = `r${this.revision}`;
|
|
959
|
+
s._snapFrom = this;
|
|
960
|
+
s._snapLog = this.log.length;
|
|
961
|
+
return s;
|
|
962
|
+
}
|
|
963
|
+
/** what happened since a snapshot of this module, by function and by pass */
|
|
964
|
+
diff(snap) {
|
|
965
|
+
if (!snap || snap._snapFrom !== this)
|
|
966
|
+
throw new TypeError('diff(…) takes a snapshot of this module (module.snapshot())');
|
|
967
|
+
const events = this.log.slice(snap._snapLog);
|
|
968
|
+
const lines = [];
|
|
969
|
+
for (const f of this.fns) {
|
|
970
|
+
const before = snap._fns.has(f.name) ? snap.fn(f.name).size : 0;
|
|
971
|
+
const mine = events.filter(e => e.fn === f.name && e.what !== 'block');
|
|
972
|
+
if (!mine.length) continue;
|
|
973
|
+
lines.push(`${f.name} ${before} -> ${f.size} values`);
|
|
974
|
+
const by = new Map();
|
|
975
|
+
for (const e of mine) {
|
|
976
|
+
const m = by.get(e.by) ?? new Map();
|
|
977
|
+
m.set(e.what, (m.get(e.what) ?? 0) + 1);
|
|
978
|
+
by.set(e.by, m);
|
|
979
|
+
}
|
|
980
|
+
for (const [who, m] of by) lines.push(` ${who}: ${[...m].map(([w, n]) => `${w} ${n}`).join(', ')}`);
|
|
981
|
+
}
|
|
982
|
+
const text = lines.join('\n');
|
|
983
|
+
return {
|
|
984
|
+
events,
|
|
985
|
+
toString: () => text,
|
|
986
|
+
print() {
|
|
987
|
+
console.log(text);
|
|
988
|
+
return this;
|
|
989
|
+
},
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
/** take another module's functions (tk.choose keeps the winner this way) */
|
|
993
|
+
adopt(other) {
|
|
994
|
+
this._writable();
|
|
995
|
+
this._fns = new Map(other._fns);
|
|
996
|
+
for (const f of this.fns) f.module = this;
|
|
997
|
+
this.revision++;
|
|
998
|
+
this.log.push({ fn: '*', by: currentBy(), what: 'adopt' });
|
|
999
|
+
return this;
|
|
1000
|
+
}
|
|
1001
|
+
toString() {
|
|
1002
|
+
return this.fns.map(String).join('\n');
|
|
1003
|
+
}
|
|
1004
|
+
print() {
|
|
1005
|
+
console.log(String(this));
|
|
1006
|
+
return this;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
// ------------------------------------------------------------------ builders
|
|
1011
|
+
export class Builder {
|
|
1012
|
+
get current() {
|
|
1013
|
+
return this._cur;
|
|
1014
|
+
}
|
|
1015
|
+
get entry() {
|
|
1016
|
+
return this.fn.entry;
|
|
1017
|
+
}
|
|
1018
|
+
/** continue at the end of a block */
|
|
1019
|
+
at(block) {
|
|
1020
|
+
if (block.fn !== this.fn)
|
|
1021
|
+
throw new TkError(`at(${block.name}): the block belongs to ${block.fn.name}, not ${this.fn.name}`);
|
|
1022
|
+
this._cur = block;
|
|
1023
|
+
this._before = null;
|
|
1024
|
+
return this.self;
|
|
1025
|
+
}
|
|
1026
|
+
/** insert before a value */
|
|
1027
|
+
before(v) {
|
|
1028
|
+
this._cur = v.block;
|
|
1029
|
+
this._before = v;
|
|
1030
|
+
return this.self;
|
|
1031
|
+
}
|
|
1032
|
+
/** a new block in the function (the builder stays where it is) */
|
|
1033
|
+
/** a new block of the function (see fn.addBlock: last, or at { before } / { after }) */
|
|
1034
|
+
block(name, at) {
|
|
1035
|
+
return this.fn.addBlock(name, at);
|
|
1036
|
+
}
|
|
1037
|
+
/** the id the next value takes (an importer keeps the numbering it reads) */
|
|
1038
|
+
id(n) {
|
|
1039
|
+
this._id = n;
|
|
1040
|
+
return this.self;
|
|
1041
|
+
}
|
|
1042
|
+
/** the source position the next values come from (shows at the end of a trace); loc(null) forgets it */
|
|
1043
|
+
loc(where, text) {
|
|
1044
|
+
this._loc = where === null || where === undefined ? null : { where, text: text ?? '' };
|
|
1045
|
+
return this.self;
|
|
1046
|
+
}
|
|
1047
|
+
_make(op, a, extra = {}) {
|
|
1048
|
+
let n = 0;
|
|
1049
|
+
while (n < a.length && a[n] instanceof Value) n++;
|
|
1050
|
+
if (op.args !== '*' && n !== op.args)
|
|
1051
|
+
throw new TypeError(`${op.name} takes ${op.args} arg${op.args === 1 ? '' : 's'}, got ${n}`);
|
|
1052
|
+
const args = a.slice(0, n);
|
|
1053
|
+
const rest = a.slice(n);
|
|
1054
|
+
const names = op.attrNames;
|
|
1055
|
+
let attrs = {};
|
|
1056
|
+
if (rest.length === 1 && isPlain(rest[0])) {
|
|
1057
|
+
attrs = rest[0];
|
|
1058
|
+
for (const k of Object.keys(attrs))
|
|
1059
|
+
if (!names.includes(k))
|
|
1060
|
+
throw new TypeError(
|
|
1061
|
+
`${op.name} has no attr '${k}'${didYouMean(k, names)} (attrs: ${names.join(', ') || 'none'})`,
|
|
1062
|
+
);
|
|
1063
|
+
} else if (rest.length === names.length) {
|
|
1064
|
+
names.forEach((k, i) => (attrs[k] = rest[i]));
|
|
1065
|
+
} else if (rest.length) {
|
|
1066
|
+
throw new TypeError(
|
|
1067
|
+
`${op.name} takes ${op.args} args and the attrs {${names.join(', ')}}; got ${describe(rest[0])} after the args`,
|
|
1068
|
+
);
|
|
1069
|
+
}
|
|
1070
|
+
for (const k of names) {
|
|
1071
|
+
const t = op.attrs[k];
|
|
1072
|
+
if (attrs[k] === undefined && !t.endsWith('?'))
|
|
1073
|
+
throw new TypeError(`${op.name} needs attr '${k}' (${t})`);
|
|
1074
|
+
if (!typeOk(t, attrs[k])) throw new TypeError(`${op.name}.${k} is ${t}, got ${describe(attrs[k])}`);
|
|
1075
|
+
}
|
|
1076
|
+
for (const v of args) {
|
|
1077
|
+
if (v.ir !== this.ir)
|
|
1078
|
+
throw new TkError(`${v.ref} is a ${v.ir.name} value: a ${this.ir.name} builder cannot use it`);
|
|
1079
|
+
if (v.fn !== this.fn)
|
|
1080
|
+
throw new TkError(
|
|
1081
|
+
`${v.ref} (${v.kind}) belongs to another ${v.fn.expr ? 'builder' : `function, ${v.fn.name}`}`,
|
|
1082
|
+
);
|
|
1083
|
+
if (v._erased) throw new TkError(`${v.ref} (${v.kind}) was erased`);
|
|
1084
|
+
}
|
|
1085
|
+
const id = this._id;
|
|
1086
|
+
this._id = undefined;
|
|
1087
|
+
return this.fn._create(op, args, attrs, {
|
|
1088
|
+
block: this._cur,
|
|
1089
|
+
before: this._before,
|
|
1090
|
+
origin: this._origin,
|
|
1091
|
+
by: this._by,
|
|
1092
|
+
loc: this._loc,
|
|
1093
|
+
id,
|
|
1094
|
+
...extra,
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/** A builder: its methods are the IR's op names (opsProto); with checks on, it is a proxy that turns any other name into
|
|
1100
|
+
* an error listing the ops. */
|
|
1101
|
+
export function makeBuilder(ir, fn, block, o) {
|
|
1102
|
+
const raw = Object.create(ir.builderProto);
|
|
1103
|
+
Object.assign(raw, {
|
|
1104
|
+
ir,
|
|
1105
|
+
fn,
|
|
1106
|
+
self: null,
|
|
1107
|
+
_cur: block,
|
|
1108
|
+
_before: o.before ?? null,
|
|
1109
|
+
_origin: o.origin ?? [],
|
|
1110
|
+
_by: o.by ?? null,
|
|
1111
|
+
_loc: o.loc ?? null,
|
|
1112
|
+
_id: undefined,
|
|
1113
|
+
});
|
|
1114
|
+
if (!checks()) {
|
|
1115
|
+
raw.self = raw;
|
|
1116
|
+
return raw;
|
|
1117
|
+
}
|
|
1118
|
+
const p = new Proxy(raw, {
|
|
1119
|
+
get(t, k, r) {
|
|
1120
|
+
if (typeof k === 'symbol' || k in t) return Reflect.get(t, k, r);
|
|
1121
|
+
if (PROBES.has(k)) return undefined;
|
|
1122
|
+
throw new TypeError(
|
|
1123
|
+
`${ir.name} has no op '${k}'${didYouMean(k, [...ir.opNames, ...memberNames(t)])} (ops: ${ir.opNames.join(', ')})`,
|
|
1124
|
+
);
|
|
1125
|
+
},
|
|
1126
|
+
});
|
|
1127
|
+
raw.self = p;
|
|
1128
|
+
return p;
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// ------------------------------------------------------------------ passes, analyses, provenance
|
|
1132
|
+
/** run anything with applyTo(target) on a module, a function or an expression graph */
|
|
1133
|
+
export function applyPass(pass, target) {
|
|
1134
|
+
if (!pass || typeof pass.applyTo !== 'function')
|
|
1135
|
+
throw new TypeError(`apply(…) takes a pass (tk.pass, tk.seq, a lowering, …), got ${describe(pass)}`);
|
|
1136
|
+
return pass.applyTo(target);
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* with checks on, an analysis result that throws once its function has changed (Map, Set and arrays keep working); its
|
|
1141
|
+
* methods check again when called, so one taken out before a change (const { dominates } = …) throws after it too
|
|
1142
|
+
*/
|
|
1143
|
+
function guard(res, check) {
|
|
1144
|
+
if (!checks() || res === null || (typeof res !== 'object' && typeof res !== 'function')) return res;
|
|
1145
|
+
return new Proxy(res, {
|
|
1146
|
+
get(t, k) {
|
|
1147
|
+
check();
|
|
1148
|
+
const v = Reflect.get(t, k, t);
|
|
1149
|
+
return typeof v === 'function'
|
|
1150
|
+
? (...a) => {
|
|
1151
|
+
check();
|
|
1152
|
+
return Reflect.apply(v, t, a);
|
|
1153
|
+
}
|
|
1154
|
+
: v;
|
|
1155
|
+
},
|
|
1156
|
+
apply(t, self, a) {
|
|
1157
|
+
check();
|
|
1158
|
+
return Reflect.apply(t, self, a);
|
|
1159
|
+
},
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
/** the chain of values (and the source) a value came from, newest first; clones are the same entity */
|
|
1164
|
+
export function trace(v) {
|
|
1165
|
+
const rows = [];
|
|
1166
|
+
const seen = new Set();
|
|
1167
|
+
let cur = v;
|
|
1168
|
+
while (cur && !seen.has(cur)) {
|
|
1169
|
+
seen.add(cur);
|
|
1170
|
+
const text = String(cur);
|
|
1171
|
+
let events = [...cur._history];
|
|
1172
|
+
let base = cur;
|
|
1173
|
+
while (base._cloneOf) {
|
|
1174
|
+
base = base._cloneOf;
|
|
1175
|
+
seen.add(base);
|
|
1176
|
+
events = [...base._history, ...events];
|
|
1177
|
+
}
|
|
1178
|
+
const how = [];
|
|
1179
|
+
for (const e of events) {
|
|
1180
|
+
// building is the default; being replaced or erased is what the row above already shows
|
|
1181
|
+
if (e.by === 'build' || e.what === 'erased' || e.what.startsWith('replaced by')) continue;
|
|
1182
|
+
const s = e.what === 'created' ? e.by : `${e.by}: ${e.what}`;
|
|
1183
|
+
if (how[how.length - 1] !== s) how.push(s);
|
|
1184
|
+
}
|
|
1185
|
+
rows.push({ ir: cur.ir.name, text, how: how.join('; ') });
|
|
1186
|
+
if (!base._origin.length && base.loc)
|
|
1187
|
+
rows.push({ ir: 'source', text: base.loc.text, how: base.loc.where });
|
|
1188
|
+
cur = base._origin[0] ?? null;
|
|
1189
|
+
}
|
|
1190
|
+
return traceOf(rows);
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
export function traceOf(rows) {
|
|
1194
|
+
const w = Math.max(...rows.map(r => r.text.length));
|
|
1195
|
+
const text = rows.map(r => `${r.ir.padEnd(7)} ${r.text.padEnd(w)} ${r.how}`.trimEnd()).join('\n');
|
|
1196
|
+
return {
|
|
1197
|
+
rows,
|
|
1198
|
+
toString: () => text,
|
|
1199
|
+
print() {
|
|
1200
|
+
console.log(text);
|
|
1201
|
+
return this;
|
|
1202
|
+
},
|
|
1203
|
+
};
|
|
1204
|
+
}
|