@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/docs/guide.md ADDED
@@ -0,0 +1,1672 @@
1
+ # The toolkit guide
2
+
3
+ This is the toolkit's manual. It is organised by task: each section explains one part of the
4
+ toolkit and shows it in examples that run against the current code, and the last section lists every public function
5
+ and option. For a short introduction, read [the README](../README.md) first. For the reasons behind the design, read
6
+ [the design doc](design.md).
7
+
8
+ ## Contents
9
+
10
+ 1. [Setting up](#1-setting-up)
11
+ 2. [Defining an IR and its ops](#2-defining-an-ir-and-its-ops)
12
+ 3. [Fragments](#3-fragments)
13
+ 4. [Building functions](#4-building-functions)
14
+ 5. [Values and the mutations](#5-values-and-the-mutations)
15
+ 6. [Passes](#6-passes)
16
+ 7. [Rewrite rules](#7-rewrite-rules)
17
+ 8. [Combining passes](#8-combining-passes)
18
+ 9. [Analyses and the revision cache](#9-analyses-and-the-revision-cache)
19
+ 10. [Lowering to a machine IR](#10-lowering-to-a-machine-ir)
20
+ 11. [The standard library](#11-the-standard-library)
21
+ 12. [Modules, snapshots, diffs and side tables](#12-modules-snapshots-diffs-and-side-tables)
22
+ 13. [Provenance and traces](#13-provenance-and-traces)
23
+ 14. [The stage graph](#14-the-stage-graph)
24
+ 15. [The checks mode](#15-the-checks-mode)
25
+ 16. [Running under QuickJS](#16-running-under-quickjs)
26
+ 17. [Reference](#17-reference)
27
+
28
+ ## 1. Setting up
29
+
30
+ The toolkit is plain ES modules with no dependencies and no build step. It runs under node 22 or later, and under
31
+ QuickJS (section 16). Install it with `npm install @go-go-golems/compiler-toolkit` and import it like this (in a
32
+ clone of the repository, import `./src/index.js` instead):
33
+
34
+ ```js
35
+ import { tk } from '@go-go-golems/compiler-toolkit';
36
+ ```
37
+
38
+ `tk` is the whole API. The module also exports `TkError`, the class of the toolkit's own errors.
39
+
40
+ Each section of this guide is one program: its examples run in order and build on each other. Every section also
41
+ starts from the definitions marked `// used in the rest of this guide`, which are given once, where they are
42
+ explained. The first of them is the running example: `Mini`, a small IR with control flow and phis, and `sum`, which
43
+ builds a loop that adds the numbers below `n`.
44
+
45
+ ```js
46
+ // used in the rest of this guide
47
+ const Mini = tk.ir('mini')
48
+ .use(tk.frag.cfg, tk.frag.ssa)
49
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
50
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
51
+ .op('mul', { args: 2, eval: ([a, b]) => Math.imul(a, b) })
52
+ .op('shl', { args: 2, eval: ([a, b]) => a << b })
53
+ .op('lt', { args: 2, eval: ([a, b]) => +(a < b) })
54
+ .op('load', { args: 1, effect: 'read', eval: ([p], _, ctx) => ctx.mem[p] ?? 0 })
55
+ .op('store', { args: 2, effect: 'write', result: false, eval: ([p, x], _, ctx) => void (ctx.mem[p] = x) });
56
+
57
+ /** sum(n) = 0 + 1 + … + (n - 1), as a loop */
58
+ function sum(mod) {
59
+ return mod.fn('sum', ['n'], (b, n) => {
60
+ const entry = b.current, head = b.block('head'), body = b.block('body'), exit = b.block('exit');
61
+ const zero = b.const(0);
62
+ b.br(head).at(head);
63
+ const i = b.phi().named('i'), s = b.phi().named('s');
64
+ b.cbr(b.lt(i, n), body, exit).at(body);
65
+ const i1 = b.add(i, b.const(1)).named('i1'), s1 = b.add(s, i).named('s1');
66
+ b.br(head).at(exit).ret(s);
67
+ i.incoming(entry, zero).incoming(body, i1);
68
+ s.incoming(entry, zero).incoming(body, s1);
69
+ });
70
+ }
71
+ ```
72
+
73
+ ```js
74
+ const mod = Mini.module();
75
+ sum(mod);
76
+ mod.run('sum', [10]); // 45
77
+ mod.fn('sum').print();
78
+ ```
79
+
80
+ ```text
81
+ fn sum(%n) {
82
+ entry:
83
+ %1 = const 0
84
+ br head
85
+ head:
86
+ %i = phi [entry: %1, body: %i1]
87
+ %s = phi [entry: %1, body: %s1]
88
+ %4 = lt %i, %n
89
+ cbr %4, body, exit
90
+ body:
91
+ %5 = const 1
92
+ %i1 = add %i, %5
93
+ %s1 = add %s, %i
94
+ br head
95
+ exit:
96
+ ret %s
97
+ }
98
+ ```
99
+
100
+ ## 2. Defining an IR and its ops
101
+
102
+ `tk.ir(name)` makes an IR, and `.op(name, spec)` adds an op to it. An op name is an identifier (letters, digits, `_`
103
+ and `.`), and an IR defines each name once; `.extend(name, fields)` adds to an op that exists (section 3). The spec's
104
+ fields:
105
+
106
+ | Field | Meaning |
107
+ |---|---|
108
+ | `args` | the number of arguments, or `'*'` for any number; default 0 |
109
+ | `attrs` | `{ name: type }`: the op's attributes and their types; a trailing `?` on the type makes one optional |
110
+ | `eval(args, attrs, ctx)` | the op's meaning: its result from its arguments' values, its attributes, and a context the caller passes |
111
+ | `effect` | any truthy value (`'read'`, `'write'`, `'call'`): the op has a side effect, so `dce` keeps it and `fold` leaves it |
112
+ | `terminator` | `true`: the op ends a block |
113
+ | `control(args, targets, ctx, value)` | for a terminator: where execution goes (a block, an edge index, or `{ ret: value }`) |
114
+ | `result` | whether a value of the op defines a result: `false`, or a function of the attributes, for one that defines none (a store); such values take no id. Default: `true`, except for terminators |
115
+ | `constant` | `true`: this is the IR's constant op, which `fold` builds; an op named `const` with no arguments and one attribute is found without it |
116
+ | `format(value)` | the text after `%id =` when a value of a function prints |
117
+ | `asm` | an assembly template, or an array of them, for `tk.std.asm` (section 10) |
118
+
119
+ Any other field stays on the op's spec for your own use: `v.spec.cost` reads a `cost` field.
120
+
121
+ Each attribute also becomes a getter on the op's values (`v.value`), so an attribute may not be named like a value
122
+ member: `name`, `args`, `uses`, `block`, `loc`, `kind` and the others listed in section 5 are refused.
123
+
124
+ The attribute types:
125
+
126
+ | Type | Values |
127
+ |---|---|
128
+ | `i32` | integers from -2<sup>31</sup> to 2<sup>32</sup> - 1 (signed or unsigned 32-bit) |
129
+ | `i12`, `i8` | signed integers that fit in 12 or 8 bits |
130
+ | `u16`, `u8`, `u5` | unsigned integers that fit in 16, 8 or 5 bits |
131
+ | `int` | any integer |
132
+ | `num` | any number |
133
+ | `str` | a string |
134
+ | `bool` | a boolean |
135
+ | `any` | anything |
136
+
137
+ An IR without blocks builds free expressions. `IR.builder()` gives a builder whose methods are the IR's ops, and a
138
+ builder call takes the argument values first, then the attributes, either in declaration order or as one object.
139
+ `IR.eval(v, ctx)` evaluates an expression with the ops' `eval` lambdas.
140
+
141
+ ```js
142
+ const Arith = tk.ir('arith')
143
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
144
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
145
+ .op('mul', { args: 2, eval: ([a, b]) => Math.imul(a, b) })
146
+ .op('clamp', {
147
+ args: 1,
148
+ attrs: { lo: 'i32', hi: 'i32?' },
149
+ eval: ([x], { lo, hi }) => Math.max(lo, hi === undefined ? x : Math.min(x, hi)),
150
+ });
151
+ Arith.opNames; // ['const', 'add', 'mul', 'clamp']
152
+
153
+ const b = Arith.builder();
154
+ const e = b.add(b.const(2), b.mul(b.const(3), b.const(4)));
155
+ String(e); // 'add(const 2, mul(const 3, const 4))'
156
+ Arith.eval(e); // 14
157
+ String(b.clamp(e, 0, 10)); // 'clamp(add(const 2, mul(const 3, const 4)), 0, 10)'
158
+ Arith.eval(b.clamp(e, { lo: 0, hi: 10 })); // 10
159
+ Arith.eval(b.clamp(e, { lo: 20 })); // 20
160
+ ```
161
+
162
+ The context is whatever the caller passes; an op reads inputs or writes effects through it:
163
+
164
+ ```js
165
+ const Calc = tk.ir('calc')
166
+ .op('num', { attrs: { value: 'num' }, eval: (_, { value }) => value })
167
+ .op('input', { attrs: { key: 'str' }, eval: (_, { key }, ctx) => ctx[key] })
168
+ .op('add', { args: 2, eval: ([a, b]) => a + b });
169
+ const c = Calc.builder();
170
+ Calc.eval(c.add(c.input('x'), c.num(0.5)), { x: 2 }); // 2.5
171
+ ```
172
+
173
+ `v.apply(pass)` runs a pass on the expression `v` is the root of, and returns the root afterwards, which may be a new
174
+ value:
175
+
176
+ ```js
177
+ const f = Arith.builder();
178
+ const root = f.add(f.const(2), f.mul(f.const(3), f.const(4)));
179
+ const folded = root.apply(tk.seq(tk.std.fold, tk.std.dce));
180
+ String(folded); // 'const 14'
181
+ root.erased; // true: fold replaced it
182
+ ```
183
+
184
+ A builder's values form one graph, and a pass sees all of it. Build each expression you will optimize with its own
185
+ builder: `dce` keeps the root it is applied to, but erases every other unused value of the graph.
186
+
187
+ ```js
188
+ const g = Arith.builder();
189
+ const p = g.add(g.const(1), g.const(2));
190
+ const q = g.mul(g.const(3), g.const(4));
191
+ p.apply(tk.std.dce);
192
+ q.erased; // true: q was an unused value of p's graph
193
+ ```
194
+
195
+ Mistakes are reported where they are made. Misuse of the API is a `TypeError`; a request the IR's state does not
196
+ allow is a `TkError`:
197
+
198
+ ```js
199
+ b.add(e); // TypeError: add takes 2 args, got 1
200
+ b.const('7'); // TypeError: const.value is i32, got the string '7'
201
+ b.const({ vlaue: 7 }); // TypeError: const has no attr 'vlaue': did you mean 'value'? (attrs: value)
202
+ b.clamp(e); // TypeError: clamp needs attr 'lo' (i32)
203
+ Arith.builder().add(e, e); // TkError: %4 (add) belongs to another builder
204
+ Arith.op('add', { args: 2 }); // TypeError: arith already has op 'add': use .extend('add', { … })
205
+ tk.ir('t').op('k', { attrs: { uses: 'int' } }); // TypeError: op k: attr 'uses' would hide the value member 'uses'
206
+ tk.ir('t').op('k', { attrs: { v: 'int32' } }); // TypeError: op k: attr 'v' has unknown type 'int32': did you mean 'i32'? (types: i32, i12, i8, u8, u5, u16, int, num, str, bool, any)
207
+ ```
208
+
209
+ ## 3. Fragments
210
+
211
+ A fragment adds to an IR: ops (`define`), members of its values (`op`), and methods of its builders (`builder`). The
212
+ toolkit's own control flow comes from fragments, and `IR.use(...fragments)` applies them.
213
+
214
+ ### Control flow and SSA: `tk.frag.cfg` and `tk.frag.ssa`
215
+
216
+ `tk.frag.cfg` gives an IR blocks and three terminators. On a builder they are `b.br(block)`, `b.cbr(cond, then,
217
+ else)` and `b.ret(value)`; each returns the builder, so `b.br(head).at(head)` reads in order. Their `control` lambdas
218
+ drive `module.run`: `br` goes to its block, `cbr` to the first block when the condition is truthy and to the second
219
+ otherwise, and `ret` returns.
220
+
221
+ `tk.frag.ssa` adds `phi`. `b.phi()` makes a phi after the phis of the current block, and `phi.incoming(block, value)`
222
+ adds the value that arrives from a predecessor block; it returns the phi, so the inputs chain. `sum` in section 1 uses
223
+ both fragments.
224
+
225
+ ### Block parameters: `tk.frag.edges`
226
+
227
+ `tk.frag.edges` gives blocks parameters instead of phis, as MLIR, Cranelift and the book's Host IR have them.
228
+ `b.params(block, n)` makes `n` parameters of a block (`arg` values), and every terminator passes arguments along each
229
+ of its edges. An edge is written `block.to(...args)`. The terminators:
230
+
231
+ | Builder call | Meaning |
232
+ |---|---|
233
+ | `b.jump(edge)` | go to the edge's block |
234
+ | `b.br(cond, then, otherwise, hint?)` | the first edge when `cond` is truthy, else the second; `hint` is an attribute of any value |
235
+ | `b.switch(x, [[k, edge], …], dflt)` | the edge of the first case whose `k` equals `x`, else `dflt` |
236
+ | `b.ret(...values)` | return the first value (or nothing) |
237
+ | `b.trap()` | stop: running it throws `TkError: trap` |
238
+
239
+ Edge arguments are ordinary uses of the terminator, after its own operands. Use lists, `replaceWith` and the
240
+ interpreter therefore need nothing special for them. On a terminator, `t.own` lists its own operands, `t.edges` its
241
+ edges as `{ block, args }`, and `t.setEdge(k, edge)` redirects edge `k` (section 5).
242
+
243
+ ```js
244
+ // used in the rest of this guide
245
+ const H = tk.ir('h')
246
+ .use(tk.frag.edges)
247
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
248
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
249
+ .op('lt', { args: 2, eval: ([a, b]) => +(a < b) })
250
+ .op('call', { args: '*', attrs: { f: 'str', void: 'bool?' }, effect: 'call', result: a => !a.void, eval: () => 0 });
251
+
252
+ /** sum(n) with block parameters instead of phis */
253
+ function hsum(mod) {
254
+ return mod.fn('sum', ['n'], (b, n) => {
255
+ const head = b.block('head'), body = b.block('body'), exit = b.block('exit');
256
+ const [i, s] = b.params(head, 2), [r] = b.params(exit, 1);
257
+ const zero = b.const(0);
258
+ b.jump(head.to(zero, zero)).at(head);
259
+ b.br(b.lt(i, n), body.to(), exit.to(s)).at(body);
260
+ b.jump(head.to(b.add(i, b.const(1)), b.add(s, i))).at(exit);
261
+ b.ret(r);
262
+ });
263
+ }
264
+ ```
265
+
266
+ ```js
267
+ const hm = H.module();
268
+ hsum(hm).print();
269
+ hm.run('sum', [10]); // 45
270
+ const t = hm.fn('sum').block('head').terminator;
271
+ t.own.map(v => v.ref); // ['%5']
272
+ t.edges.map(e => `${e.block.name}(${e.args.map(a => a.ref).join(', ')})`); // ['body()', 'exit(%2)']
273
+ ```
274
+
275
+ ```text
276
+ fn sum(%n) {
277
+ entry:
278
+ %4 = const 0
279
+ jump head(%4, %4)
280
+ head:
281
+ %1 = arg
282
+ %2 = arg
283
+ %5 = lt %1, %n
284
+ br %5, body(), exit(%2)
285
+ body:
286
+ %6 = const 1
287
+ %7 = add %1, %6
288
+ %8 = add %2, %1
289
+ jump head(%7, %8)
290
+ exit:
291
+ %3 = arg
292
+ ret %3
293
+ }
294
+ ```
295
+
296
+ `switch` takes its cases as pairs, and the `call` op above has a result only when its `void` attribute is not set:
297
+
298
+ ```js
299
+ hm.fn('pick', ['x'], (b, x) => {
300
+ const a = b.block('a'), c = b.block('c'), d = b.block('d');
301
+ b.switch(x, [[0, a.to()], [1, c.to(x)]], d.to()).at(a);
302
+ b.call(x, { f: 'log', void: true });
303
+ b.ret(b.const(7)).at(c);
304
+ const [y] = b.params(c, 1);
305
+ b.ret(y).at(d);
306
+ b.trap();
307
+ }).print();
308
+ [hm.run('pick', [0]), hm.run('pick', [1])]; // [7, 1]
309
+ hm.run('pick', [5]); // TkError: trap
310
+ ```
311
+
312
+ ```text
313
+ fn pick(%x) {
314
+ entry:
315
+ switch %x [0 -> a(), 1 -> c(%x)], d()
316
+ a:
317
+ call %x, f="log", void=true
318
+ %1 = const 7
319
+ ret %1
320
+ c:
321
+ %2 = arg
322
+ ret %2
323
+ d:
324
+ trap
325
+ }
326
+ ```
327
+
328
+ ### Machine IRs: `tk.frag.machine`
329
+
330
+ `tk.frag.machine` is for IRs whose ops are machine instructions. A value's `reg` is the register it is in: what
331
+ `tk.regs` (a `WeakMap` a register allocator fills) says for it, else its virtual name. The fragment also puts
332
+ assembly templates for `br`, `cbr` and `ret` in the IR's `machine.asm` table, which `tk.std.asm` uses for ops without
333
+ an `asm` of their own (section 10).
334
+
335
+ ```js
336
+ const M = tk.ir('m')
337
+ .use(tk.frag.cfg, tk.frag.machine)
338
+ .op('li', { attrs: { imm: 'i32' }, asm: 'li {d}, {imm}', eval: (_, { imm }) => imm })
339
+ .op('add', { args: 2, asm: 'add {d}, {0}, {1}', eval: ([a, b]) => (a + b) | 0 });
340
+ const mm = M.module();
341
+ const inc = mm.fn('inc', ['x'], (b, x) => b.ret(b.add(x, b.li(1))));
342
+ tk.std.asm(mm).print();
343
+ tk.regs.set(inc.params[0], 'a0').set(inc.values('add')[0], 'a0').set(inc.values('li')[0], 't0');
344
+ tk.std.asm(mm).print();
345
+ ```
346
+
347
+ ```text
348
+ inc:
349
+ .entry:
350
+ li %1, 1
351
+ add %2, %x, %1
352
+ mv a0, %2
353
+ ret
354
+ inc:
355
+ .entry:
356
+ li t0, 1
357
+ add a0, a0, t0
358
+ mv a0, a0
359
+ ret
360
+ ```
361
+
362
+ ### Your own fragments
363
+
364
+ `tk.fragment(name)` makes a fragment. `.op({ … })` adds members (methods, getters) to values, with `this` the value;
365
+ `.builder({ … })` adds methods to builders, with `this` the builder; `.define(ir => …)` runs once on each IR that uses
366
+ the fragment, which is how `cfg` adds its ops. `IR.use(fragment)` applies a fragment to every op of the IR, and
367
+ `IR.extend(names, x)` applies a fragment, or plain spec fields, to some ops only. Values that exist already see the
368
+ new members.
369
+
370
+ ```js
371
+ const commutative = tk.fragment('commutative').op({
372
+ canonicalize() {
373
+ if (this.arg(0).is('const') && !this.arg(1).is('const')) this.swapArgs();
374
+ },
375
+ });
376
+ const cost = tk.fragment('cost').op({
377
+ get cost() {
378
+ return this.spec.cost ?? 1;
379
+ },
380
+ });
381
+ Mini.extend(['add', 'mul'], commutative).extend('mul', { cost: 3 }).use(cost);
382
+
383
+ const forRange = tk.fragment('for-range').builder({
384
+ forRange(n, init, body) {
385
+ const from = this.current, head = this.block(), loop = this.block(), exit = this.block();
386
+ const zero = this.const(0);
387
+ this.br(head).at(head);
388
+ const i = this.phi(), acc = init.map(() => this.phi());
389
+ this.cbr(this.lt(i, n), loop, exit).at(loop);
390
+ const next = body(this, i, acc);
391
+ const i1 = this.add(i, this.const(1));
392
+ this.br(head).at(exit);
393
+ i.incoming(from, zero).incoming(loop, i1);
394
+ acc.forEach((p, k) => p.incoming(from, init[k]).incoming(loop, next[k]));
395
+ return acc;
396
+ },
397
+ });
398
+ Mini.use(forRange);
399
+
400
+ const mod = Mini.module();
401
+ mod.fn('sum', ['n'], (b, n) => b.ret(b.forRange(n, [b.const(0)], (b, i, [s]) => [b.add(s, i)])[0]));
402
+ mod.run('sum', [10]); // 45
403
+
404
+ const canon = tk.pass('canon').each(v => 'canonicalize' in v && v.canonicalize());
405
+ const tf = mod.fn('t', ['a'], (b, a) => b.ret(b.mul(b.const(5), a))).apply(canon);
406
+ const m = tf.values('mul')[0];
407
+ String(m); // '%2 = mul %a, %1'
408
+ m.cost; // 3
409
+ m.history(); // ['created by build', 'canon: args swapped']
410
+ ```
411
+
412
+ A builder's methods come in three layers. The builder's own (`at`, `block`, `loc`, …) are at the bottom and cannot be
413
+ hidden: an op with one of their names gets no builder method. Each op's method is above them, and the fragments'
414
+ builder methods are on top, so a fragment's method replaces an op's method of the same name (this is how
415
+ `tk.frag.edges` gives `br` its edges).
416
+
417
+ ## 4. Building functions
418
+
419
+ A module holds functions. `mod.fn(name, params, body, opts)` defines one: `params` names its parameters (`null` for an
420
+ unnamed one), and `body(b, ...params)` builds it with a builder placed in the entry block. `mod.fn(name)` finds a
421
+ function again. The options are for importers: `entry` names the entry block, and `ids` gives the parameters' ids.
422
+
423
+ The builder adds each value at the end of its current block. `b.current` is that block and `b.entry` the entry block;
424
+ `b.block(name)` makes a new block without moving there, and `b.at(block)` moves to the end of a block. `b.before(v)`
425
+ inserts before a value instead. Otherwise a phi goes after the block's phis and a block parameter after its
426
+ parameters, wherever the builder is in the block. `mod.run(name, args, ctx)` runs a function, and passes `ctx` to
427
+ every `eval` and `control` lambda.
428
+
429
+ ```js
430
+ const mod = Mini.module();
431
+ const poke = mod.fn('poke', ['p', 'x'], (b, p, x) => {
432
+ b.store(p, b.add(x, b.const(1)));
433
+ b.ret(b.load(p));
434
+ });
435
+ poke.print();
436
+ const ctx = { mem: [] };
437
+ mod.run('poke', [4, 41], ctx); // 42
438
+ ctx.mem[4]; // 42
439
+ ```
440
+
441
+ ```text
442
+ fn poke(%p, %x) {
443
+ entry:
444
+ %2 = const 1
445
+ %3 = add %x, %2
446
+ store %p, %3
447
+ %4 = load %p
448
+ ret %4
449
+ }
450
+ ```
451
+
452
+ The `store` has no `%id =`: its op says `result: false`. A value that defines a result takes the next id, in creation
453
+ order from 0, parameters first; `v.named(name)` gives it a name, which prints instead of the id.
454
+
455
+ A block ends at its terminator, and building past one is an error. Blocks are named `b1`, `b2`, … by default, and a
456
+ name already taken gets a `'`:
457
+
458
+ ```js
459
+ mod.fn('bad', [], b => {
460
+ b.ret(b.const(1));
461
+ b.const(2); // TkError: block entry already ends with ret: b.at(another block) first
462
+ });
463
+ const order = mod.fn('order', ['x'], (b, x) => {
464
+ const y = b.mul(x, b.const(2));
465
+ b.before(y).const(1).named('one');
466
+ b.at(b.current).ret(y);
467
+ });
468
+ order.entry.values().map(String); // ['%1 = const 2', '%one = const 1', '%2 = mul %x, %1', 'ret %2']
469
+ order.addBlock().name; // 'b1'
470
+ order.addBlock('entry').name; // "entry'"
471
+ ```
472
+
473
+ An importer that reads another IR keeps its numbering: `b.id(n)` gives the next value the id `n`. Explicit ids do not
474
+ move the counter, `f.nextId`, so an importer that numbers some values should number all of them, or set `f.nextId`
475
+ past the largest id it read.
476
+
477
+ ```js
478
+ const imp = mod.fn(
479
+ 'imported',
480
+ [null],
481
+ (b, p) => {
482
+ const k = b.id(10).const(5);
483
+ b.ret(b.id(11).add(p, k));
484
+ },
485
+ { entry: 'start', ids: [7] },
486
+ );
487
+ imp.print();
488
+ imp.nextId; // 0
489
+ ```
490
+
491
+ ```text
492
+ fn imported(%7) {
493
+ start:
494
+ %10 = const 5
495
+ %11 = add %7, %10
496
+ ret %11
497
+ }
498
+ ```
499
+
500
+ `b.loc(where, text)` sets the source position of the values built next, and `b.loc(null)` forgets it. A position shows
501
+ at the end of a value's trace (section 13).
502
+
503
+ ```js
504
+ const located = mod.fn('located', ['x'], (b, x) => {
505
+ b.loc('f.js:1', 'let y = x + 1');
506
+ const y = b.add(x, b.const(1));
507
+ b.loc(null);
508
+ b.ret(y);
509
+ });
510
+ located.values('add')[0].loc.where; // 'f.js:1'
511
+ located.entry.terminator.loc; // null
512
+ ```
513
+
514
+ An op with a `format` prints itself:
515
+
516
+ ```js
517
+ const Fmt = tk.ir('fmt')
518
+ .use(tk.frag.cfg)
519
+ .op('ld', { args: 1, attrs: { off: 'int' }, format: v => `ld ${v.off}(${v.arg(0).ref})` });
520
+ Fmt.module().fn('f', ['p'], (b, p) => b.ret(b.ld(p, 4))).print();
521
+ ```
522
+
523
+ ```text
524
+ fn f(%p) {
525
+ entry:
526
+ %1 = ld 4(%p)
527
+ ret %1
528
+ }
529
+ ```
530
+
531
+ `f.meta` and `mod.meta` hold whatever a frontend wants to keep about a function or a module (a return count, flags,
532
+ globals). They are plain data, and `mod.clone()` copies them.
533
+
534
+ ## 5. Values and the mutations
535
+
536
+ A value is an instance of an op. What it has:
537
+
538
+ | Member | What it is |
539
+ |---|---|
540
+ | `kind`, `op`, `spec`, `ir` | the op's name, the op, its spec, its IR |
541
+ | `args`, `arg(i)` | the argument values; `arg(i)` throws for an index out of range |
542
+ | `attrs`, and one getter per attribute | the attributes: `v.attrs.value`, or `v.value` |
543
+ | `uses` | the values that use this one (a value used twice by one user is listed twice) |
544
+ | `block`, `fn` | where it is |
545
+ | `id`, `name`, `ref` | its number (`null` without a result), its name, and how it prints as an argument (`%name`, `%id`, or the op name without a result) |
546
+ | `hasResult` | whether it defines a result |
547
+ | `pure` | no effect, not a terminator, not a phi or block parameter: removable when unused, movable |
548
+ | `erased` | whether it has been erased |
549
+ | `is(kind, attrs?)` | its op is `kind` (and its attributes match); an unknown `kind` throws |
550
+ | `targets`, `incomingBlocks`, `edgeArgc`, `loc` | a terminator's blocks, a phi's predecessor blocks, the argument count of each edge (`tk.frag.edges`), the source position |
551
+
552
+ ```js
553
+ const mod = Mini.module();
554
+ const f = sum(mod);
555
+ const i1 = f.values().find(v => v.name === 'i1');
556
+ [i1.kind, i1.ref, i1.id, i1.block.name]; // ['add', '%i1', 6, 'body']
557
+ i1.args.map(a => a.ref); // ['%i', '%5']
558
+ i1.arg(1).value; // 1
559
+ i1.uses.map(u => u.ref); // ['%i']
560
+ i1.arg(1).is('const', { value: 1 }); // true
561
+ i1.pure; // true
562
+ f.entry.terminator.hasResult; // false
563
+ i1.is('mull'); // TypeError: is('mull'): mini has no op 'mull': did you mean 'mul'?
564
+ ```
565
+
566
+ A pass changes values in place, through a few mutations. Each one records the actor that made it (the pass running,
567
+ section 13) and increments the function's `revision` (section 9). Each one but `phi.incoming` also refuses to change a
568
+ read-only snapshot (section 12); `incoming` does not check that yet.
569
+
570
+ | Mutation | What it does |
571
+ |---|---|
572
+ | a builder call | creates a value |
573
+ | `v.replaceWith(x)` | every use of `v` reads `x` instead, then `v` is erased; `x` is a value, or a function `b => value` whose builder is placed before `v`; returns the replacement |
574
+ | `v.replaceUses(x)` | every use of `v` reads `x` instead; `v` stays, unused, for a later `dce` |
575
+ | `v.erase()` | removes a value nothing uses; it throws while uses remain |
576
+ | `fn.eraseAll(values)` | removes a set of values together: every use of each must be another of them; returns the count |
577
+ | `v.moveTo(block)` | moves a value to the end of a block of the same function, before its terminator |
578
+ | `v.setArg(i, x)` | argument `i` becomes `x` |
579
+ | `v.swapArgs()` | swaps the two arguments of a two-argument value |
580
+ | `phi.incoming(block, x)` | adds a phi input (`tk.frag.ssa`) |
581
+ | `t.setEdge(k, block.to(...args))` | points edge `k` of a terminator at another block, with new arguments (`tk.frag.edges`) |
582
+
583
+ `replaceWith` also moves a value's name to an unnamed replacement (a name belongs to what is computed), moves the
584
+ entries of side tables made with `{ follows: 'replace' }` (section 12), and keeps an expression's root up to date.
585
+ `v.named(name)` is not a mutation: it changes no revision.
586
+
587
+ `replaceWith` with a builder function, as a pass uses it:
588
+
589
+ ```js
590
+ const scale = mod.fn('scale', ['x'], (b, x) => b.ret(b.add(b.mul(x, b.const(2)), b.const(0))));
591
+ const double = tk.pass('double').each(v => {
592
+ if (v.is('mul') && v.arg(1).is('const', { value: 2 })) v.replaceWith(b => b.add(v.arg(0), v.arg(0)));
593
+ });
594
+ scale.apply(double).print();
595
+ const add = scale.values('add')[0];
596
+ add.history(); // ['created by double']
597
+ add.origin()[0].history(); // ['created by build', 'double: replaced by %5']
598
+ add.erase(); // TkError: cannot erase %5 (add): 1 use remains (%4 (add) in entry): replaceWith(…) first
599
+ ```
600
+
601
+ ```text
602
+ fn scale(%x) {
603
+ entry:
604
+ %1 = const 2
605
+ %5 = add %x, %x
606
+ %3 = const 0
607
+ %4 = add %5, %3
608
+ ret %4
609
+ }
610
+ ```
611
+
612
+ `replaceUses` leaves the old value in place, which suits a pass that should not disturb the values it walks; `dce`
613
+ removes it later:
614
+
615
+ ```js
616
+ const g = mod.fn('g', ['x', 'y'], (b, x, y) => b.ret(b.add(b.mul(x, y), b.mul(x, y))));
617
+ const [m1, m2] = g.values('mul');
618
+ m2.replaceUses(m1);
619
+ g.values('mul').length; // 2
620
+ m2.history(); // ['created by build', 'user: uses moved to %2']
621
+ g.apply(tk.std.dce).print();
622
+ ```
623
+
624
+ ```text
625
+ fn g(%x, %y) {
626
+ entry:
627
+ %2 = mul %x, %y
628
+ %4 = add %2, %2
629
+ ret %4
630
+ }
631
+ ```
632
+
633
+ `dce` erases one unused value at a time, so it cannot erase values that only use each other, such as a loop's dead
634
+ accumulator: a phi and the add that feeds it back. `eraseAll` erases such a set at once:
635
+
636
+ ```js
637
+ const h = sum(Mini.module());
638
+ const [i, s] = h.block('head').phis;
639
+ h.block('exit').terminator.setArg(0, i); // return i instead of s
640
+ h.apply(tk.std.dce);
641
+ h.values('phi').length; // 2: s and s1 use each other, so neither is unused
642
+ const s1 = h.values().find(v => v.name === 's1');
643
+ h.eraseAll([i]); // TkError: eraseAll: %i (phi) is used by %4 (lt), which is not erased with it
644
+ h.eraseAll([s, s1]); // 2
645
+ h.values('phi').length; // 1
646
+ h.module.run('sum', [10]); // 10
647
+ ```
648
+
649
+ `setArg`, `swapArgs` and `setEdge`:
650
+
651
+ ```js
652
+ const k = mod.fn('k', ['a'], (b, a) => b.ret(b.add(b.const(1), a)));
653
+ const plus = k.values('add')[0];
654
+ plus.swapArgs();
655
+ String(plus); // '%2 = add %a, %1'
656
+ plus.setArg(1, k.params[0]);
657
+ String(plus); // '%2 = add %a, %a'
658
+ plus.history(); // ['created by build', 'user: args swapped', 'user: arg 1 set to %a']
659
+
660
+ const hm = H.module();
661
+ const hf = hsum(hm);
662
+ const jump = hf.entry.terminator;
663
+ String(jump); // 'jump head(%4, %4)'
664
+ jump.setEdge(0, hf.block('exit').to(hf.params[0]));
665
+ String(jump); // 'jump exit(%n)'
666
+ hm.run('sum', [10]); // 10
667
+ jump.history(); // ['created by build', 'user: edge 0 set to exit']
668
+ ```
669
+
670
+ ## 6. Passes
671
+
672
+ A pass is a name and one body. The body's kind decides how it runs:
673
+
674
+ | Body | Runs |
675
+ |---|---|
676
+ | `.each((value, analyses) => …)` | on every value of each function, in order |
677
+ | `.run((fn, analyses) => …)` | once per function |
678
+ | `.module(module => …)` | once per module, for work across functions; applied to anything else, it throws |
679
+ | `.rules(...ruleSets)` | the rules, driven greedily until none fires (section 7) |
680
+
681
+ `.needs({ name: analysis })` names the analyses the body receives as its last argument; each is computed when the body
682
+ first reads it (section 9). `.about(text)` describes the pass. A pass has one body: `.each`, `.run` and `.module`
683
+ throw if it has one already (`.rules` replaces it).
684
+
685
+ `.each` walks the values the function has when the walk starts and skips the ones erased meanwhile, so a value it
686
+ creates is not visited in the same walk. Run the pass again, or under `tk.fixpoint` (section 8), to reach those.
687
+
688
+ A pass applies to a module (`mod.apply(pass)`, each function in turn), to one function (`f.apply(pass)`), or to an
689
+ expression (`v.apply(pass)`). The first two return their target; `v.apply` returns the expression's root afterwards.
690
+ While a pass runs, every change records its name.
691
+
692
+ The loop-invariant code motion used in the rest of this guide:
693
+
694
+ ```js
695
+ // used in the rest of this guide
696
+ const licm = tk.pass('licm')
697
+ .about('move loop-invariant pure values to the preheader')
698
+ .needs({ loops: tk.std.loops })
699
+ .run((f, { loops }) => {
700
+ for (const loop of loops.innermostFirst())
701
+ if (loop.preheader)
702
+ for (const v of loop.values())
703
+ if (v.pure && v.args.every(a => !loop.contains(a))) v.moveTo(loop.preheader);
704
+ });
705
+ ```
706
+
707
+ ```js
708
+ const mod = Mini.module();
709
+ const f = sum(mod);
710
+ f.apply(licm);
711
+ f.block('entry').values().map(String); // ['%1 = const 0', '%5 = const 1', 'br head']
712
+ mod.run('sum', [10]); // 45
713
+ f.values('const')[1].history(); // ['created by build', 'licm: moved to entry']
714
+ ```
715
+
716
+ An `.each` pass, and a `.module` pass:
717
+
718
+ ```js
719
+ const addZero = tk.pass('add-zero').each(v => {
720
+ if (v.is('add') && v.arg(1).is('const', { value: 0 })) v.replaceWith(v.arg(0));
721
+ });
722
+ const g = mod.fn('g', ['a'], (b, a) => b.ret(b.add(a, b.const(0))));
723
+ g.apply(addZero).apply(tk.std.dce).print();
724
+
725
+ const dropScratch = tk.pass('drop-scratch').module(m => {
726
+ for (const fn of m.fns) if (fn.name.startsWith('_')) m.remove(fn.name);
727
+ });
728
+ mod.fn('_tmp', [], b => b.ret(b.const(0)));
729
+ mod.apply(dropScratch).fns.map(fn => fn.name); // ['sum', 'g']
730
+ g.apply(dropScratch); // TypeError: pass drop-scratch works on a module, not on a Fn
731
+ tk.pass('empty').applyTo(mod); // TkError: pass empty has no body: give it .each(…), .run(…), .module(…) or .rules(…)
732
+ ```
733
+
734
+ ```text
735
+ fn g(%a) {
736
+ entry:
737
+ ret %a
738
+ }
739
+ ```
740
+
741
+ ## 7. Rewrite rules
742
+
743
+ A rule set holds rewrite rules over one IR: `tk.rules(name, IR)`, then for each rule `.rule(name)`,
744
+ `.match(pattern)`, optionally `.when(condition)`, and `.to(replacement)`. Rule names are unique within a set.
745
+
746
+ The pattern language:
747
+
748
+ - `op(p, …)` matches a value of that op whose arguments match the sub-patterns; the count must be the op's;
749
+ - a bare op name matches any value of that op, whatever its arguments;
750
+ - a bare other name binds any value; the same name twice must be the same value, and `_` matches anything;
751
+ - `op k`, for an op with exactly one attribute, matches a value whose attribute equals the number `k` (decimal or
752
+ `0x` hex, possibly negative), and `op c` binds the attribute to the name `c`.
753
+
754
+ The pattern is parsed against the IR when the rule is defined, so a misspelled op fails there. The condition and the
755
+ replacement receive the bindings, an object whose properties are the pattern's names; reading another name throws,
756
+ in both check modes. `.to((bindings, b) => value)` returns the replacement: a bound value, or a value built with `b`,
757
+ a builder placed before the matched value. Returning nothing, `null` or the matched value itself means no change.
758
+
759
+ The peephole rules used in the rest of this guide:
760
+
761
+ ```js
762
+ // used in the rest of this guide
763
+ const isPow2 = c => c > 0 && (c & (c - 1)) === 0;
764
+ const peep = tk.rules('peephole', Mini)
765
+ .rule('add-zero').match('add(x, const 0)').to(({ x }) => x)
766
+ .rule('mul-one').match('mul(x, const 1)').to(({ x }) => x)
767
+ .rule('mul-pow2').match('mul(x, const c)').when(({ c }) => isPow2(c))
768
+ .to(({ x, c }, b) => b.shl(x, b.const(Math.log2(c))))
769
+ .rule('const-right').match('add(const c, x)').when(({ x }) => !x.is('const'))
770
+ .to(({ c, x }, b) => b.add(x, b.const(c)));
771
+ const peephole = tk.pass('peephole').rules(peep);
772
+ ```
773
+
774
+ A rule set is a value: `names` lists its rules, `without(...names)` and `with(...sets)` make new sets.
775
+
776
+ ```js
777
+ peep.names; // ['add-zero', 'mul-one', 'mul-pow2', 'const-right']
778
+ peep.without('mul-pow2').names; // ['add-zero', 'mul-one', 'const-right']
779
+
780
+ const mod = Mini.module();
781
+ const g = mod.fn('g', ['a'], (b, a) => b.ret(b.add(b.mul(a, b.const(8)), b.const(0))));
782
+ g.apply(peephole).apply(tk.std.dce).print();
783
+ ```
784
+
785
+ ```text
786
+ fn g(%a) {
787
+ entry:
788
+ %5 = const 3
789
+ %6 = shl %a, %5
790
+ ret %6
791
+ }
792
+ ```
793
+
794
+ A repeated name, a hex literal and `_`:
795
+
796
+ ```js
797
+ const more = tk.rules('more', Mini)
798
+ .rule('double').match('add(x, x)').to(({ x }, b) => b.shl(x, b.const(1)))
799
+ .rule('times-16').match('mul(x, const 0x10)').to(({ x }, b) => b.shl(x, b.const(4)))
800
+ .rule('times-0').match('mul(_, const 0)').to((_, b) => b.const(0));
801
+ peep.with(more).names; // ['add-zero', 'mul-one', 'mul-pow2', 'const-right', 'double', 'times-16', 'times-0']
802
+ const h = mod.fn('h', ['a', 'c'], (b, a, c) => b.ret(b.add(b.add(a, a), b.mul(c, b.const(0)))));
803
+ h.apply(tk.pass('more').rules(more, peep)).apply(tk.std.dce).print();
804
+ ```
805
+
806
+ ```text
807
+ fn h(%a, %c) {
808
+ entry:
809
+ %6 = const 1
810
+ %7 = shl %a, %6
811
+ ret %7
812
+ }
813
+ ```
814
+
815
+ The driver, `tk.pass(name).rules(...sets)`, works in rounds. In a round it visits every value in order and fires the
816
+ first rule, in the order of the sets and of their rules, that matches it and whose condition holds; the replacement
817
+ then replaces the value. It stops after a round in which no rule fired. Rules that never settle, such as
818
+ commutativity, would run forever; the driver stops after 10,000 firings in one function:
819
+
820
+ ```js
821
+ const algebra = tk.rules('algebra', Mini).rule('add-comm').match('add(x, y)').to(({ x, y }, b) => b.add(y, x));
822
+ sum(Mini.module()).apply(tk.pass('greedy').rules(algebra)); // TkError: greedy: the rules fired 10000 times in sum (the last was add-comm): they may not terminate
823
+ ```
824
+
825
+ Mistakes in rules:
826
+
827
+ ```js
828
+ tk.rules('oops', Mini).rule('r').match('add(x, cnst 0)'); // TkError: pattern 'add(x, cnst 0)': mini has no op 'cnst': did you mean 'const'?
829
+ tk.rules('oops', Mini).rule('r').match('add(x)'); // TkError: pattern 'add(x)': add takes 2 args, the pattern gives 1
830
+ tk.rules('oops', Mini).rule('r').match('x'); // TkError: rule r: the pattern 'x' must start with an op
831
+ const bad = tk.rules('bad', Mini).rule('r').match('add(x, const 0)').to(({ y }) => y);
832
+ const z = mod.fn('z', ['a'], (b, a) => b.ret(b.add(a, b.const(0))));
833
+ z.apply(tk.pass('p').rules(bad)); // TkError: rule r: no binding 'y' (the pattern binds: x)
834
+ ```
835
+
836
+ ## 8. Combining passes
837
+
838
+ Anything with an `applyTo(target)` method is a pass to the toolkit: passes, the standard passes, and what the
839
+ combinators return. The combinators:
840
+
841
+ | Combinator | Applies |
842
+ |---|---|
843
+ | `tk.seq(...passes)` | the passes in order |
844
+ | `tk.fixpoint(pass, { max })` | the pass again until the target's revision stops changing; after `max` rounds (default 100), it throws |
845
+ | `tk.when(fn => bool, pass)` | the pass to the functions the predicate accepts |
846
+ | `tk.choose(alternatives, cost)` | each alternative to its own clone of a module, then keeps the clone with the lowest `cost(module)` |
847
+
848
+ A combined pass has a `name` that says what it is made of. A check is a pass like any other, placed where you want it:
849
+
850
+ ```js
851
+ const O1 = tk.seq(tk.std.fold, peephole, tk.std.dce);
852
+ const O2 = tk.seq(tk.fixpoint(O1), licm, O1);
853
+ const Os = tk.seq(tk.when(f => f.size < 40, O2), tk.std.verifySSA);
854
+ O2.name; // 'seq(fixpoint(seq(fold, peephole, dce)), licm, seq(fold, peephole, dce))'
855
+
856
+ const mod = Mini.module();
857
+ sum(mod);
858
+ mod.fn('k', [], b => b.ret(b.mul(b.add(b.const(2), b.const(3)), b.const(4))));
859
+ mod.apply(Os);
860
+ mod.fn('k').print();
861
+
862
+ const flip = tk.pass('flip').each(v => v.is('add') && v.swapArgs());
863
+ mod.apply(tk.fixpoint(flip, { max: 5 })); // TkError: fixpoint(flip) still changes the module after 5 rounds
864
+ ```
865
+
866
+ ```text
867
+ fn k() {
868
+ entry:
869
+ %6 = const 20
870
+ ret %6
871
+ }
872
+ ```
873
+
874
+ `tk.choose` works on a module. Each alternative runs on a clone; the module adopts the functions of the cheapest
875
+ clone (the first, on a tie), and `mod.choices` records each choice. Here the cost counts a value inside a loop as 10:
876
+
877
+ ```js
878
+ const weighted = m =>
879
+ m.fns.reduce((n, f) => {
880
+ const loops = f.get(tk.std.loops);
881
+ return n + f.values().reduce((c, v) => c + 10 ** loops.depthOf(v.block), 0);
882
+ }, 0);
883
+ const m2 = Mini.module();
884
+ sum(m2);
885
+ m2.apply(tk.choose([O1, O2], weighted));
886
+ m2.choices[0].costs.map(c => c.cost); // [83, 74]
887
+ m2.choices[0].picked === O2.name; // true
888
+ m2.fn('sum').block('entry').values().map(String); // ['%1 = const 0', '%5 = const 1', 'br head']
889
+ m2.snapshot().apply(tk.choose([O1, O2], weighted)); // TkError: snapshot r21 is read-only: .clone() gives an editable copy
890
+ ```
891
+
892
+ A combinator of your own is an object with a `name` and an `applyTo(target)` that returns the target:
893
+
894
+ ```js
895
+ const sized = p => ({
896
+ name: `sized(${p.name})`,
897
+ applyTo(target) {
898
+ const before = target.size;
899
+ p.applyTo(target);
900
+ console.log(`${p.name}: ${before} -> ${target.size} values`);
901
+ return target;
902
+ },
903
+ });
904
+ const m3 = Mini.module();
905
+ m3.fn('g', ['a'], (b, a) => b.ret(b.add(b.mul(a, b.const(8)), b.const(0))));
906
+ m3.apply(tk.seq(sized(peephole), sized(tk.std.dce)));
907
+ ```
908
+
909
+ ```text
910
+ peephole: 5 -> 5 values
911
+ dce: 5 -> 3 values
912
+ ```
913
+
914
+ ## 9. Analyses and the revision cache
915
+
916
+ An analysis is a named function of a function: `tk.analysis(name, fn => result, { on })`. A plain function works too;
917
+ its JavaScript name names it. `f.get(analysis)` computes the result on the first call and returns the cached result
918
+ until the function changes.
919
+
920
+ Changes are counted, not declared. Every mutation increments `f.revision`. Adding a block, and any mutation of a
921
+ terminator, also increments `f.cfgRevision`. An analysis made with `{ on: 'cfg' }` (a plain function: with a property
922
+ `on = 'cfg'`) depends only on the control flow, so it is recomputed only when `cfgRevision` moves; others are
923
+ recomputed when `revision` moves. `tk.std.dominators` and `tk.std.loops` are `on: 'cfg'`. No pass has to say which
924
+ analyses it preserves.
925
+
926
+ Liveness is not in the library; the dataflow solver is (section 11), and liveness is configured from it:
927
+
928
+ ```js
929
+ const liveness = tk.analysis('liveness', fn =>
930
+ tk.std.dataflow(fn, {
931
+ dir: 'backward',
932
+ ...tk.lattice.sets,
933
+ transfer: (block, live) => {
934
+ const out = new Set(live);
935
+ for (const v of block.values().reverse()) {
936
+ out.delete(v);
937
+ v.args.forEach(a => out.add(a));
938
+ }
939
+ return out;
940
+ },
941
+ }),
942
+ );
943
+ const mod = Mini.module();
944
+ const f = sum(mod);
945
+ const live = f.get(liveness);
946
+ f.get(liveness) === live; // true: cached for this revision
947
+ [...live.in(f.block('body'))].map(v => v.ref).sort(); // ['%1', '%i', '%n', '%s']
948
+
949
+ [f.revision, f.cfgRevision]; // [20, 8]
950
+ const loops = f.get(tk.std.loops);
951
+ f.apply(licm);
952
+ [f.revision, f.cfgRevision]; // [21, 8]
953
+ f.get(tk.std.loops) === loops; // true: licm did not change the control flow
954
+ f.get(liveness) === live; // false: recomputed for revision 21
955
+ ```
956
+
957
+ The results of the library's analyses are plain objects; destructure what you need:
958
+
959
+ ```js
960
+ const { dominates, idomOf } = f.get(tk.std.dominators);
961
+ dominates(f.entry, f.block('exit')); // true
962
+ idomOf(f.block('exit')).name; // 'head'
963
+ const blockCount = fn => fn.blocks.length;
964
+ blockCount.on = 'cfg';
965
+ f.get(blockCount); // 4
966
+ ```
967
+
968
+ A result read after its function changed answers from stale data, unless checks are on: then reading it, or calling
969
+ one of its methods, throws and says to call `get` again (section 15). In a pass, ask for analyses with `.needs` and
970
+ read them from the body's last argument, as `licm` does; each is computed on its first read.
971
+
972
+ ## 10. Lowering to a machine IR
973
+
974
+ A machine IR is an IR like any other, with `tk.frag.machine` and an `asm` template on each op. Its ops have `eval`
975
+ lambdas too, so the lowered program runs.
976
+
977
+ `tk.lower(from, to, name)` makes a lowering: a table with one case per source op, `.op(kind, (v, b, args, blocks) =>
978
+ value)`. A case gets the source value, a builder of the target IR placed in the matching block, the source arguments
979
+ already lowered, and a `Map` from source blocks to target blocks. It returns the target value that stands for `v`, or
980
+ nothing for an op without a result. Blocks (with their names), parameters, phis (when the target IR has phis and the
981
+ lowering has no `phi` case) and the `cfg` terminators `br`, `cbr` and `ret` (when the target has them and the lowering
982
+ has no case) carry over by themselves. Blocks are lowered in reverse postorder; a value used before it is lowered, in
983
+ that order, is an error.
984
+
985
+ `lowering.run(module)` returns a new module of the target IR. Every value a case builds records the source value as
986
+ its origin, and the value a case returns takes the source value's name; the actor of every change is the lowering's
987
+ name. A lowering is not a pass:
988
+ `mod.apply(lowering)` throws.
989
+
990
+ The instruction selection used in the rest of this guide:
991
+
992
+ ```js
993
+ // used in the rest of this guide
994
+ const RV = tk.ir('rv32')
995
+ .use(tk.frag.cfg, tk.frag.ssa, tk.frag.machine)
996
+ .op('li', { attrs: { imm: 'i32' }, asm: 'li {d}, {imm}', eval: (_, { imm }) => imm })
997
+ .op('addi', { args: 1, attrs: { imm: 'i12' }, asm: 'addi {d}, {0}, {imm}', eval: ([a], { imm }) => (a + imm) | 0 })
998
+ .op('add', { args: 2, asm: 'add {d}, {0}, {1}', eval: ([a, b]) => (a + b) | 0 })
999
+ .op('slli', { args: 1, attrs: { imm: 'u5' }, asm: 'slli {d}, {0}, {imm}', eval: ([a], { imm }) => a << imm })
1000
+ .op('slt', { args: 2, asm: 'slt {d}, {0}, {1}', eval: ([a, b]) => +(a < b) });
1001
+
1002
+ const small = v => v.is('const') && v.value >= -2048 && v.value < 2048;
1003
+ const select = tk.lower(Mini, RV, 'select')
1004
+ .op('const', (v, b) => b.li({ imm: v.value }))
1005
+ .op('add', (v, b, [x, y]) => (small(v.arg(1)) ? b.addi(x, { imm: v.arg(1).value }) : b.add(x, y)))
1006
+ .op('shl', (v, b, [x]) => b.slli(x, { imm: v.arg(1).value }))
1007
+ .op('lt', (v, b, [x, y]) => b.slt(x, y));
1008
+ ```
1009
+
1010
+ ```js
1011
+ const mod = Mini.module();
1012
+ sum(mod);
1013
+ const rv = select.run(mod).apply(tk.std.dce);
1014
+ rv.run('sum', [10]); // 45
1015
+ tk.std.asm(rv).print();
1016
+ String(rv.fn('sum').values('addi')[0].origin()[0]); // '%i1 = add %i, %5'
1017
+ ```
1018
+
1019
+ ```text
1020
+ sum:
1021
+ .entry:
1022
+ li %1, 0
1023
+ j .head
1024
+ .head:
1025
+ # %i = phi entry: %1, body: %i1
1026
+ # %s = phi entry: %1, body: %s1
1027
+ slt %4, %i, %n
1028
+ bnez %4, .body
1029
+ j .exit
1030
+ .body:
1031
+ addi %i1, %i, 1
1032
+ add %s1, %s, %i
1033
+ j .head
1034
+ .exit:
1035
+ mv a0, %s
1036
+ ret
1037
+ ```
1038
+
1039
+ The `li` that stood for `const 1` is gone: `addi` took the constant as an immediate, and `dce` erased the unused
1040
+ `li`. An op without a case is an error that says how many values need one:
1041
+
1042
+ ```js
1043
+ mod.fn('m', ['a'], (b, a) => b.ret(b.mul(a, a)));
1044
+ select.run(mod); // TkError: select has no case for mini op 'mul' (1 value in m): add .op('mul', …)
1045
+ mod.apply(select); // TypeError: select makes a new rv32 module: call .run(module), not apply
1046
+ ```
1047
+
1048
+ `tk.std.asm(module)` prints a machine IR's assembly. An op's template is its `asm`, else the IR's `machine.asm` entry
1049
+ for its kind; an array makes several lines. In a template, `{d}` is the value's register, `{0}`, `{1}`, … its
1050
+ arguments' registers, `{t0}`, `{t1}`, … its target blocks (as `.name`), and `{name}` an attribute. A phi prints as a
1051
+ comment. The result's `lines` are `{ text, value }`; `find(regex)` returns the first matching line's number (from 1,
1052
+ or 0 when none matches), and `line(n)` returns that line with a `trace()` back to the source (section 13).
1053
+
1054
+ ## 11. The standard library
1055
+
1056
+ ### Passes: `fold`, `dce`, `verifySSA`
1057
+
1058
+ `tk.std.fold` evaluates, with its `eval` lambda, each pure value whose arguments are all constants, and replaces it
1059
+ with a constant. The constant op is the IR's op named `const`, or the one declared `constant: true`; it must take no
1060
+ arguments and have one attribute. A result the constant's attribute type does not accept is left alone.
1061
+
1062
+ ```js
1063
+ const K = tk.ir('k')
1064
+ .op('num', { attrs: { n: 'int' }, constant: true, eval: (_, { n }) => n })
1065
+ .op('neg', { args: 1, eval: ([x]) => -x })
1066
+ .op('half', { args: 1, eval: ([x]) => x / 2 });
1067
+ const kb = K.builder();
1068
+ String(kb.neg(kb.neg(kb.num(5))).apply(tk.std.fold)); // 'num 5'
1069
+ const hb = K.builder();
1070
+ String(hb.half(hb.num(7)).apply(tk.std.fold)); // 'half(num 7)'
1071
+ ```
1072
+
1073
+ `3.5` is not an `int`, so `half(num 7)` stays.
1074
+
1075
+ `tk.std.dce` erases pure values and phis that nothing uses, until none is left. An expression's root counts as used.
1076
+ Values that only use each other stay; `fn.eraseAll` removes them (section 5).
1077
+
1078
+ `tk.std.verifySSA` throws unless the function is well-formed SSA: every block ends with a terminator and has no other;
1079
+ phis come first and have one input per predecessor; use lists agree with arguments; no value uses an erased one; and
1080
+ every definition dominates its uses. It lists every problem it finds:
1081
+
1082
+ ```js
1083
+ const mod = Mini.module();
1084
+ const f = sum(mod);
1085
+ f.apply(tk.std.verifySSA); // a well-formed function passes
1086
+ f.values().find(v => v.name === 'i1').moveTo(f.entry);
1087
+ try {
1088
+ f.apply(tk.std.verifySSA);
1089
+ } catch (e) {
1090
+ console.log(e.message);
1091
+ }
1092
+ ```
1093
+
1094
+ ```text
1095
+ verify-ssa: sum: 2 problems
1096
+ %i1 (add) in entry uses %i, which does not dominate it
1097
+ %i1 (add) in entry uses %5, which does not dominate it
1098
+ ```
1099
+
1100
+ ### Graph algorithms
1101
+
1102
+ The graph algorithms take a function (its blocks), or any graph described as a view: `tk.view.graph({ nodes, succ,
1103
+ entry })`, where `succ(node)` returns a node's successors and `entry` defaults to the first node. A function's own
1104
+ view is `f.graph`.
1105
+
1106
+ - `tk.std.depthFirst(view)`: `{ postorder, rpo, retreating }`, the orders of a depth-first walk from the entry and
1107
+ the edges `{ from, to }` that go back to a node on the walk's stack.
1108
+ - `tk.std.dominators(view, { root })`: `{ idom, rpo, dominates(a, b), children(n), idomOf(n) }`, by the
1109
+ Cooper-Harvey-Kennedy algorithm. `idom` is a `Map`; the entry is its own immediate dominator there, and `idomOf`
1110
+ returns `null` for it.
1111
+ - `tk.std.loops(view)`: natural loops, one per header: `{ all, innermostFirst(), of(block), depthOf(block) }`. A loop
1112
+ has `header`, `latches`, `body`, `exits`, `preheader` (the single outside predecessor, if it has only one successor;
1113
+ else `null`), `depth`, `contains(blockOrValue)`, and, for a function, `values()`.
1114
+ - `tk.std.scc(view)`: the strongly connected components (Tarjan), each after every component it reaches: callees
1115
+ before callers.
1116
+
1117
+ ```js
1118
+ const calls = tk.view.graph({
1119
+ nodes: ['main', 'a', 'b', 'c'],
1120
+ succ: n => ({ main: ['a'], a: ['b'], b: ['a', 'c'], c: [] })[n],
1121
+ });
1122
+ tk.std.scc(calls); // [['c'], ['a', 'b'], ['main']]
1123
+ tk.std.dominators(calls).dominates('a', 'c'); // true
1124
+ tk.std.depthFirst(calls).rpo; // ['main', 'a', 'b', 'c']
1125
+ tk.std.depthFirst(calls).retreating.map(e => `${e.from} -> ${e.to}`); // ['b -> a']
1126
+
1127
+ const [loop] = f.get(tk.std.loops).all;
1128
+ [loop.header.name, loop.preheader.name, loop.depth]; // ['head', 'entry', 1]
1129
+ loop.body.map(b => b.name); // ['head', 'body']
1130
+ loop.exits.map(b => b.name); // ['exit']
1131
+ ```
1132
+
1133
+ ### Dataflow
1134
+
1135
+ `tk.std.dataflow(view, problem)` solves a monotone dataflow problem with a worklist, and returns `{ in(node),
1136
+ out(node), iterations }`. The problem gives:
1137
+
1138
+ | Field | Meaning |
1139
+ |---|---|
1140
+ | `dir` | `'forward'` (default) or `'backward'` |
1141
+ | `bottom()`, `join(a, b)`, `equal(a, b)` | the lattice; spread one of `tk.lattice`'s |
1142
+ | `transfer(node, x)` | a node's effect: from its in-value to its out-value (forward), or out to in (backward) |
1143
+ | `boundary` | the value at the entry (forward) or at nodes without successors (backward); default `bottom()` |
1144
+ | `widen(old, new, node)` | applied at loop heads, for lattices with infinite chains |
1145
+ | `max` | visits before it gives up and throws; default 100,000 |
1146
+
1147
+ `tk.lattice.sets` is the lattice of sets under union. `tk.lattice.constants` maps names to constants: a name known to
1148
+ have two different values maps to `tk.lattice.TOP`.
1149
+
1150
+ ```js
1151
+ const facts = { entry: [['x', 1]], left: [['y', 2]], right: [['y', 3]], join: [] };
1152
+ const diamond = tk.view.graph({
1153
+ nodes: Object.keys(facts),
1154
+ succ: n => ({ entry: ['left', 'right'], left: ['join'], right: ['join'], join: [] })[n],
1155
+ });
1156
+ const cp = tk.std.dataflow(diamond, {
1157
+ ...tk.lattice.constants,
1158
+ transfer: (n, known) => new Map([...known, ...facts[n]]),
1159
+ });
1160
+ cp.in('join').get('x'); // 1
1161
+ cp.in('join').get('y') === tk.lattice.TOP; // true: 2 on one path, 3 on the other
1162
+
1163
+ const reach = tk.std.dataflow(calls, { ...tk.lattice.sets, transfer: (n, seen) => new Set([...seen, n]) });
1164
+ [...reach.out('c')]; // ['main', 'a', 'b', 'c']
1165
+ ```
1166
+
1167
+ ### Assembly: `asm`
1168
+
1169
+ `tk.std.asm` is described in section 10.
1170
+
1171
+ ## 12. Modules, snapshots, diffs and side tables
1172
+
1173
+ A module holds functions by name: `mod.fn(name)`, `mod.fns`, `mod.remove(name)`, and `mod.size`, the number of values
1174
+ in all of them. It also keeps a log of every change, `mod.log`, whose entries are `{ fn, by, what, value }`, and a
1175
+ `revision` that every change increments.
1176
+
1177
+ `mod.clone()` makes an editable copy. Each value of the copy has the value it copies as its origin, and traces treat
1178
+ the two as one (section 13); side tables and `meta` are copied too. `mod.snapshot()` makes a read-only copy, labelled
1179
+ `r` and the module's revision, and `mod.diff(snapshot)` reports what happened since, by function and by actor:
1180
+
1181
+ ```js
1182
+ const mod = Mini.module();
1183
+ sum(mod);
1184
+ mod.fn('g', ['a'], (b, a) => b.ret(b.add(b.mul(a, b.const(8)), b.const(0))));
1185
+ const before = mod.snapshot();
1186
+ mod.apply(tk.seq(peephole, licm, tk.std.dce));
1187
+ mod.diff(before).print();
1188
+ before.label; // 'r27'
1189
+ before.fn('g').values()[0].erase(); // TkError: snapshot r27 is read-only: .clone() gives an editable copy
1190
+ mod.log[mod.log.length - 1].what; // 'erase'
1191
+ ```
1192
+
1193
+ ```text
1194
+ sum 11 -> 11 values
1195
+ licm: move 1
1196
+ g 5 -> 3 values
1197
+ peephole: mul-pow2: create 2, replace 1
1198
+ peephole: add-zero: replace 1
1199
+ dce: erase 2
1200
+ ```
1201
+
1202
+ `diff` returns `{ events, toString(), print() }`; `events` are the log entries since the snapshot. Only a snapshot of
1203
+ the module itself can be compared against.
1204
+
1205
+ A side table attaches data to values without changing the IR: `tk.attr(name)` makes one, with `set(v, x)` (which
1206
+ returns the table), `get(v)`, `has(v)` and `delete(v)`. With `{ follows: 'replace' }`, an entry follows its value to
1207
+ the value that replaces it through `replaceWith`, unless the replacement has an entry of its own. Clones copy every
1208
+ side table's entries to the copied values.
1209
+
1210
+ ```js
1211
+ const home = tk.attr('home', { follows: 'replace' });
1212
+ const note = tk.attr('note');
1213
+ const g = mod.fn('g');
1214
+ const shl = g.values('shl')[0];
1215
+ home.set(shl, 'stack+8');
1216
+ note.set(shl, 'from x * 8');
1217
+ const w = shl.replaceWith(b => b.mul(shl.arg(0), b.const(8)));
1218
+ home.get(w); // 'stack+8'
1219
+ note.has(w); // false: note does not follow
1220
+ home.get(mod.clone().fn('g').values('mul')[0]); // 'stack+8': a clone copies the entries
1221
+ ```
1222
+
1223
+ `mod.meta` and `f.meta` are for a frontend's own data; a clone deep-copies them:
1224
+
1225
+ ```js
1226
+ mod.meta.target = 'rv32';
1227
+ const copy = mod.clone();
1228
+ copy.meta.target; // 'rv32'
1229
+ copy.fn('g').values('mul')[0].origin()[0] === mod.fn('g').values('mul')[0]; // true
1230
+ ```
1231
+
1232
+ ## 13. Provenance and traces
1233
+
1234
+ Nobody writes provenance: every mutation records the actor running at the time.
1235
+
1236
+ | Actor | When |
1237
+ |---|---|
1238
+ | `build` | inside the body of `mod.fn(name, params, body)` |
1239
+ | a pass's name | while the pass runs |
1240
+ | `pass: rule` | while a rule of a rule set fires, as `peephole: const-right` |
1241
+ | a lowering's name | while the lowering runs |
1242
+ | `choose` | when `tk.choose` adopts the cheapest clone |
1243
+ | `user` | anywhere else |
1244
+
1245
+ Three records follow from that:
1246
+
1247
+ - `v.history()`: what happened to the value, oldest first: `created by build`, `peephole: mul-pow2: replaced by %6`,
1248
+ `licm: moved to entry`, `user: arg 1 set to %a`, and so on.
1249
+ - `v.origin()`: the values it was made from. A replacement built in `replaceWith` or by a rule has the replaced value;
1250
+ a lowered value has its source value; a cloned value has the value it copies. A value built by a frontend has none,
1251
+ but may have a source position, `v.loc`, from `b.loc(where, text)`.
1252
+ - `v.trace()`: the chain of origins, newest first, one row per value: its IR, how it prints, and who made it. A value
1253
+ and its clones are one row, and building or being replaced is not shown, as the row above already says it. The chain
1254
+ ends with the source position. It returns `{ rows, toString(), print() }`.
1255
+
1256
+ The frontend used in the rest of this guide builds `sum` with source positions, as a parser would:
1257
+
1258
+ ```js
1259
+ // used in the rest of this guide
1260
+ const O2 = tk.seq(tk.fixpoint(tk.seq(tk.std.fold, peephole, tk.std.dce)), licm);
1261
+
1262
+ /** a frontend: builder calls with source positions; a parser's tree would be walked the same way */
1263
+ const frontend = step => {
1264
+ const mod = Mini.module();
1265
+ mod.fn('sum', ['n'], (b, n) => {
1266
+ const entry = b.current, head = b.block('head'), body = b.block('body'), exit = b.block('exit');
1267
+ const zero = b.loc('sum.js:2', 'let s = 0, i = 0').const(0);
1268
+ b.br(head).at(head);
1269
+ const i = b.phi().named('i'), s = b.phi().named('s');
1270
+ b.loc('sum.js:3', 'i < n').cbr(b.lt(i, n), body, exit).at(body);
1271
+ const s1 = b.loc('sum.js:4', 's = s + i').add(s, i).named('s1');
1272
+ const i1 = b.loc('sum.js:5', `i = i + ${step}`).add(b.const(step), i).named('i1');
1273
+ b.br(head).at(exit).loc('sum.js:7', 'return s').ret(s);
1274
+ i.incoming(entry, zero).incoming(body, i1);
1275
+ s.incoming(entry, zero).incoming(body, s1);
1276
+ });
1277
+ return mod;
1278
+ };
1279
+ ```
1280
+
1281
+ ```js
1282
+ const mini = frontend(1);
1283
+ const opt = mini.clone().apply(O2);
1284
+ const rv = select.run(opt).apply(tk.std.dce);
1285
+ const i1 = rv.fn('sum').values().find(v => v.name === 'i1');
1286
+ i1.trace().print();
1287
+ i1.history(); // ['created by select']
1288
+ opt.fn('sum').values().find(v => v.name === 'i1').history(); // ['created by peephole: const-right']
1289
+ ```
1290
+
1291
+ ```text
1292
+ rv32 %i1 = addi %i, 1 select
1293
+ mini %i1 = add %i, %8 peephole: const-right
1294
+ mini %i1 = add %6, %i
1295
+ source i = i + 1 sum.js:5
1296
+ ```
1297
+
1298
+ Read from the bottom up: line 5 of the source became `add %6, %i`, with the constant on the left as written; the rule
1299
+ `const-right` rebuilt it as `add %i, %8`, and `licm` moved the new constant to the entry block; instruction selection
1300
+ turned it into `addi`, with the constant as an immediate. The name `i1` followed the value through each replacement.
1301
+
1302
+ A line of assembly traces the same way:
1303
+
1304
+ ```js
1305
+ const asm = tk.std.asm(rv);
1306
+ asm.line(asm.find(/addi/)).trace().print();
1307
+ ```
1308
+
1309
+ ```text
1310
+ asm 13 addi %i1, %i, 1
1311
+ rv32 %i1 = addi %i, 1 select
1312
+ mini %i1 = add %i, %8 peephole: const-right
1313
+ mini %i1 = add %6, %i
1314
+ source i = i + 1 sum.js:5
1315
+ ```
1316
+
1317
+ ## 14. The stage graph
1318
+
1319
+ A stage graph names each stage of a compiler and the stages it depends on: `tk.graph(name)`, then
1320
+ `.node(name, deps, f)`, where `f` receives the values of `deps` in order (`.node(name, f)` for a stage without
1321
+ dependencies). `get(name)` computes whatever is missing and caches it. A stage is computed again only when a stage it
1322
+ depends on has a new value: `set(name, value)` gives a stage a value of its own, and `invalidate(name)` forgets a
1323
+ stage's value, including a set one, so it is computed again when read. `runs(name)` counts how often a stage has been
1324
+ computed, and `names` lists the stages.
1325
+
1326
+ ```js
1327
+ const build = tk.graph('mini -> rv32')
1328
+ .node('step', () => 1)
1329
+ .node('mini', ['step'], step => frontend(step))
1330
+ .node('opt', ['mini'], m => m.clone().apply(O2))
1331
+ .node('rv', ['opt'], m => select.run(m).apply(tk.std.dce))
1332
+ .node('asm', ['rv'], m => tk.std.asm(m));
1333
+
1334
+ build.get('opt').run('sum', [10]); // 45
1335
+ build.get('rv').run('sum', [10]); // 45
1336
+ build.get('asm').find(/addi/); // 13
1337
+ build.get('asm') === build.get('asm'); // true: cached
1338
+ build.runs('opt'); // 1
1339
+ build.set('step', 2);
1340
+ build.get('rv').run('sum', [10]); // 20
1341
+ build.runs('opt'); // 2
1342
+ build.runs('asm'); // 1: not read since
1343
+ build.invalidate('step');
1344
+ build.get('rv').run('sum', [10]); // 45
1345
+ build.names; // ['step', 'mini', 'opt', 'rv', 'asm']
1346
+ ```
1347
+
1348
+ A dependency must exist when a stage names it, and a name read must exist:
1349
+
1350
+ ```js
1351
+ build.get('rv2'); // TypeError: stage graph mini -> rv32 has no node 'rv2': did you mean 'rv'?
1352
+ tk.graph('g').node('a', ['b'], b => b); // TypeError: stage graph g has no node 'b' (a dependency of a)
1353
+ tk.graph('c').node('a', () => 1).node('b', ['a'], a => a).node('a', ['b'], b => b).get('a'); // TkError: stage graph c: a cycle a -> b -> a
1354
+ ```
1355
+
1356
+ ## 15. The checks mode
1357
+
1358
+ The toolkit can check its own use. With checks on:
1359
+
1360
+ - its objects are proxies that turn a misspelled or missing member into an error naming what exists and the closest
1361
+ match, instead of `undefined` three calls later;
1362
+ - an analysis result throws once its function has changed, whether a member is read or a method taken out of it
1363
+ earlier is called;
1364
+ - a pass that reads an analysis it did not ask for in `.needs` gets an error.
1365
+
1366
+ Checks never change what a pass computes, only how early a mistake throws. They are off by default, because a proxy
1367
+ runs on every property read: measured on the toolkit's own benchmark, they make passes that read many properties 3
1368
+ to 9 times slower under node and 2 to 4 times slower under QuickJS
1369
+ (`scripts/checks-cost.bench.mjs`).
1370
+
1371
+ Some validation runs in both modes, because it runs once per creation or definition rather than on every read: the
1372
+ arguments and attributes of each new value, op and attribute definitions, rule patterns and their bindings, and
1373
+ lowering cases.
1374
+
1375
+ Turn checks on to write or debug passes, and in tests, in one of three ways:
1376
+
1377
+ - `TK_CHECKS=1` in the environment (any value but `0`, `false` or empty turns them on);
1378
+ - `globalThis.TK_CHECKS = true` before the toolkit loads, where there is no environment (QuickJS);
1379
+ - `tk.checks(true)` in the program, before the objects to be checked are made.
1380
+
1381
+ An object keeps the mode it was made in: `tk.checks(true)` covers the IRs, modules, values, builders and passes made
1382
+ after it. `tk`, `tk.std` and `tk.frag` are made when the toolkit loads, so only the first two ways cover them.
1383
+ `tk.checks()` says whether checks are on.
1384
+
1385
+ ```js
1386
+ tk.checks(true);
1387
+ const C = tk.ir('c')
1388
+ .use(tk.frag.cfg)
1389
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
1390
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 });
1391
+ const mod = C.module();
1392
+ const f = mod.fn('f', ['x'], (b, x) => {
1393
+ b.ad(x, x); // TypeError: c has no op 'ad': did you mean 'add'? (ops: br, cbr, ret, const, add)
1394
+ b.ret(b.add(x, b.const(1)));
1395
+ });
1396
+ f.values('add')[0].agrs; // TypeError: c value %2 (add) has no 'agrs': did you mean 'args'?
1397
+ f.blcoks; // TypeError: function f has no 'blcoks': did you mean 'blocks'?
1398
+
1399
+ mod.apply(tk.pass('p').run((fn, { loops }) => loops)); // TkError: pass p did not ask for 'loops': add it to .needs({ … }) (it needs: nothing)
1400
+
1401
+ const { dominates } = f.get(tk.std.dominators);
1402
+ f.addBlock('extra');
1403
+ dominates(f.entry, f.entry); // TkError: dominators of f is from revision 2, and f is now at revision 3: call f.get(dominators) again
1404
+ tk.checks(false);
1405
+ ```
1406
+
1407
+ Without checks, `b.ad(x, x)` is JavaScript's own `TypeError` (`b.ad is not a function`), `.agrs` and `.blcoks` are
1408
+ `undefined`, an analysis not asked for is `undefined`, and a stale result answers from old data.
1409
+
1410
+ Tests should pass in both modes: `npm test` runs the suite twice, with checks off and with `TK_CHECKS=1`. A test that
1411
+ asserts a check's error branches on `tk.checks()`:
1412
+
1413
+ ```js
1414
+ const tb = tk.ir('t').op('add', { args: 2 }).builder();
1415
+ let message;
1416
+ try {
1417
+ tb.ad();
1418
+ } catch (e) {
1419
+ message = e.message;
1420
+ }
1421
+ const expected = tk.checks() ? "t has no op 'ad': did you mean 'add'? (ops: add)" : 'tb.ad is not a function';
1422
+ console.log(message === expected);
1423
+ ```
1424
+
1425
+ ```text
1426
+ true
1427
+ ```
1428
+
1429
+ ## 16. Running under QuickJS
1430
+
1431
+ The toolkit also runs under QuickJS, the JavaScript engine of the ESP32-P4 board that gb-riscv32 compiles for. It
1432
+ uses nothing beyond what that QuickJS has: in particular, the toolkit and its tests do not use `structuredClone` or
1433
+ `Array.prototype.at`, which it lacks, and nor should code meant to run there.
1434
+
1435
+ `scripts/quickjs-check.mjs` runs the test files under QuickJS (`npm run test:quickjs` runs it on every test file):
1436
+
1437
+ ```sh
1438
+ QJS_STACK=57344 QJS=/path/to/qjs-run node scripts/quickjs-check.mjs [test files…]
1439
+ ```
1440
+
1441
+ - `QJS` is a host QuickJS runner that evaluates one plain script and prints with `print`: gb-riscv32 builds one
1442
+ (`build/qjs/qjs-run`, from its GBRV-004 `scripts/10-qjs-runner.c`) over the QuickJS the P4 firmware embeds.
1443
+ - `QJS_STACK` is the runner's limit on the JavaScript stack, in bytes (default 1 MiB); 57344 is the P4's 56 KB.
1444
+ - Without arguments the script runs `test/*.test.mjs`; with arguments, the files named.
1445
+ - The runner evaluates plain scripts only, so the script bundles each file with the toolkit's modules: every module
1446
+ becomes a function scope that returns its exports. It understands one-line `import { … } from '…'` and
1447
+ `import x from '…'`, and `export const|let|function|class` and `export { … }`. `node:test` and
1448
+ `node:assert/strict` are replaced by small shims (`test`; `equal`, `deepEqual`, `ok`, `match`, `throws`); any other
1449
+ package import is an error.
1450
+ - Each file runs twice, with checks off and with `globalThis.TK_CHECKS = true` at the top of the bundle. Each run
1451
+ prints a line per test and a summary `passed N, failed M`; the script exits 1 unless every run ends with
1452
+ `failed 0`.
1453
+ - The bundles are written to `$OUT`, or to a new temporary directory, and their paths are printed.
1454
+
1455
+ ## 17. Reference
1456
+
1457
+ Every public function, member and option, by object. "Throws" names the errors raised in both check modes.
1458
+
1459
+ ### `tk`
1460
+
1461
+ | Member | Signature | Returns |
1462
+ |---|---|---|
1463
+ | `tk.ir` | `(name)` | a new IR, with the built-in op `param` |
1464
+ | `tk.fragment` | `(name)` | a new fragment |
1465
+ | `tk.frag` | `{ cfg, ssa, edges, machine }` | the built-in fragments |
1466
+ | `tk.rules` | `(name, IR)` | a new rule set over the IR's ops; throws unless the second argument is an IR |
1467
+ | `tk.pass` | `(name)` | a new pass, without a body |
1468
+ | `tk.analysis` | `(name, compute, { on: 'all' \| 'cfg' })` | an analysis; `on` defaults to `'all'`; throws unless `compute` is a function |
1469
+ | `tk.seq` | `(...passes)` | a pass that applies them in order |
1470
+ | `tk.fixpoint` | `(pass, { max: 100 })` | a pass that repeats `pass` until the target's revision stops changing |
1471
+ | `tk.when` | `(fn => bool, pass)` | a pass that applies `pass` to the functions the predicate accepts |
1472
+ | `tk.choose` | `(alternatives, module => cost)` | a pass, for modules only, that keeps the cheapest alternative |
1473
+ | `tk.lower` | `(from, to, name)` | a new lowering between two IRs; `name` defaults to `'<from>-><to>'` |
1474
+ | `tk.attr` | `(name, { follows: 'replace' })` | a new side table; `follows` is `'replace'` or absent |
1475
+ | `tk.graph` | `(name)` | a new stage graph |
1476
+ | `tk.view.graph` | `({ nodes, succ, entry })` | a graph view for `tk.std`; `entry` defaults to `nodes[0]` |
1477
+ | `tk.std` | | `fold`, `dce`, `verifySSA`, `depthFirst`, `dominators`, `loops`, `scc`, `dataflow`, `asm` |
1478
+ | `tk.lattice` | | `sets`, `constants`, `TOP` |
1479
+ | `tk.regs` | `WeakMap` | value to physical register name, read by `v.reg` and `tk.std.asm` |
1480
+ | `tk.checks` | `(on?)` | whether checks are on; with an argument, sets the mode for objects made from then on |
1481
+ | `tk.TkError` | class | the toolkit's error class (also exported as `TkError`) |
1482
+
1483
+ ### IR (`tk.ir(name)`)
1484
+
1485
+ | Member | What it does |
1486
+ |---|---|
1487
+ | `op(name, spec)` | adds an op (spec fields in section 2); returns the IR. Throws for a name that is not an identifier, a name defined already, an `args` that is not a count or `'*'`, an unknown attribute type, an attribute that would hide a value member, an `eval` that is not a function |
1488
+ | `use(...fragments)` | applies fragments (each once); returns the IR |
1489
+ | `extend(names, fragmentOrFields)` | applies a fragment, or plain spec fields, to the named ops (a name or an array); returns the IR |
1490
+ | `builder()` | a builder of free expressions |
1491
+ | `module()` | a new, empty module |
1492
+ | `eval(value, ctx = {})` | evaluates an expression with the ops' `eval` lambdas |
1493
+ | `opNames` | the op names, without `param` |
1494
+ | `opNamed(name)` | the op; throws for an unknown name, with a "did you mean" |
1495
+ | `name`, `ops`, `fragments` | the name, a `Map` of the ops, the fragments used |
1496
+ | `hasBlocks`, `machine`, `constOp` | set by `cfg` or `edges`; set by `machine` (`{ asm: { kind: template } }`); the op `fold` builds |
1497
+
1498
+ An op (`v.op`, `IR.ops.get(name)`) has `name`, `ir`, `spec`, `args` (the count or `'*'`), `attrs`, `attrNames`,
1499
+ `terminator`, and `hasResult(attrs)`.
1500
+
1501
+ ### Builder (`IR.builder()`, the `b` of `mod.fn`, of `replaceWith` and of `.to`)
1502
+
1503
+ | Member | What it does |
1504
+ |---|---|
1505
+ | one method per op | `b.kind(...argValues, ...attrs)` or `b.kind(...argValues, { attr: value })`: creates a value. Throws for a wrong argument count, an unknown, missing or ill-typed attribute, an argument from another IR, function or builder, or an erased argument |
1506
+ | `current`, `entry` | the block being built; the function's entry block |
1507
+ | `block(name?)` | a new block (default name `b<n>`; a taken name gets `'`); the builder does not move |
1508
+ | `at(block)` | continue at the end of a block of the same function; returns the builder |
1509
+ | `before(value)` | insert before a value; returns the builder |
1510
+ | `id(n)` | the next value with a result takes the id `n`; returns the builder |
1511
+ | `loc(where, text = '')`, `loc(null)` | the source position of the values built next, or none; returns the builder |
1512
+ | `fn`, `ir` | the function (an expression graph for `IR.builder()`), the IR |
1513
+ | `br(block)`, `cbr(cond, then, else)`, `ret(value)` | `tk.frag.cfg`'s terminators; return the builder |
1514
+ | `phi()` | `tk.frag.ssa`: a phi at the start of the current block |
1515
+ | `params(block, n, { ids })` | `tk.frag.edges`: `n` new parameters of a block |
1516
+ | `jump(edge)`, `br(cond, then, else, hint?)`, `switch(x, [[k, edge], …], dflt)`, `ret(...values)`, `trap()` | `tk.frag.edges`'s terminators, with edges `block.to(...args)`; return the builder |
1517
+
1518
+ ### Module (`IR.module()`)
1519
+
1520
+ | Member | What it does |
1521
+ |---|---|
1522
+ | `fn(name)` | the function; throws for an unknown name, with a "did you mean" |
1523
+ | `fn(name, params, body, { entry, ids })` | defines a function (section 4); throws if the IR has no blocks or the name is taken |
1524
+ | `fns`, `size` | the functions, in definition order; the number of values in all of them |
1525
+ | `apply(pass)` | applies a pass; returns the module |
1526
+ | `run(name, args = [], ctx = {})` | runs a function with the ops' `eval` and `control` lambdas and returns its result; `ctx.fuel` (default 10,000,000) bounds the values evaluated |
1527
+ | `clone()` | an editable copy (section 12) |
1528
+ | `snapshot()` | a read-only copy, labelled `r<revision>` |
1529
+ | `diff(snapshot)` | `{ events, toString(), print() }`: the changes since a snapshot of this module |
1530
+ | `remove(name)` | removes a function; returns the module |
1531
+ | `adopt(other)` | takes another module's functions (what `tk.choose` does) |
1532
+ | `ir`, `revision`, `log`, `choices`, `meta` | the IR; a counter every change increments; the change log `{ fn, by, what, value }`; `tk.choose`'s records `{ picked, costs: [{ name, cost }] }`; free data |
1533
+ | `readOnly`, `label` | whether it is a snapshot; its label |
1534
+ | `toString()`, `print()` | the text of every function; print it and return the module |
1535
+
1536
+ A snapshot's mutations, including `remove` and `adopt`, throw `TkError: snapshot <label> is read-only: .clone() gives
1537
+ an editable copy`.
1538
+
1539
+ ### Function (`mod.fn(...)`)
1540
+
1541
+ | Member | What it does |
1542
+ |---|---|
1543
+ | `blocks`, `entry`, `params` | the blocks in order, the entry block, the parameters (`param` values) |
1544
+ | `block(name)` | the block; throws for an unknown name, with a "did you mean" |
1545
+ | `values(kind?)` | the values in block order (an expression graph's in creation order), or those of one op; throws for an unknown op |
1546
+ | `size` | the number of values |
1547
+ | `addBlock(name?)` | a new block |
1548
+ | `eraseAll(values)` | erases a set of values whose uses are all inside the set; returns the count |
1549
+ | `get(analysis)` | the analysis' result for this revision (section 9) |
1550
+ | `apply(pass)` | applies a pass; returns the function |
1551
+ | `graph` | the block graph as a view `{ nodes, entry, succ }` |
1552
+ | `revision`, `cfgRevision` | change counters (section 9) |
1553
+ | `nextId` | the id the next value with a result takes |
1554
+ | `module`, `name`, `ir`, `expr`, `root`, `meta` | the module (`null` for an expression graph); its name; its IR; whether it is an expression graph; an expression graph's root; free data |
1555
+ | `toString()`, `print()` | its text; print it and return the function |
1556
+
1557
+ ### Block (`b.block(name)`, `f.block(name)`)
1558
+
1559
+ | Member | What it does |
1560
+ |---|---|
1561
+ | `values()` | its values, in order |
1562
+ | `terminator` | its last value if that is a terminator, else `null` |
1563
+ | `succs`, `preds` | the blocks its terminator goes to; the blocks whose terminators go to it |
1564
+ | `phis`, `params` | its phis; its parameters (`tk.frag.edges`) |
1565
+ | `to(...args)` | an edge to this block, passing `args` to its parameters (`tk.frag.edges`) |
1566
+ | `fn`, `name` | its function, its name |
1567
+
1568
+ ### Value
1569
+
1570
+ Reading: `kind`, `op`, `spec`, `ir`, `args`, `arg(i)`, `attrs` and one getter per attribute, `uses`, `block`, `fn`,
1571
+ `id`, `name`, `ref`, `hasResult`, `pure`, `erased`, `is(kind, attrs?)`, `targets`, `incomingBlocks`, `edgeArgc`,
1572
+ `loc` (section 5).
1573
+
1574
+ | Member | What it does |
1575
+ |---|---|
1576
+ | `named(name)` | names the value; returns it |
1577
+ | `replaceWith(valueOrBuilderFn)` | section 5; returns the replacement. Throws if the value is erased, the replacement is not a value or belongs to another function |
1578
+ | `replaceUses(value)` | section 5; returns this value. Throws if the argument is not a value of the same function |
1579
+ | `erase()` | section 5; throws while uses remain; does nothing to an erased value |
1580
+ | `moveTo(block)` | section 5; returns the value. Throws for a block of another function |
1581
+ | `setArg(i, value)`, `swapArgs()` | section 5; return the value. `swapArgs` throws unless the value has two arguments |
1582
+ | `apply(pass)` | for a value of an expression graph: applies the pass with this value as the root; returns the root afterwards. Throws for a value in a function |
1583
+ | `history()`, `origin()`, `trace()` | section 13 |
1584
+ | `toString()`, `print()` | as an expression tree, or as an instruction; print it and return the value |
1585
+ | `incoming(block, value)` | `tk.frag.ssa`, on a phi: adds an input; returns the phi |
1586
+ | `own`, `edges`, `setEdge(k, edge)` | `tk.frag.edges`, on a terminator: its own operands; its edges `{ block, args }`; redirects edge `k` and returns the terminator |
1587
+ | `reg` | `tk.frag.machine`: its register, from `tk.regs`, else its `ref` |
1588
+
1589
+ ### Fragment (`tk.fragment(name)`)
1590
+
1591
+ | Member | What it does |
1592
+ |---|---|
1593
+ | `op(members)` | members of every value the fragment is applied to (`this` is the value); getters are kept |
1594
+ | `builder(members)` | members of the builders of the IRs that use it (`this` is the builder) |
1595
+ | `define(ir => …)` | setup run once on each IR that uses it |
1596
+ | `name` | its name |
1597
+
1598
+ ### Rule set (`tk.rules(name, IR)`)
1599
+
1600
+ | Member | What it does |
1601
+ |---|---|
1602
+ | `rule(name)` | starts a rule; throws if the set has one of that name |
1603
+ | `match(pattern)` | the current rule's pattern (section 7); throws for a pattern that does not parse or does not fit the IR |
1604
+ | `when(bindings => bool)` | the current rule's condition |
1605
+ | `to((bindings, b) => value)` | the current rule's replacement |
1606
+ | `names` | the rule names, in order |
1607
+ | `without(...names)` | a new set without those rules; throws for an unknown name |
1608
+ | `with(...sets)` | a new set with the other sets' rules after its own |
1609
+ | `name`, `ir`, `list` | its name, its IR, its rules `{ name, text, pattern, vars, when, to }` |
1610
+
1611
+ ### Pass (`tk.pass(name)`)
1612
+
1613
+ | Member | What it does |
1614
+ |---|---|
1615
+ | `each(f)`, `run(f)`, `module(f)`, `rules(...sets)` | the body (section 6); the first three throw if the pass has one already |
1616
+ | `needs({ name: analysis })` | the analyses the body receives |
1617
+ | `about(text)` | a description, kept in `text` |
1618
+ | `applyTo(target)` | applies the pass to a module, a function or an expression graph; returns the target. Throws if the pass has no body |
1619
+ | `name`, `text`, `kind` | its name, description and body kind (`'each'`, `'run'`, `'module'`, `'rules'`) |
1620
+
1621
+ A combinator's result has `name` and `applyTo(target)`.
1622
+
1623
+ ### Analysis (`tk.analysis(name, compute, { on })`)
1624
+
1625
+ `analysisName`, `compute(fn)`, `on` (`'all'` or `'cfg'`). A plain function of a function is an analysis too, named by
1626
+ its JavaScript name and with an optional `on` property.
1627
+
1628
+ ### Lowering (`tk.lower(from, to, name)`)
1629
+
1630
+ | Member | What it does |
1631
+ |---|---|
1632
+ | `op(kind, (v, b, args, blocks) => value)` | the case for a source op (section 10); throws for an op the source IR does not have |
1633
+ | `run(module)` | a new module of the target IR; throws for a module of another IR, for a source op without a case, and for a value used before it is lowered |
1634
+ | `from`, `to`, `name`, `cases` | the IRs, its name, a `Map` of its cases |
1635
+
1636
+ ### Side table (`tk.attr(name, { follows })`)
1637
+
1638
+ `set(value, x)` (returns the table), `get(value)`, `has(value)`, `delete(value)`, `name`. Entries are held weakly.
1639
+
1640
+ ### Stage graph (`tk.graph(name)`)
1641
+
1642
+ | Member | What it does |
1643
+ |---|---|
1644
+ | `node(name, deps, f)`, `node(name, f)` | defines a stage; throws for a dependency that does not exist |
1645
+ | `get(name)` | the stage's value, computed if missing or out of date; throws for an unknown name and for a cycle |
1646
+ | `set(name, value)` | gives a stage a value of its own; the stages after it are recomputed when read |
1647
+ | `invalidate(name)` | forgets a stage's value (and a set one) |
1648
+ | `runs(name)` | how often a stage was computed |
1649
+ | `names` | the stage names |
1650
+
1651
+ ### The standard library (`tk.std`, `tk.lattice`)
1652
+
1653
+ | Member | Signature | Returns |
1654
+ |---|---|---|
1655
+ | `fold`, `dce`, `verifySSA` | passes | section 11 |
1656
+ | `depthFirst` | `(view)` | `{ postorder, rpo, retreating: [{ from, to }] }` |
1657
+ | `dominators` | `(view, { root })` | `{ idom, rpo, dominates(a, b), children(n), idomOf(n) }`; `on = 'cfg'` |
1658
+ | `loops` | `(view)` | `{ all, innermostFirst(), of(block), depthOf(block) }`; each loop `{ header, latches, body, exits, preheader, depth, contains(x), values() }`; `on = 'cfg'` |
1659
+ | `scc` | `(view)` | an array of components, each an array of nodes, callees first |
1660
+ | `dataflow` | `(view, { dir, bottom, join, equal, transfer, boundary, widen, max })` | `{ in(node), out(node), iterations }` |
1661
+ | `asm` | `(machineModule)` | `{ lines: [{ text, value }], line(n), find(regex), toString(), print() }`; throws for a module whose IR is not a machine IR, and for an op without a template |
1662
+ | `tk.lattice.sets` | `{ bottom, join, equal }` | sets under union |
1663
+ | `tk.lattice.constants` | `{ bottom, join, equal }` | `Map`s from names to values; a conflict joins to `TOP` |
1664
+ | `tk.lattice.TOP` | symbol | "not a constant" |
1665
+
1666
+ A view is a function or `{ nodes, succ, entry }`.
1667
+
1668
+ ### Errors
1669
+
1670
+ The toolkit throws a `TypeError` when the API is used wrongly (a wrong argument count or type, an unknown name) and a
1671
+ `TkError` when a request is not possible in the IR's current state (erasing a used value, changing a snapshot, a stale
1672
+ analysis, a rule set that does not terminate). With checks on, an unknown member of a toolkit object is a `TypeError`.