@geastack/compiler 1.0.40 → 1.0.42

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.
@@ -35,6 +35,8 @@ export interface IrBodyCensus {
35
35
  readonly roundingArithmetic: ReadonlySet<IrValueId>;
36
36
  /** See `IntegerNarrowing.integerDivisions`. */
37
37
  readonly integerDivisions: ReadonlySet<IrValueId>;
38
+ /** See `IntegerNarrowing.nonZeroDivisors`. */
39
+ readonly nonZeroDivisors: ReadonlySet<IrValueId>;
38
40
  /** See `IntegerNarrowing.declaredWidths`. */
39
41
  readonly declaredWidths: ReadonlyMap<IrValueId, DeclaredIntegerWidth>;
40
42
  readonly exactNumericConversions: ReadonlySet<IrValueId>;
@@ -97,7 +99,7 @@ export interface IrBodyCensusPolicy {
97
99
  readonly copiedCapture: (declaration: DeclarationId) => boolean;
98
100
  }
99
101
  /** What is known when `formalStorage` runs: everything except the hoists and the two censuses that read them. */
100
- export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'float32' | 'remainderForms' | 'roundingArithmetic' | 'integerDivisions' | 'declaredWidths' | 'exactNumericConversions' | 'declaredIntegerCells' | 'numericCalls' | 'numericCallOnly'>;
102
+ export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'float32' | 'remainderForms' | 'roundingArithmetic' | 'integerDivisions' | 'nonZeroDivisors' | 'declaredWidths' | 'exactNumericConversions' | 'declaredIntegerCells' | 'numericCalls' | 'numericCallOnly'>;
101
103
  export declare const irBodyCensusOf: (body: IrBody, policy: IrBodyCensusPolicy) => IrBodyCensus;
102
104
  /**
103
105
  * Where every value in this body came from -- purely syntactic indices over
package/dist/ir/facts.js CHANGED
@@ -107,6 +107,7 @@ export const irBodyCensusOf = (body, policy) => {
107
107
  remainderForms,
108
108
  roundingArithmetic: narrowed.roundingArithmetic,
109
109
  integerDivisions: narrowed.integerDivisions,
110
+ nonZeroDivisors: narrowed.nonZeroDivisors,
110
111
  declaredWidths: narrowed.declaredWidths,
111
112
  exactNumericConversions: narrowed.exactNumericConversions,
112
113
  declaredIntegerCells: narrowed.declaredBindings,
@@ -102,6 +102,12 @@ export interface IntegerNarrowing {
102
102
  * it anyway, and a `%` whose divisor is not a known non-zero constant.
103
103
  */
104
104
  readonly integerDivisions: ReadonlySet<IrValueId>;
105
+ /**
106
+ * The `%` among `integerDivisions` whose divisor the body proves odd
107
+ * (`oddValuesOf`), and so never zero: their helper keeps only the
108
+ * `MIN % -1` test, which -1, being odd, still needs.
109
+ */
110
+ readonly nonZeroDivisors: ReadonlySet<IrValueId>;
105
111
  /**
106
112
  * The narrowed values an `int`/`i32` annotation put there, each with its
107
113
  * machine width. Their `+ - *`, negation and updates WRAP at that width --
@@ -10,6 +10,7 @@ export const emptyIntegerNarrowing = {
10
10
  dynamicRemainders: new Set(),
11
11
  roundingArithmetic: new Set(),
12
12
  integerDivisions: new Set(),
13
+ nonZeroDivisors: new Set(),
13
14
  declaredWidths: new Map(),
14
15
  exactNumericConversions: new Set(),
15
16
  declaredBindings: new Map()
@@ -777,6 +778,14 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
777
778
  }
778
779
  };
779
780
  const declared = declaredIntegerValuesOf(body, declaredCells, readsCell, computes, phis, numericConversions, valueRepresentations, integral, constants, isNumberScalarValue);
781
+ const odd = oddValuesOf(body, graph, readsCell, computes, phis, numericConversions, constants);
782
+ const nonZeroDivisors = new Set();
783
+ for (const value of declared.divisions) {
784
+ const compute = computes.get(value);
785
+ const divisor = compute?.form === 'binary' && compute.operator === '%' ? compute.operands[1] : undefined;
786
+ if (divisor !== undefined && odd.has(divisor.value))
787
+ nonZeroDivisors.add(value);
788
+ }
780
789
  const values = new Set(declared.values);
781
790
  const bindings = new Set();
782
791
  const declaredBindings = new Map();
@@ -866,6 +875,7 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
866
875
  dynamicRemainders,
867
876
  roundingArithmetic,
868
877
  integerDivisions: declared.divisions,
878
+ nonZeroDivisors,
869
879
  declaredWidths: declared.widths,
870
880
  exactNumericConversions,
871
881
  declaredBindings
@@ -1268,3 +1278,126 @@ const cellReadRefinementsOf = (body, graph, readsCell, computes, constants, type
1268
1278
  }
1269
1279
  return refinements;
1270
1280
  };
1281
+ /**
1282
+ * The values a body proves odd, and so never zero.
1283
+ *
1284
+ * A trial-division loop's divisor (`for (let d: int = 3; d * d <= n; d += 2)
1285
+ * if (n % d === 0) ...`) starts odd and steps by an even constant, so it is
1286
+ * odd at every read. Without that proof its `%` keeps the guarded helper's
1287
+ * zero test, and clang lays the loop out around that branch: primes ran 8%
1288
+ * behind the same loop written in C++ and Rust on the Haswell benchmark
1289
+ * machine. Parity survives wrapping, so `int` and `i32` arithmetic keeps it.
1290
+ *
1291
+ * A value is odd when it is an odd constant, a numeric conversion of an odd
1292
+ * value, odd plus or minus an even constant, a product of two odd values, a
1293
+ * phi of odd values, or a read of a cell that holds an odd value on every path
1294
+ * to it. The cells take the forward dataflow `cellReadRefinementsOf` uses, met
1295
+ * by intersection: only a cell this body alone writes takes part, and the
1296
+ * entry, which a parameter's or an unwritten cell's value reaches, holds none.
1297
+ */
1298
+ const oddValuesOf = (body, graph, readsCell, computes, phis, numericConversions, constants) => {
1299
+ const facts = body.facts;
1300
+ const oddReads = new Set();
1301
+ if (facts === undefined)
1302
+ return oddReads;
1303
+ const captured = new Set(facts.capturedDeclarations);
1304
+ const eligible = (cell) => !facts.boxed.has(cell) && !captured.has(cell);
1305
+ const evenConstant = (value) => {
1306
+ const constant = constants.get(value);
1307
+ return constant !== undefined && constant % 2 === 0;
1308
+ };
1309
+ const odd = (value, seen = new Set()) => {
1310
+ if (seen.has(value))
1311
+ return false;
1312
+ seen.add(value);
1313
+ const constant = constants.get(value);
1314
+ if (constant !== undefined)
1315
+ return Math.abs(constant % 2) === 1;
1316
+ if (readsCell.has(value))
1317
+ return oddReads.has(value);
1318
+ const converted = numericConversions.get(value);
1319
+ if (converted !== undefined)
1320
+ return odd(converted.value, seen);
1321
+ const incoming = phis.get(value);
1322
+ if (incoming !== undefined)
1323
+ return incoming.length > 0 && incoming.every((operand) => odd(operand.value, new Set(seen)));
1324
+ const compute = computes.get(value);
1325
+ if (compute?.form !== 'binary')
1326
+ return false;
1327
+ const [left, right] = compute.operands;
1328
+ if (!left || !right)
1329
+ return false;
1330
+ if (compute.operator === '+' || compute.operator === '-')
1331
+ return (odd(left.value, new Set(seen)) && evenConstant(right.value)) || (evenConstant(left.value) && odd(right.value, new Set(seen)));
1332
+ if (compute.operator === '*')
1333
+ return odd(left.value, new Set(seen)) && odd(right.value, new Set(seen));
1334
+ return false;
1335
+ };
1336
+ const transfer = (blockId, entry) => {
1337
+ const state = new Set(entry);
1338
+ for (const operation of body.blocks.get(blockId)?.operations ?? []) {
1339
+ if (operation.kind === 'binding-read') {
1340
+ if (state.has(operation.declaration))
1341
+ oddReads.add(operation.result.id);
1342
+ else
1343
+ oddReads.delete(operation.result.id);
1344
+ continue;
1345
+ }
1346
+ if (operation.kind === 'binding-write') {
1347
+ if (eligible(operation.declaration) && odd(operation.value.value))
1348
+ state.add(operation.declaration);
1349
+ else
1350
+ state.delete(operation.declaration);
1351
+ continue;
1352
+ }
1353
+ if ('declaration' in operation && typeof operation.declaration === 'string')
1354
+ state.delete(operation.declaration);
1355
+ }
1356
+ return state;
1357
+ };
1358
+ const meet = (states) => {
1359
+ const [first, ...rest] = states;
1360
+ if (first === undefined)
1361
+ return new Set();
1362
+ return new Set([...first].filter((cell) => rest.every((other) => other.has(cell))));
1363
+ };
1364
+ // Optimistic, as in `cellReadRefinementsOf`: an unvisited predecessor adds
1365
+ // nothing to the meet, facts only shrink, and the entry starts empty.
1366
+ const exits = new Map();
1367
+ const entryOf = (blockId) => {
1368
+ const predecessors = graph.predecessors.get(blockId) ?? [];
1369
+ if (blockId === body.entry || predecessors.length === 0)
1370
+ return new Set();
1371
+ const visited = predecessors.map((predecessor) => exits.get(predecessor)).filter((state) => state !== undefined);
1372
+ return visited.length === 0 ? null : meet(visited);
1373
+ };
1374
+ const sameState = (left, right) => left !== undefined && left.size === right.size && [...right].every((cell) => left.has(cell));
1375
+ for (let changed = true, rounds = 0; changed; rounds++) {
1376
+ // An unsettled optimistic state is not a sound one.
1377
+ if (rounds === 64)
1378
+ return new Set();
1379
+ changed = false;
1380
+ for (const blockId of body.blockOrder) {
1381
+ const entry = entryOf(blockId);
1382
+ if (entry === null)
1383
+ continue;
1384
+ const exit = transfer(blockId, entry);
1385
+ if (sameState(exits.get(blockId), exit))
1386
+ continue;
1387
+ exits.set(blockId, exit);
1388
+ changed = true;
1389
+ }
1390
+ }
1391
+ // The settled states, applied once more, leave exactly the reads they prove.
1392
+ oddReads.clear();
1393
+ for (const blockId of body.blockOrder) {
1394
+ const entry = entryOf(blockId);
1395
+ if (entry !== null)
1396
+ transfer(blockId, entry);
1397
+ }
1398
+ const proved = new Set(oddReads);
1399
+ for (const value of [...computes.keys(), ...phis.keys(), ...numericConversions.keys()])
1400
+ if (odd(value))
1401
+ proved.add(value);
1402
+ return proved;
1403
+ };
@@ -431,7 +431,11 @@ const isCallableNode = (node) => ts.isFunctionExpression(node) ||
431
431
  ts.isSetAccessorDeclaration(node);
432
432
  /** A declaration instantiated with the enclosing function body, before that body's statements execute. */
433
433
  const isBodyLevelFunctionDeclaration = (node) => {
434
- if (!ts.isFunctionDeclaration(node) || !ts.isBlock(node.parent))
434
+ if (!ts.isFunctionDeclaration(node))
435
+ return false;
436
+ if (ts.isSourceFile(node.parent))
437
+ return true;
438
+ if (!ts.isBlock(node.parent))
435
439
  return false;
436
440
  const owner = node.parent.parent;
437
441
  return ((ts.isFunctionDeclaration(owner) ||
@@ -432,7 +432,10 @@ export const createPackageSourceHost = (host = ts.sys, packages = []) => {
432
432
  if (candidates.length === 1 && candidates[0])
433
433
  return candidates[0];
434
434
  }
435
- return host.fileExists(absolute) ? absolute : resolve(file);
435
+ // A host that names files only by its own spelling (a virtual host, on
436
+ // Windows where `resolve` turns `/src/a.js` into `C:\src\a.js`) is asked
437
+ // again with the path it gave.
438
+ return host.fileExists(absolute) ? absolute : file;
436
439
  };
437
440
  const view = {
438
441
  ...host,
@@ -442,7 +445,7 @@ export const createPackageSourceHost = (host = ts.sys, packages = []) => {
442
445
  if (aliases.some((entry) => inside(entry.prefix, resolve(directory))))
443
446
  return true;
444
447
  const dir = unalias(directory);
445
- if (host.directoryExists?.(dir))
448
+ if (host.directoryExists?.(dir) || (dir === resolve(directory) && host.directoryExists?.(directory)))
446
449
  return true;
447
450
  const root = packageOf(`${dir}/__module__.ts`);
448
451
  const record = root ? readRecord(root) : undefined;
@@ -1699,6 +1699,8 @@ export interface EmitContext {
1699
1699
  readonly roundingArithmetic: ReadonlySet<IrValueId>;
1700
1700
  /** See `IntegerNarrowing.integerDivisions`. */
1701
1701
  readonly integerDivisions: ReadonlySet<IrValueId>;
1702
+ /** See `IntegerNarrowing.nonZeroDivisors`. */
1703
+ readonly nonZeroDivisors: ReadonlySet<IrValueId>;
1702
1704
  /** See `IntegerNarrowing.declaredWidths`. */
1703
1705
  readonly declaredWidths: ReadonlyMap<IrValueId, DeclaredIntegerWidth>;
1704
1706
  /** See `IntegerNarrowing.exactNumericConversions`; settled before rendering. */
@@ -1941,6 +1943,7 @@ export interface EmitBodyPrepassFacts {
1941
1943
  readonly remainderForms: Map<IrValueId, 'restated' | 'dynamic'>;
1942
1944
  readonly roundingArithmetic: Set<IrValueId>;
1943
1945
  readonly integerDivisions: Set<IrValueId>;
1946
+ readonly nonZeroDivisors: Set<IrValueId>;
1944
1947
  readonly declaredWidths: Map<IrValueId, DeclaredIntegerWidth>;
1945
1948
  readonly exactNumericConversions: Set<IrValueId>;
1946
1949
  readonly declaredIntegerCells: Map<DeclarationId, DeclaredIntegerWidth>;
@@ -129,6 +129,7 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
129
129
  const remainderForms = new Map();
130
130
  const roundingArithmetic = new Set();
131
131
  const integerDivisions = new Set();
132
+ const nonZeroDivisors = new Set();
132
133
  const declaredWidths = new Map();
133
134
  const exactNumericConversions = new Set();
134
135
  const declaredIntegerCells = new Map();
@@ -290,6 +291,7 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
290
291
  remainderForms,
291
292
  roundingArithmetic,
292
293
  integerDivisions,
294
+ nonZeroDivisors,
293
295
  declaredWidths,
294
296
  exactNumericConversions,
295
297
  declaredIntegerCells,
@@ -336,6 +338,7 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
336
338
  remainderForms,
337
339
  roundingArithmetic,
338
340
  integerDivisions,
341
+ nonZeroDivisors,
339
342
  declaredWidths,
340
343
  exactNumericConversions,
341
344
  declaredIntegerCells,
@@ -904,7 +904,11 @@ const emitCompute = (ctx, lines, operation) => {
904
904
  // it anyway (`IntegerNarrowing.integerDivisions`): there the integer division
905
905
  // IS the answer, without a round trip through a double.
906
906
  if (ctx.integerDivisions.has(operation.result.id) && (operation.operator === '/' || operation.operator === '%')) {
907
- const helper = operation.operator === '/' ? 'gea::integerQuotient' : 'gea::integerModulo';
907
+ const helper = operation.operator === '/'
908
+ ? 'gea::integerQuotient'
909
+ : ctx.nonZeroDivisors.has(operation.result.id)
910
+ ? 'gea::integerModuloNonZero'
911
+ : 'gea::integerModulo';
908
912
  lines.push(`${name} = ${helper}(${operandText(ctx, first)}, ${operandText(ctx, second)});`);
909
913
  return;
910
914
  }
@@ -2929,6 +2933,8 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
2929
2933
  prepass.roundingArithmetic.add(value);
2930
2934
  for (const value of settled.integerDivisions)
2931
2935
  prepass.integerDivisions.add(value);
2936
+ for (const value of settled.nonZeroDivisors)
2937
+ prepass.nonZeroDivisors.add(value);
2932
2938
  for (const [value, width] of settled.declaredWidths)
2933
2939
  prepass.declaredWidths.set(value, width);
2934
2940
  for (const value of settled.exactNumericConversions)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.40",
3
+ "version": "1.0.42",
4
4
  "description": "The geastack TypeScript-to-C++ compiler: one semantic spine, no source-shaped authority, no boxing of statically typed values.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -6112,6 +6112,20 @@ template <typename Left, typename Right>
6112
6112
  return divisor == 0 ? Common{0} : static_cast<Common>(std::fmod(static_cast<Common>(dividend), static_cast<Common>(divisor)));
6113
6113
  }
6114
6114
  }
6115
+ /**
6116
+ * `integerModulo` for a divisor the compiler proved odd (`oddValuesOf`), so
6117
+ * never zero. The zero test is the one that costs: clang lays a trial-division
6118
+ * loop out around it, 8% slower on Haswell, where the `MIN % -1` test hoists
6119
+ * out as the dividend's and costs nothing -- and -1 is odd, so it stays.
6120
+ */
6121
+ template <typename Left, typename Right>
6122
+ [[gnu::always_inline]] inline auto integerModuloNonZero(Left dividend, Right divisor) {
6123
+ using Common = std::common_type_t<Left, Right>;
6124
+ static_assert(std::is_integral_v<Common>, "a proved-odd divisor is an integer");
6125
+ if constexpr (std::is_signed_v<Common>)
6126
+ if (static_cast<Common>(dividend) == std::numeric_limits<Common>::min() && divisor == -1) [[unlikely]] return Common{0};
6127
+ return static_cast<Common>(static_cast<Common>(dividend) % static_cast<Common>(divisor));
6128
+ }
6115
6129
  /**
6116
6130
  * `+ - *` over an `int`/`i32` binding's values, at the annotation's width.
6117
6131
  * They wrap, as an `int32_t` lane of a typed array does: computed in the