@geastack/compiler 1.0.22 → 1.0.23
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/dist/ir/borrow-effects.js +55 -1
- package/dist/ir/dense-loops.d.ts +16 -2
- package/dist/ir/dense-loops.js +66 -21
- package/dist/ir/facts.d.ts +6 -29
- package/dist/ir/facts.js +46 -1
- package/dist/ir/floats.d.ts +46 -0
- package/dist/ir/floats.js +196 -0
- package/dist/ir/hoist.d.ts +11 -2
- package/dist/ir/hoist.js +17 -2
- package/dist/ir/integer-storage.js +8 -4
- package/dist/ir/integers.d.ts +14 -0
- package/dist/ir/integers.js +55 -1
- package/dist/ir/numeric-intrinsics.d.ts +1 -1
- package/dist/ir/numeric-intrinsics.js +3 -2
- package/dist/targets/cpp/emit-arrays.d.ts +2 -1
- package/dist/targets/cpp/emit-arrays.js +7 -3
- package/dist/targets/cpp/emit-bindings.js +4 -2
- package/dist/targets/cpp/emit-callable.js +13 -0
- package/dist/targets/cpp/emit-carrier-members.d.ts +3 -1
- package/dist/targets/cpp/emit-carrier-members.js +18 -2
- package/dist/targets/cpp/emit-context.d.ts +13 -0
- package/dist/targets/cpp/emit-context.js +18 -2
- package/dist/targets/cpp/emit-properties.js +16 -3
- package/dist/targets/cpp/emit.js +36 -4
- package/dist/targets/cpp/host/emit-host-invoke.js +10 -1
- package/dist/targets/cpp/host/host-members.js +43 -30
- package/dist/targets/cpp/types.d.ts +2 -0
- package/dist/targets/cpp/types.js +2 -0
- package/package.json +9 -9
- package/src/targets/cpp/runtime/gea_runtime.h +80 -4
|
@@ -8,14 +8,66 @@ const primitive = (value) => {
|
|
|
8
8
|
return ['scalar', 'string', 'null', 'undefined', 'symbol'].includes(value.kind);
|
|
9
9
|
};
|
|
10
10
|
const number = (value) => value.kind === 'scalar' && value.domain === 'number';
|
|
11
|
+
/**
|
|
12
|
+
* `Math` functions that, given only Numbers, compute a Number and run
|
|
13
|
+
* nothing: no `valueOf` to coerce, no callback, no state. A stencil wraps
|
|
14
|
+
* every intermediate in `Math.fround` and clamps with `Math.min`/`Math.max`,
|
|
15
|
+
* so without these no such loop could keep a raw typed-array pointer.
|
|
16
|
+
*/
|
|
17
|
+
const pureNumericMath = new Set([
|
|
18
|
+
'abs',
|
|
19
|
+
'acos',
|
|
20
|
+
'acosh',
|
|
21
|
+
'asin',
|
|
22
|
+
'asinh',
|
|
23
|
+
'atan',
|
|
24
|
+
'atan2',
|
|
25
|
+
'atanh',
|
|
26
|
+
'cbrt',
|
|
27
|
+
'ceil',
|
|
28
|
+
'clz32',
|
|
29
|
+
'cos',
|
|
30
|
+
'cosh',
|
|
31
|
+
'exp',
|
|
32
|
+
'expm1',
|
|
33
|
+
'floor',
|
|
34
|
+
'fround',
|
|
35
|
+
'hypot',
|
|
36
|
+
'imul',
|
|
37
|
+
'log',
|
|
38
|
+
'log10',
|
|
39
|
+
'log1p',
|
|
40
|
+
'log2',
|
|
41
|
+
'max',
|
|
42
|
+
'min',
|
|
43
|
+
'pow',
|
|
44
|
+
'round',
|
|
45
|
+
'sign',
|
|
46
|
+
'sin',
|
|
47
|
+
'sinh',
|
|
48
|
+
'sqrt',
|
|
49
|
+
'tan',
|
|
50
|
+
'tanh',
|
|
51
|
+
'trunc'
|
|
52
|
+
]);
|
|
11
53
|
export const borrowSafeOperationsOf = (body, safeCallees = new Set(), plainFieldRead = () => false) => {
|
|
12
54
|
const keys = stringConstantsOf(body);
|
|
13
55
|
const nativeCharacterReads = new Set();
|
|
56
|
+
const mathReads = new Set();
|
|
14
57
|
const safe = new Set();
|
|
15
58
|
for (const block of body.blocks.values()) {
|
|
16
59
|
for (const operation of block.operations) {
|
|
17
60
|
if (operation.kind === 'get' && operation.receiver.representation.kind === 'string' && keys.get(operation.key.value) === 'charCodeAt')
|
|
18
61
|
nativeCharacterReads.add(operation.result.id);
|
|
62
|
+
// Authenticated by the native protocol, as `ir/floats.ts` authenticates
|
|
63
|
+
// `Math.fround`: a user object named Math has none.
|
|
64
|
+
const receiver = operation.kind === 'get' ? operation.receiver.representation : null;
|
|
65
|
+
if (operation.kind === 'get' &&
|
|
66
|
+
receiver?.kind === 'native-handle' &&
|
|
67
|
+
receiver.native === null &&
|
|
68
|
+
receiver.protocol === 'Math' &&
|
|
69
|
+
pureNumericMath.has(keys.get(operation.key.value) ?? ''))
|
|
70
|
+
mathReads.add(operation.result.id);
|
|
19
71
|
}
|
|
20
72
|
}
|
|
21
73
|
for (const block of body.blocks.values()) {
|
|
@@ -51,7 +103,8 @@ export const borrowSafeOperationsOf = (body, safeCallees = new Set(), plainField
|
|
|
51
103
|
case 'get': {
|
|
52
104
|
const receiver = operation.receiver.representation;
|
|
53
105
|
const key = keys.get(operation.key.value);
|
|
54
|
-
if ((
|
|
106
|
+
if (mathReads.has(operation.result.id) ||
|
|
107
|
+
(receiver.kind === 'string' && (key === 'length' || key === 'charCodeAt')) ||
|
|
55
108
|
(receiver.kind === 'typed-array' && (key === 'length' || number(operation.key.representation))))
|
|
56
109
|
safe.add(operation);
|
|
57
110
|
// A data field of a native object: `node.left` on a class instance
|
|
@@ -76,6 +129,7 @@ export const borrowSafeOperationsOf = (body, safeCallees = new Set(), plainField
|
|
|
76
129
|
break;
|
|
77
130
|
case 'call':
|
|
78
131
|
if (safeCallees.has(operation.callee.value) ||
|
|
132
|
+
(mathReads.has(operation.callee.value) && operation.arguments.every((argument) => number(argument.representation))) ||
|
|
79
133
|
(nativeCharacterReads.has(operation.callee.value) &&
|
|
80
134
|
operation.arguments.length === 1 &&
|
|
81
135
|
operation.arguments.every((argument) => number(argument.representation))))
|
package/dist/ir/dense-loops.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DeclarationId, IrValueId } from '../identity/ids.js';
|
|
2
|
+
import { type HoistPlan } from './hoist.js';
|
|
2
3
|
import type { Representation, TypedArrayElementDomain } from '../representation/model.js';
|
|
3
4
|
import type { IrBlockId, IrBody, IrNonTerminatorOperation, IrOperand } from './model.js';
|
|
4
5
|
/**
|
|
@@ -55,7 +56,7 @@ export interface DenseArray {
|
|
|
55
56
|
/** The block the flag and the pointer are computed in. */
|
|
56
57
|
readonly preheader: IrBlockId;
|
|
57
58
|
/** Every invariant addend used by an access, with `null` for the bare counter. All ranges must fit before any access is unchecked. */
|
|
58
|
-
readonly bases: readonly
|
|
59
|
+
readonly bases: readonly DenseOffset[];
|
|
59
60
|
/** The counter cell, read at the preheader for the lowest index the loop can touch. */
|
|
60
61
|
readonly counter: DeclarationId;
|
|
61
62
|
/** The loop's own bound. */
|
|
@@ -110,6 +111,19 @@ export interface DenseArray {
|
|
|
110
111
|
*/
|
|
111
112
|
readonly widened: boolean;
|
|
112
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* What an index adds to the counter: a signed sum of loop invariants, `null`
|
|
116
|
+
* for the bare counter. A stencil names its neighbours by subtracting
|
|
117
|
+
* (`u[c - 1]`, `u[c - PITCH]`) and by chaining (`u[c + up - 1]`), and every
|
|
118
|
+
* one of those is the counter plus a number the preheader can add up and
|
|
119
|
+
* check like any other base.
|
|
120
|
+
*/
|
|
121
|
+
export type DenseOffset = {
|
|
122
|
+
readonly terms: readonly {
|
|
123
|
+
readonly operand: IrOperand;
|
|
124
|
+
readonly negated: boolean;
|
|
125
|
+
}[];
|
|
126
|
+
} | null;
|
|
113
127
|
export type DenseReference = {
|
|
114
128
|
readonly kind: 'cell';
|
|
115
129
|
readonly declaration: DeclarationId;
|
|
@@ -227,4 +241,4 @@ export interface AdmittedDenseLoopPlan {
|
|
|
227
241
|
* chain is needed at all.
|
|
228
242
|
*/
|
|
229
243
|
export declare const admittedDenseLoopPlanOf: (plan: DenseLoopPlan, integerValues: ReadonlySet<IrValueId>, admitsCell: DenseCellPolicy) => AdmittedDenseLoopPlan;
|
|
230
|
-
export declare const denseLoopsOf: (body: IrBody) => DenseLoopPlan;
|
|
244
|
+
export declare const denseLoopsOf: (body: IrBody, hoists?: HoistPlan) => DenseLoopPlan;
|
package/dist/ir/dense-loops.js
CHANGED
|
@@ -84,7 +84,7 @@ export const admittedDenseLoopPlanOf = (plan, integerValues, admitsCell) => {
|
|
|
84
84
|
}
|
|
85
85
|
return { arrays, groups, accesses, lengths };
|
|
86
86
|
};
|
|
87
|
-
export const denseLoopsOf = (body) => {
|
|
87
|
+
export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
|
|
88
88
|
// A try region renders as one assembled chunk, so a preheader inside one has
|
|
89
89
|
// no single place for the setup to land -- the same restriction `hoist.ts`
|
|
90
90
|
// takes, and for the same reason.
|
|
@@ -141,7 +141,7 @@ export const denseLoopsOf = (body) => {
|
|
|
141
141
|
// loop's own body until `ir/hoist.ts` moves them to its preheader, and asking
|
|
142
142
|
// the raw IR where they are answers "inside the loop" for every one of them.
|
|
143
143
|
// `emitBody` runs the same plan, and renders it before this setup.
|
|
144
|
-
for (const [blockId, operations] of
|
|
144
|
+
for (const [blockId, operations] of hoists.into)
|
|
145
145
|
for (const operation of operations) {
|
|
146
146
|
blockOfOperation.set(operation, blockId);
|
|
147
147
|
const result = resultOfIrOperation(operation);
|
|
@@ -155,6 +155,29 @@ export const denseLoopsOf = (body) => {
|
|
|
155
155
|
const where = location.get(value);
|
|
156
156
|
return where === undefined || !blocks.has(where);
|
|
157
157
|
};
|
|
158
|
+
// A `const` local read inside a loop reaches it as a header phi whose
|
|
159
|
+
// incoming values are the one value from before the loop and the phi
|
|
160
|
+
// itself: invariant, but defined in the loop, so every offset Bloom's
|
|
161
|
+
// stencil adds to its counter (`c + up`) looked like an unbounded index.
|
|
162
|
+
// The preheader names what the phi always holds.
|
|
163
|
+
const invariantOperand = (operand, blocks) => {
|
|
164
|
+
const seen = new Set();
|
|
165
|
+
let current = operand;
|
|
166
|
+
while (!definedOutside(current.value, blocks)) {
|
|
167
|
+
if (seen.has(current.value))
|
|
168
|
+
return null;
|
|
169
|
+
seen.add(current.value);
|
|
170
|
+
const phi = operationOf.get(current.value);
|
|
171
|
+
if (phi?.kind !== 'phi')
|
|
172
|
+
return null;
|
|
173
|
+
const sources = phi.incoming.map((incoming) => incoming.value).filter((value) => !seen.has(value.value));
|
|
174
|
+
const first = sources[0];
|
|
175
|
+
if (first === undefined || sources.some((source) => source.value !== first.value))
|
|
176
|
+
return null;
|
|
177
|
+
current = first;
|
|
178
|
+
}
|
|
179
|
+
return current;
|
|
180
|
+
};
|
|
158
181
|
// A value the preheader may NAME: defined before the loop, so it is both
|
|
159
182
|
// unchanged by the loop (SSA) and already assigned where the setup renders.
|
|
160
183
|
// A cell the loop never writes is not enough -- the READ of it can be one of
|
|
@@ -168,7 +191,8 @@ export const denseLoopsOf = (body) => {
|
|
|
168
191
|
cellWrites,
|
|
169
192
|
usesOf,
|
|
170
193
|
operationOf,
|
|
171
|
-
definedOutside
|
|
194
|
+
definedOutside,
|
|
195
|
+
invariantOperand
|
|
172
196
|
}));
|
|
173
197
|
const groupOfLoop = new Map();
|
|
174
198
|
for (const [index, loop] of found.entries()) {
|
|
@@ -293,7 +317,8 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
|
|
|
293
317
|
if (!left || !right)
|
|
294
318
|
return null;
|
|
295
319
|
const counter = context.readsCell.get(left.value);
|
|
296
|
-
|
|
320
|
+
const bound = counter === undefined ? null : context.invariantOperand(right, loop.blocks);
|
|
321
|
+
if (counter === undefined || bound === null)
|
|
297
322
|
return null;
|
|
298
323
|
// Exactly one advance, by an amount the preheader can name. Several
|
|
299
324
|
// advances, or a step the loop itself computes, and "the counter never
|
|
@@ -309,10 +334,11 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
|
|
|
309
334
|
// of `loops`.
|
|
310
335
|
if (loops.some((inner) => inner.header !== loop.header && inner.blocks.has(advance.block) && loop.blocks.has(inner.header)))
|
|
311
336
|
return null;
|
|
312
|
-
const
|
|
313
|
-
if (
|
|
337
|
+
const advanced = stepOf(advance.value, counter, context.operationOf, context.readsCell);
|
|
338
|
+
if (advanced === undefined)
|
|
314
339
|
return null;
|
|
315
|
-
|
|
340
|
+
const step = advanced === null ? null : context.invariantOperand(advanced, loop.blocks);
|
|
341
|
+
if (advanced !== null && step === null)
|
|
316
342
|
return null;
|
|
317
343
|
const candidates = windowsOfLoop(loop.blocks, body, { ...context, counter });
|
|
318
344
|
if (candidates.length === 0)
|
|
@@ -320,7 +346,7 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
|
|
|
320
346
|
return {
|
|
321
347
|
preheader,
|
|
322
348
|
counter,
|
|
323
|
-
bound
|
|
349
|
+
bound,
|
|
324
350
|
inclusive: test.operator === '<=',
|
|
325
351
|
step,
|
|
326
352
|
widened: advanceReachesAnAccess(loop, body, graph, advance.block, counter),
|
|
@@ -506,7 +532,11 @@ const windowsOfLoop = (blocks, body, context) => {
|
|
|
506
532
|
if (found.wrapped !== wrapped || found.modulus !== modulus)
|
|
507
533
|
found.sound = false;
|
|
508
534
|
else {
|
|
509
|
-
|
|
535
|
+
const same = (known) => known === null || base === null
|
|
536
|
+
? known === base
|
|
537
|
+
: known.terms.length === base.terms.length &&
|
|
538
|
+
known.terms.every((term, at) => term.operand.value === base.terms[at]?.operand.value && term.negated === base.terms[at]?.negated);
|
|
539
|
+
if (!found.bases.some(same))
|
|
510
540
|
found.bases.push(base);
|
|
511
541
|
found.operations.push(operation);
|
|
512
542
|
}
|
|
@@ -639,18 +669,33 @@ const indexBaseOf = (key, context, blocks) => {
|
|
|
639
669
|
return null;
|
|
640
670
|
const parallel = parallelCounterBaseOf(key, context, blocks);
|
|
641
671
|
if (parallel !== undefined)
|
|
642
|
-
return parallel;
|
|
643
|
-
const
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
const
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
672
|
+
return { terms: [{ operand: parallel, negated: false }] };
|
|
673
|
+
const terms = [];
|
|
674
|
+
// Exactly one positive counter leaf; every other leaf invariant. Depth is
|
|
675
|
+
// bounded by the expression the program wrote, a handful of terms.
|
|
676
|
+
const walk = (operand, negated, depth) => {
|
|
677
|
+
if (context.readsCell.get(operand.value) === context.counter)
|
|
678
|
+
return negated ? undefined : 1;
|
|
679
|
+
const invariant = context.invariantOperand(operand, blocks);
|
|
680
|
+
if (invariant !== null) {
|
|
681
|
+
terms.push({ operand: invariant, negated });
|
|
682
|
+
return 0;
|
|
683
|
+
}
|
|
684
|
+
const compute = context.operationOf.get(operand.value);
|
|
685
|
+
if (depth > 4 || compute?.kind !== 'compute' || compute.form !== 'binary')
|
|
686
|
+
return undefined;
|
|
687
|
+
if (compute.operator !== '+' && compute.operator !== '-')
|
|
688
|
+
return undefined;
|
|
689
|
+
const [left, right] = compute.operands;
|
|
690
|
+
if (!left || !right)
|
|
691
|
+
return undefined;
|
|
692
|
+
const counted = walk(left, negated, depth + 1);
|
|
693
|
+
if (counted === undefined)
|
|
694
|
+
return undefined;
|
|
695
|
+
const more = walk(right, compute.operator === '-' ? !negated : negated, depth + 1);
|
|
696
|
+
return more === undefined ? undefined : counted + more;
|
|
697
|
+
};
|
|
698
|
+
return walk(key, false, 0) === 1 ? { terms } : undefined;
|
|
654
699
|
};
|
|
655
700
|
/** Two counters advanced together by one differ by their initial offset.
|
|
656
701
|
* Requiring a zero primary seed and adjacent advances avoids synthesizing
|
package/dist/ir/facts.d.ts
CHANGED
|
@@ -3,39 +3,12 @@ import type { Representation } from '../representation/model.js';
|
|
|
3
3
|
import { type DeadValueRules } from './dead-values.js';
|
|
4
4
|
import type { ForwardedBinding, ForwardingPolicy } from './deferral.js';
|
|
5
5
|
import { type HoistPlan } from './hoist.js';
|
|
6
|
+
import { type Float32Narrowing } from './floats.js';
|
|
6
7
|
import { type IntegerStorageFacts } from './integers.js';
|
|
7
8
|
import { type CallOperation, type ComputeOperation, type GetOperation, type IrBody, type IrOperand, type IrOperation } from './model.js';
|
|
8
9
|
import { type NumericIntrinsic } from './numeric-intrinsics.js';
|
|
9
10
|
import { type SharedStringLayout } from './string-layout-reuse.js';
|
|
10
11
|
import { type TypeQueryComparison } from './type-query-results.js';
|
|
11
|
-
/**
|
|
12
|
-
* Every per-body census the printer needs before it renders a line, computed
|
|
13
|
-
* in one place, in the one order they depend on each other in.
|
|
14
|
-
*
|
|
15
|
-
* Distinct from `IrBody.facts` (`ir/captures.ts`), which is the whole-program
|
|
16
|
-
* capture answer sealed onto the body before rendering starts. These are the
|
|
17
|
-
* per-body questions, asked once per body at render entry; the two converge
|
|
18
|
-
* when the remaining Phase 3 rows land.
|
|
19
|
-
*
|
|
20
|
-
* These thirteen analyses used to run inline in `targets/cpp/emit.ts`, each
|
|
21
|
-
* copying its answer into the emit context. Nothing about them is C++: they ask
|
|
22
|
-
* what a body does -- which results nothing reads, which reads may be deferred
|
|
23
|
-
* to their single use, which numbers fit a `long long`, which loop-invariant
|
|
24
|
-
* reads may be hoisted -- and the printer only spells the answers. What made
|
|
25
|
-
* them live in the target was the ORDER, which is real and subtle and was
|
|
26
|
-
* recorded only as comments between the calls: the type-query census removes
|
|
27
|
-
* values from the deferral census, the hoists remove more, and the string
|
|
28
|
-
* length reuse removes more still, so reading the deferral set at the wrong
|
|
29
|
-
* point in the sequence silently answers a question with a set that is about
|
|
30
|
-
* to shrink. Here that order is the body of one function, stated once, and a
|
|
31
|
-
* reader who needs to know why a step sits where it does finds the reason at
|
|
32
|
-
* the step rather than in a comment beside a call site.
|
|
33
|
-
*
|
|
34
|
-
* The target still owns two decisions inside the sequence, because both are
|
|
35
|
-
* about C++ storage rather than about the program, and both are needed
|
|
36
|
-
* mid-order. They arrive as `IrBodyCensusPolicy` hooks, invoked exactly where
|
|
37
|
-
* the inline pipeline invoked them.
|
|
38
|
-
*/
|
|
39
12
|
export interface IrBodyCensus {
|
|
40
13
|
/** Protocol cursors that never escape their `get-iterator`, so the printer may hold them by value. */
|
|
41
14
|
readonly localIterators: ReadonlySet<IrValueId>;
|
|
@@ -54,6 +27,8 @@ export interface IrBodyCensus {
|
|
|
54
27
|
readonly typeQueryComparisons: ReadonlyMap<ComputeOperation, TypeQueryComparison>;
|
|
55
28
|
readonly integerValues: ReadonlySet<IrValueId>;
|
|
56
29
|
readonly integerBindings: ReadonlySet<DeclarationId>;
|
|
30
|
+
/** Values, cells and single-precision arithmetic held in `float` -- see `ir/floats.ts`. */
|
|
31
|
+
readonly float32: Float32Narrowing;
|
|
57
32
|
readonly remainderForms: ReadonlyMap<IrValueId, 'restated' | 'dynamic'>;
|
|
58
33
|
/** See `IntegerNarrowing.roundingArithmetic`. */
|
|
59
34
|
readonly roundingArithmetic: ReadonlySet<IrValueId>;
|
|
@@ -83,6 +58,8 @@ export interface IrBodyCensusPolicy {
|
|
|
83
58
|
readonly deadValues: DeadValueRules;
|
|
84
59
|
/** Whether this cell is a private local `string` whose `typeof` result may be saved rather than recomputed. */
|
|
85
60
|
readonly stringQueryCell: (declaration: DeclarationId) => boolean;
|
|
61
|
+
/** Whether a number cell's storage is this body's own to declare `float` -- see `ir/floats.ts`. */
|
|
62
|
+
readonly float32Cell: (declaration: DeclarationId) => boolean;
|
|
86
63
|
/** What a whole-program census already settled about this body's integer storage. */
|
|
87
64
|
readonly integerStorage: IntegerStorageFacts;
|
|
88
65
|
/**
|
|
@@ -110,7 +87,7 @@ export interface IrBodyCensusPolicy {
|
|
|
110
87
|
readonly formalStorage: (settled: IrBodyCensusBeforeHoists) => ReadonlySet<DeclarationId>;
|
|
111
88
|
}
|
|
112
89
|
/** What is known when `formalStorage` runs: everything except the hoists and the two censuses that read them. */
|
|
113
|
-
export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'remainderForms' | 'roundingArithmetic' | 'numericCalls' | 'numericCallOnly'>;
|
|
90
|
+
export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'float32' | 'remainderForms' | 'roundingArithmetic' | 'numericCalls' | 'numericCallOnly'>;
|
|
114
91
|
export declare const irBodyCensusOf: (body: IrBody, policy: IrBodyCensusPolicy) => IrBodyCensus;
|
|
115
92
|
/**
|
|
116
93
|
* Where every value in this body came from -- purely syntactic indices over
|
package/dist/ir/facts.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { booleanConstantsOf, deadValuesOf, unreadValuesOf } from './dead-values.js';
|
|
2
2
|
import { deferrableValuesOf } from './deferral.js';
|
|
3
3
|
import { loopInvariantHoistsOf, loopInvariantValuesOf } from './hoist.js';
|
|
4
|
+
import { narrowableFloatsOf } from './floats.js';
|
|
4
5
|
import { narrowableIntegersOf, remainderFormGroups } from './integers.js';
|
|
5
6
|
import { localIteratorValuesOf } from './local-iterators.js';
|
|
6
7
|
import { allOperationsOf } from './model.js';
|
|
@@ -9,6 +10,49 @@ import { operandsOfIrOperation, resultOfIrOperation } from './queries.js';
|
|
|
9
10
|
import { sharedStringLayoutsOf, straightLineStringLayoutsOf } from './string-layout-reuse.js';
|
|
10
11
|
import { stringLengthReuseOf } from './string-length-reuse.js';
|
|
11
12
|
import { typeQueryResultsOf } from './type-query-results.js';
|
|
13
|
+
/**
|
|
14
|
+
* Every per-body census the printer needs before it renders a line, computed
|
|
15
|
+
* in one place, in the one order they depend on each other in.
|
|
16
|
+
*
|
|
17
|
+
* Distinct from `IrBody.facts` (`ir/captures.ts`), which is the whole-program
|
|
18
|
+
* capture answer sealed onto the body before rendering starts. These are the
|
|
19
|
+
* per-body questions, asked once per body at render entry; the two converge
|
|
20
|
+
* when the remaining Phase 3 rows land.
|
|
21
|
+
*
|
|
22
|
+
* These thirteen analyses used to run inline in `targets/cpp/emit.ts`, each
|
|
23
|
+
* copying its answer into the emit context. Nothing about them is C++: they ask
|
|
24
|
+
* what a body does -- which results nothing reads, which reads may be deferred
|
|
25
|
+
* to their single use, which numbers fit a `long long`, which loop-invariant
|
|
26
|
+
* reads may be hoisted -- and the printer only spells the answers. What made
|
|
27
|
+
* them live in the target was the ORDER, which is real and subtle and was
|
|
28
|
+
* recorded only as comments between the calls: the type-query census removes
|
|
29
|
+
* values from the deferral census, the hoists remove more, and the string
|
|
30
|
+
* length reuse removes more still, so reading the deferral set at the wrong
|
|
31
|
+
* point in the sequence silently answers a question with a set that is about
|
|
32
|
+
* to shrink. Here that order is the body of one function, stated once, and a
|
|
33
|
+
* reader who needs to know why a step sits where it does finds the reason at
|
|
34
|
+
* the step rather than in a comment beside a call site.
|
|
35
|
+
*
|
|
36
|
+
* The target still owns two decisions inside the sequence, because both are
|
|
37
|
+
* about C++ storage rather than about the program, and both are needed
|
|
38
|
+
* mid-order. They arrive as `IrBodyCensusPolicy` hooks, invoked exactly where
|
|
39
|
+
* the inline pipeline invoked them.
|
|
40
|
+
*/
|
|
41
|
+
/**
|
|
42
|
+
* Narrowed integers a `float` holds exactly: magnitude at most 2^24, the
|
|
43
|
+
* float32 significand. `rounded[c] = lit + ROUND_MAGIC` adds one to a float32
|
|
44
|
+
* value and stores the sum into a Float32Array, which is single-precision
|
|
45
|
+
* arithmetic only if the integer counts as a float32 operand.
|
|
46
|
+
*/
|
|
47
|
+
const float32ExactIntegersOf = (narrowed) => {
|
|
48
|
+
const exact = new Set();
|
|
49
|
+
for (const value of narrowed.values) {
|
|
50
|
+
const magnitude = narrowed.magnitudes.get(value);
|
|
51
|
+
if (magnitude?.kind === 'bounded' && magnitude.limit <= 2 ** 24)
|
|
52
|
+
exact.add(value);
|
|
53
|
+
}
|
|
54
|
+
return exact;
|
|
55
|
+
};
|
|
12
56
|
export const irBodyCensusOf = (body, policy) => {
|
|
13
57
|
const localIterators = localIteratorValuesOf(body);
|
|
14
58
|
const censused = deferrableValuesOf(body, policy.deferrableMemberRead, policy.forwarding);
|
|
@@ -54,6 +98,7 @@ export const irBodyCensusOf = (body, policy) => {
|
|
|
54
98
|
typeQueryComparisons: typeQueries.comparisons,
|
|
55
99
|
integerValues: narrowed.values,
|
|
56
100
|
integerBindings: narrowed.bindings,
|
|
101
|
+
float32: narrowableFloatsOf(body, policy.float32Cell, narrowed.values, float32ExactIntegersOf(narrowed)),
|
|
57
102
|
remainderForms,
|
|
58
103
|
roundingArithmetic: narrowed.roundingArithmetic,
|
|
59
104
|
numericCalls: numericIntrinsics.calls,
|
|
@@ -61,7 +106,7 @@ export const irBodyCensusOf = (body, policy) => {
|
|
|
61
106
|
};
|
|
62
107
|
const stableFormals = policy.formalStorage(settled);
|
|
63
108
|
const loopInvariantValues = loopInvariantValuesOf(body);
|
|
64
|
-
const hoists = loopInvariantHoistsOf(body);
|
|
109
|
+
const hoists = loopInvariantHoistsOf(body, policy.integerStorage.cellConstants);
|
|
65
110
|
const hoistedStringLayouts = sharedStringLayoutsOf(body, hoists, dead);
|
|
66
111
|
const straightLineStringLayouts = straightLineStringLayoutsOf(body, stableFormals, new Set([...dead, ...hoists.relocated]), Math.max(-1, ...[...hoistedStringLayouts.values()].map((layout) => layout.ordinal)) + 1);
|
|
67
112
|
const sharedStringLayouts = new Map([...hoistedStringLayouts, ...straightLineStringLayouts]);
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { DeclarationId, IrValueId } from '../identity/ids.js';
|
|
2
|
+
import type { IrBody } from './model.js';
|
|
3
|
+
/**
|
|
4
|
+
* Which `number` values one body may hold in a C++ `float`, and which of its
|
|
5
|
+
* additions, subtractions, multiplications and divisions may be computed in
|
|
6
|
+
* one.
|
|
7
|
+
*
|
|
8
|
+
* A Number is a double, and every value here is still exactly that double: a
|
|
9
|
+
* value joins only when it is a float32 value by construction -- a
|
|
10
|
+
* `Math.fround` result, a `Float32Array` element, a negation of one, or a
|
|
11
|
+
* float32 constant -- so `float` storage holds it without loss and promoting
|
|
12
|
+
* it back to `double` wherever a double is needed is exact.
|
|
13
|
+
*
|
|
14
|
+
* Arithmetic is the one place the representation changes what is computed,
|
|
15
|
+
* and it is admitted on one condition: both operands are float32 values and
|
|
16
|
+
* EVERY use of the result rounds it to float32 straight away (a
|
|
17
|
+
* `Math.fround` argument or a `Float32Array` element store). For `+ - * /`
|
|
18
|
+
* on two float32 operands, rounding the exact double result to float32 gives
|
|
19
|
+
* the same value as the single-precision operation, because a double carries
|
|
20
|
+
* more than twice float32's significand plus two bits (Figueroa, "When is
|
|
21
|
+
* double rounding innocuous?", 1995). So `Math.fround(a * b)` computed as a
|
|
22
|
+
* `float` multiply is the value ECMA-262 asks for, and an unrounded `a * b`
|
|
23
|
+
* stays a double operation.
|
|
24
|
+
*
|
|
25
|
+
* The point is a core with a single-precision FPU and no double one (the
|
|
26
|
+
* ESP32-S31 is `rv32imafc`): there every double operation is a software
|
|
27
|
+
* routine, and a Gray-Scott step written the way such loops are written --
|
|
28
|
+
* every intermediate wrapped in `Math.fround` -- ran forty of them per cell.
|
|
29
|
+
*/
|
|
30
|
+
export interface Float32Narrowing {
|
|
31
|
+
/** SSA values whose C++ storage may be `float`. */
|
|
32
|
+
readonly values: ReadonlySet<IrValueId>;
|
|
33
|
+
/** Binding cells whose C++ storage may be `float`. Every read of one is in `values`. */
|
|
34
|
+
readonly bindings: ReadonlySet<DeclarationId>;
|
|
35
|
+
/** Binary compute results evaluated as single-precision arithmetic. */
|
|
36
|
+
readonly arithmetic: ReadonlySet<IrValueId>;
|
|
37
|
+
}
|
|
38
|
+
export declare const emptyFloat32Narrowing: Float32Narrowing;
|
|
39
|
+
/**
|
|
40
|
+
* @param admitsCell whether a cell's storage is this body's to choose -- a
|
|
41
|
+
* cell another frame shares, or one declared outside this body, keeps the
|
|
42
|
+
* double its carrier spells.
|
|
43
|
+
* @param excluded values another census already gave a storage of its own
|
|
44
|
+
* (the integer census's `long long`s).
|
|
45
|
+
*/
|
|
46
|
+
export declare const narrowableFloatsOf: (body: IrBody, admitsCell: (declaration: DeclarationId) => boolean, excluded: ReadonlySet<IrValueId>, exactIntegers?: ReadonlySet<IrValueId>) => Float32Narrowing;
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { allOperationsOf } from './model.js';
|
|
2
|
+
import { operandsOfIrOperation } from './queries.js';
|
|
3
|
+
export const emptyFloat32Narrowing = { values: new Set(), bindings: new Set(), arithmetic: new Set() };
|
|
4
|
+
const roundedOperators = new Set(['+', '-', '*', '/']);
|
|
5
|
+
const isNumberScalar = (operand) => operand.representation.kind === 'scalar' && operand.representation.domain === 'number';
|
|
6
|
+
/** A number literal that is its own float32 rounding: storing it in a `float` loses nothing. */
|
|
7
|
+
const isFloat32Literal = (text) => {
|
|
8
|
+
const value = Number(text);
|
|
9
|
+
return Number.isFinite(value) && Math.fround(value) === value;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* @param admitsCell whether a cell's storage is this body's to choose -- a
|
|
13
|
+
* cell another frame shares, or one declared outside this body, keeps the
|
|
14
|
+
* double its carrier spells.
|
|
15
|
+
* @param excluded values another census already gave a storage of its own
|
|
16
|
+
* (the integer census's `long long`s).
|
|
17
|
+
*/
|
|
18
|
+
export const narrowableFloatsOf = (body, admitsCell, excluded, exactIntegers = new Set()) => {
|
|
19
|
+
const stringKeys = new Map();
|
|
20
|
+
const float32Constants = new Set();
|
|
21
|
+
for (const block of body.blocks.values()) {
|
|
22
|
+
for (const operation of block.operations) {
|
|
23
|
+
if (operation.kind !== 'constant')
|
|
24
|
+
continue;
|
|
25
|
+
if (operation.literal === 'string')
|
|
26
|
+
stringKeys.set(operation.result.id, operation.text);
|
|
27
|
+
else if (operation.literal === 'number' && isFloat32Literal(operation.text))
|
|
28
|
+
float32Constants.add(operation.result.id);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
// `Math.fround` authenticated by its native protocol, as `numericIntrinsicsOf`
|
|
32
|
+
// authenticates `Math.imul`: a user object named Math has no such protocol.
|
|
33
|
+
const froundCallees = new Set();
|
|
34
|
+
for (const block of body.blocks.values()) {
|
|
35
|
+
for (const operation of block.operations) {
|
|
36
|
+
if (operation.kind !== 'get')
|
|
37
|
+
continue;
|
|
38
|
+
const receiver = operation.receiver.representation;
|
|
39
|
+
if (receiver.kind === 'native-handle' &&
|
|
40
|
+
receiver.native === null &&
|
|
41
|
+
receiver.protocol === 'Math' &&
|
|
42
|
+
stringKeys.get(operation.key.value) === 'fround')
|
|
43
|
+
froundCallees.add(operation.result.id);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const isFroundCall = (operation) => froundCallees.has(operation.callee.value) &&
|
|
47
|
+
operation.arguments.length === 1 &&
|
|
48
|
+
operation.arguments.every(isNumberScalar) &&
|
|
49
|
+
operation.result !== null &&
|
|
50
|
+
isNumberScalar(operation.result);
|
|
51
|
+
const definitions = new Map();
|
|
52
|
+
const cellWrites = new Map();
|
|
53
|
+
/** Values every use of which rounds to float32; struck by any other use. */
|
|
54
|
+
const roundedUses = new Map();
|
|
55
|
+
const use = (value, rounds) => {
|
|
56
|
+
roundedUses.set(value, (roundedUses.get(value) ?? true) && rounds);
|
|
57
|
+
};
|
|
58
|
+
for (const block of body.blocks.values()) {
|
|
59
|
+
for (const operation of allOperationsOf(block)) {
|
|
60
|
+
if (operation.kind === 'call' && isFroundCall(operation)) {
|
|
61
|
+
definitions.set(operation.result.id, { kind: 'source' });
|
|
62
|
+
use(operation.arguments[0].value, true);
|
|
63
|
+
use(operation.callee.value, false);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (operation.kind === 'set' && operation.receiver.representation.kind === 'typed-array') {
|
|
67
|
+
const keyText = stringKeys.get(operation.key.value);
|
|
68
|
+
const elementStore = operation.receiver.representation.element === 'float32' && keyText === undefined && isNumberScalar(operation.value);
|
|
69
|
+
use(operation.value.value, elementStore);
|
|
70
|
+
use(operation.receiver.value, false);
|
|
71
|
+
use(operation.key.value, false);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (operation.kind === 'get' && operation.receiver.representation.kind === 'typed-array') {
|
|
75
|
+
const keyText = stringKeys.get(operation.key.value);
|
|
76
|
+
if (operation.receiver.representation.element === 'float32' && keyText === undefined && isNumberScalar(operation.result))
|
|
77
|
+
definitions.set(operation.result.id, { kind: 'source' });
|
|
78
|
+
}
|
|
79
|
+
else if (operation.kind === 'compute' && isNumberScalar(operation.result)) {
|
|
80
|
+
const operands = operation.operands;
|
|
81
|
+
if (operation.form === 'unary' && operation.operator === '-' && operands.length === 1 && isNumberScalar(operands[0]))
|
|
82
|
+
definitions.set(operation.result.id, { kind: 'negate', operand: operands[0].value });
|
|
83
|
+
else if (operation.form === 'binary' &&
|
|
84
|
+
roundedOperators.has(operation.operator) &&
|
|
85
|
+
operands.length === 2 &&
|
|
86
|
+
operands.every(isNumberScalar))
|
|
87
|
+
definitions.set(operation.result.id, { kind: 'arithmetic', operands: operands.map((operand) => operand.value) });
|
|
88
|
+
}
|
|
89
|
+
else if (operation.kind === 'phi' && isNumberScalar(operation.result)) {
|
|
90
|
+
definitions.set(operation.result.id, { kind: 'phi', incoming: operation.incoming.map((incoming) => incoming.value.value) });
|
|
91
|
+
}
|
|
92
|
+
else if (operation.kind === 'binding-read' && isNumberScalar(operation.result)) {
|
|
93
|
+
definitions.set(operation.result.id, { kind: 'cell', declaration: operation.declaration });
|
|
94
|
+
}
|
|
95
|
+
else if (operation.kind === 'binding-write') {
|
|
96
|
+
const writes = cellWrites.get(operation.declaration) ?? [];
|
|
97
|
+
writes.push(operation.value.value);
|
|
98
|
+
cellWrites.set(operation.declaration, writes);
|
|
99
|
+
// A cell write is not a rounding: the cell is read back as a Number.
|
|
100
|
+
use(operation.value.value, false);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
for (const operand of operandsOfIrOperation(operation))
|
|
104
|
+
use(operand.value, false);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
// Optimistic: every candidate is a float32 value until a premise fails, so a
|
|
108
|
+
// loop-carried phi or a cell written from itself can settle at all.
|
|
109
|
+
const values = new Set([...definitions.keys()].filter((value) => !excluded.has(value)));
|
|
110
|
+
const arithmetic = new Set();
|
|
111
|
+
const cells = new Set();
|
|
112
|
+
for (const [declaration, writes] of cellWrites)
|
|
113
|
+
if (admitsCell(declaration) && writes.length > 0)
|
|
114
|
+
cells.add(declaration);
|
|
115
|
+
const exact = (value) => values.has(value) || float32Constants.has(value) || exactIntegers.has(value);
|
|
116
|
+
const strike = () => {
|
|
117
|
+
let struck = false;
|
|
118
|
+
let changed = true;
|
|
119
|
+
while (changed) {
|
|
120
|
+
changed = false;
|
|
121
|
+
for (const declaration of [...cells]) {
|
|
122
|
+
if ((cellWrites.get(declaration) ?? []).every(exact))
|
|
123
|
+
continue;
|
|
124
|
+
cells.delete(declaration);
|
|
125
|
+
changed = struck = true;
|
|
126
|
+
}
|
|
127
|
+
for (const value of [...values]) {
|
|
128
|
+
const definition = definitions.get(value);
|
|
129
|
+
const holds = definition.kind === 'source'
|
|
130
|
+
? true
|
|
131
|
+
: definition.kind === 'negate'
|
|
132
|
+
? exact(definition.operand)
|
|
133
|
+
: definition.kind === 'arithmetic'
|
|
134
|
+
? definition.operands.every(exact) && roundedUses.get(value) === true
|
|
135
|
+
: definition.kind === 'phi'
|
|
136
|
+
? definition.incoming.every(exact)
|
|
137
|
+
: cells.has(definition.declaration);
|
|
138
|
+
if (holds)
|
|
139
|
+
continue;
|
|
140
|
+
values.delete(value);
|
|
141
|
+
changed = struck = true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return struck;
|
|
145
|
+
};
|
|
146
|
+
// Exact is not enough: a `let x = 0` written only with float32 constants is
|
|
147
|
+
// exact too, and moving every such counter into a `float` would change the
|
|
148
|
+
// storage of programs that never touch single precision. A value keeps
|
|
149
|
+
// `float` storage only when a float32 source reaches it -- the least
|
|
150
|
+
// fixpoint from `fround` results and `Float32Array` reads.
|
|
151
|
+
const ground = () => {
|
|
152
|
+
const grounded = new Set();
|
|
153
|
+
const groundedCells = new Set();
|
|
154
|
+
let changed = true;
|
|
155
|
+
while (changed) {
|
|
156
|
+
changed = false;
|
|
157
|
+
for (const value of values) {
|
|
158
|
+
if (grounded.has(value))
|
|
159
|
+
continue;
|
|
160
|
+
const definition = definitions.get(value);
|
|
161
|
+
const reached = definition.kind === 'source' || definition.kind === 'arithmetic'
|
|
162
|
+
? true
|
|
163
|
+
: definition.kind === 'negate'
|
|
164
|
+
? grounded.has(definition.operand)
|
|
165
|
+
: definition.kind === 'phi'
|
|
166
|
+
? definition.incoming.some((incoming) => grounded.has(incoming))
|
|
167
|
+
: groundedCells.has(definition.declaration);
|
|
168
|
+
if (!reached)
|
|
169
|
+
continue;
|
|
170
|
+
grounded.add(value);
|
|
171
|
+
changed = true;
|
|
172
|
+
}
|
|
173
|
+
for (const declaration of cells) {
|
|
174
|
+
if (groundedCells.has(declaration) || !(cellWrites.get(declaration) ?? []).some((write) => grounded.has(write)))
|
|
175
|
+
continue;
|
|
176
|
+
groundedCells.add(declaration);
|
|
177
|
+
changed = true;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
let removed = false;
|
|
181
|
+
for (const value of [...values])
|
|
182
|
+
if (!grounded.has(value))
|
|
183
|
+
(values.delete(value), (removed = true));
|
|
184
|
+
for (const declaration of [...cells])
|
|
185
|
+
if (!groundedCells.has(declaration))
|
|
186
|
+
(cells.delete(declaration), (removed = true));
|
|
187
|
+
return removed;
|
|
188
|
+
};
|
|
189
|
+
strike();
|
|
190
|
+
while (ground() && strike())
|
|
191
|
+
;
|
|
192
|
+
for (const value of values)
|
|
193
|
+
if (definitions.get(value)?.kind === 'arithmetic')
|
|
194
|
+
arithmetic.add(value);
|
|
195
|
+
return { values, bindings: cells, arithmetic };
|
|
196
|
+
};
|