-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathConstantPropagation.ts
More file actions
702 lines (671 loc) · 21.6 KB
/
ConstantPropagation.ts
File metadata and controls
702 lines (671 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {isValidIdentifier} from '@babel/types';
import {CompilerError} from '../CompilerError';
import {
GeneratedSource,
GotoVariant,
HIRFunction,
IdentifierId,
Instruction,
InstructionValue,
LoadGlobal,
Phi,
Place,
Primitive,
assertConsistentIdentifiers,
assertTerminalSuccessorsExist,
makePropertyLiteral,
markInstructionIds,
markPredecessors,
mergeConsecutiveBlocks,
reversePostorderBlocks,
} from '../HIR';
import {
removeDeadDoWhileStatements,
removeUnnecessaryTryCatch,
removeUnreachableForUpdates,
} from '../HIR/HIRBuilder';
import {eliminateRedundantPhi} from '../SSA';
/*
* Applies constant propagation/folding to the given function. The approach is
* [Sparse Conditional Constant Propagation](https://en.wikipedia.org/wiki/Sparse_conditional_constant_propagation):
* we use abstract interpretation to record known constant values for identifiers,
* with lack of a value indicating that the identifier does not have a
* known constant value.
*
* Instructions which can be compile-time evaluated *and* whose operands are known constants
* are replaced with the resulting constant value. For example a BinaryExpression
* where the left value is known to be `1` and the right value is known to be `2`
* can be replaced with a `Constant 3` instruction.
*
* This pass also exploits the use of SSA form, tracking the constant values of
* local variables. For example, in `let x = 4; let y = x + 1` we know that
* `x = 4` in the binary expression and can replace the binary expression with
* `Constant 5`.
*
* This pass also visits conditionals (currently only IfTerminal) and can prune
* unreachable branches when the condition is a known truthy/falsey constant. The
* pass uses fixpoint iteration, looping until no additional updates can be
* performed. This allows the compiler to find cases where once one conditional is pruned,
* other values become constant, allowing subsequent conditionals to be pruned and so on.
*/
export function constantPropagation(fn: HIRFunction): void {
const constants: Constants = new Map();
const jsxSimpleTagPlaces = collectJsxSimpleTagPlaces(fn);
constantPropagationImpl(fn, constants, jsxSimpleTagPlaces);
}
/*
* Collect the `IdentifierId` of every Place that is used as a JSX element's
* tag (i.e. simple `<X />`, not `<x.Y />` / `<x:y />`). These places may not
* be rewritten through a LoadGlobal whose binding name has different JSX
* component-vs-intrinsic casing, because doing so changes runtime semantics
* (JSX treats lowercase tags as string intrinsics and uppercase ones as
* component references).
*/
function collectJsxSimpleTagPlaces(fn: HIRFunction): Set<IdentifierId> {
const set = new Set<IdentifierId>();
const visit = (f: HIRFunction): void => {
for (const [, block] of f.body.blocks) {
for (const instr of block.instructions) {
const v = instr.value;
if (v.kind === 'JsxExpression' && v.tag.kind === 'Identifier') {
set.add(v.tag.identifier.id);
}
if (v.kind === 'FunctionExpression' || v.kind === 'ObjectMethod') {
visit(v.loweredFunc.func);
}
}
}
};
visit(fn);
return set;
}
/*
* Heuristic: identifiers whose first alphabetic character is uppercase are
* conventionally React components in JSX, while lowercase ones are intrinsic
* (HTML) element tags.
*/
function isLikelyComponentName(name: string): boolean {
const first = name.match(/[A-Za-z]/);
return first !== null && first[0] === first[0].toUpperCase();
}
function constantPropagationImpl(
fn: HIRFunction,
constants: Constants,
jsxSimpleTagPlaces: Set<IdentifierId> = new Set(),
): void {
while (true) {
const haveTerminalsChanged = applyConstantPropagation(
fn,
constants,
jsxSimpleTagPlaces,
);
if (!haveTerminalsChanged) {
break;
}
/*
* If terminals have changed then blocks may have become newly unreachable.
* Re-run minification of the graph (incl reordering instruction ids)
*/
reversePostorderBlocks(fn.body);
removeUnreachableForUpdates(fn.body);
removeDeadDoWhileStatements(fn.body);
removeUnnecessaryTryCatch(fn.body);
markInstructionIds(fn.body);
markPredecessors(fn.body);
// Now that predecessors are updated, prune phi operands that can never be reached
for (const [, block] of fn.body.blocks) {
for (const phi of block.phis) {
for (const [predecessor] of phi.operands) {
if (!block.preds.has(predecessor)) {
phi.operands.delete(predecessor);
}
}
}
}
/*
* By removing some phi operands, there may be phis that were not previously
* redundant but now are
*/
eliminateRedundantPhi(fn);
/*
* Finally, merge together any blocks that are now guaranteed to execute
* consecutively
*/
mergeConsecutiveBlocks(fn);
assertConsistentIdentifiers(fn);
assertTerminalSuccessorsExist(fn);
}
}
function applyConstantPropagation(
fn: HIRFunction,
constants: Constants,
jsxSimpleTagPlaces: Set<IdentifierId>,
): boolean {
let hasChanges = false;
for (const [, block] of fn.body.blocks) {
/*
* Initialize phi values if all operands have the same known constant value.
* Note that this analysis uses a single-pass only, so it will never fill in
* phi values for blocks that have a back-edge.
*/
for (const phi of block.phis) {
let value = evaluatePhi(phi, constants);
if (value !== null) {
constants.set(phi.place.identifier.id, value);
}
}
for (let i = 0; i < block.instructions.length; i++) {
if (block.kind === 'sequence' && i === block.instructions.length - 1) {
/*
* evaluating the last value of a value block can break order of evaluation,
* skip these instructions
*/
continue;
}
const instr = block.instructions[i]!;
const value = evaluateInstruction(constants, instr, jsxSimpleTagPlaces);
if (value !== null) {
constants.set(instr.lvalue.identifier.id, value);
}
}
const terminal = block.terminal;
switch (terminal.kind) {
case 'if': {
const testValue = read(constants, terminal.test);
if (testValue !== null && testValue.kind === 'Primitive') {
hasChanges = true;
const targetBlockId = testValue.value
? terminal.consequent
: terminal.alternate;
block.terminal = {
kind: 'goto',
variant: GotoVariant.Break,
block: targetBlockId,
id: terminal.id,
loc: terminal.loc,
};
}
break;
}
default: {
// no-op
}
}
}
return hasChanges;
}
function evaluatePhi(phi: Phi, constants: Constants): Constant | null {
let value: Constant | null = null;
for (const [, operand] of phi.operands) {
const operandValue = constants.get(operand.identifier.id) ?? null;
// did not find a constant, can't constant propogate
if (operandValue === null) {
return null;
}
/*
* first iteration of the loop, let's store the operand and continue
* looping.
*/
if (value === null) {
value = operandValue;
continue;
}
// found different kinds of constants, can't constant propogate
if (operandValue.kind !== value.kind) {
return null;
}
switch (operandValue.kind) {
case 'Primitive': {
CompilerError.invariant(value.kind === 'Primitive', {
reason: 'value kind expected to be Primitive',
loc: GeneratedSource,
});
// different constant values, can't constant propogate
if (operandValue.value !== value.value) {
return null;
}
break;
}
case 'LoadGlobal': {
CompilerError.invariant(value.kind === 'LoadGlobal', {
reason: 'value kind expected to be LoadGlobal',
loc: GeneratedSource,
});
// different global values, can't constant propogate
if (operandValue.binding.name !== value.binding.name) {
return null;
}
break;
}
default:
return null;
}
}
return value;
}
function evaluateInstruction(
constants: Constants,
instr: Instruction,
jsxSimpleTagPlaces: Set<IdentifierId>,
): Constant | null {
const value = instr.value;
switch (value.kind) {
case 'Primitive': {
return value;
}
case 'LoadGlobal': {
return value;
}
case 'ComputedLoad': {
const property = read(constants, value.property);
if (
property !== null &&
property.kind === 'Primitive' &&
((typeof property.value === 'string' &&
isValidIdentifier(property.value)) ||
typeof property.value === 'number')
) {
const nextValue: InstructionValue = {
kind: 'PropertyLoad',
loc: value.loc,
property: makePropertyLiteral(property.value),
object: value.object,
};
instr.value = nextValue;
}
return null;
}
case 'ComputedStore': {
const property = read(constants, value.property);
if (
property !== null &&
property.kind === 'Primitive' &&
((typeof property.value === 'string' &&
isValidIdentifier(property.value)) ||
typeof property.value === 'number')
) {
const nextValue: InstructionValue = {
kind: 'PropertyStore',
loc: value.loc,
property: makePropertyLiteral(property.value),
object: value.object,
value: value.value,
};
instr.value = nextValue;
}
return null;
}
case 'PostfixUpdate': {
const previous = read(constants, value.value);
if (
previous !== null &&
previous.kind === 'Primitive' &&
typeof previous.value === 'number'
) {
const next =
value.operation === '++' ? previous.value + 1 : previous.value - 1;
// Store the updated value
constants.set(value.lvalue.identifier.id, {
kind: 'Primitive',
value: next,
loc: value.loc,
});
// But return the value prior to the update
return previous;
}
return null;
}
case 'PrefixUpdate': {
const previous = read(constants, value.value);
if (
previous !== null &&
previous.kind === 'Primitive' &&
typeof previous.value === 'number'
) {
const next: Primitive = {
kind: 'Primitive',
value:
value.operation === '++' ? previous.value + 1 : previous.value - 1,
loc: value.loc,
};
// Store and return the updated value
constants.set(value.lvalue.identifier.id, next);
return next;
}
return null;
}
case 'UnaryExpression': {
switch (value.operator) {
case '!': {
const operand = read(constants, value.value);
if (operand !== null && operand.kind === 'Primitive') {
const result: Primitive = {
kind: 'Primitive',
value: !operand.value,
loc: value.loc,
};
instr.value = result;
return result;
}
return null;
}
case '-': {
const operand = read(constants, value.value);
if (
operand !== null &&
operand.kind === 'Primitive' &&
typeof operand.value === 'number'
) {
const result: Primitive = {
kind: 'Primitive',
value: operand.value * -1,
loc: value.loc,
};
instr.value = result;
return result;
}
return null;
}
default:
return null;
}
}
case 'BinaryExpression': {
const lhsValue = read(constants, value.left);
const rhsValue = read(constants, value.right);
if (
lhsValue !== null &&
rhsValue !== null &&
lhsValue.kind === 'Primitive' &&
rhsValue.kind === 'Primitive'
) {
const lhs = lhsValue.value;
const rhs = rhsValue.value;
let result: Primitive | null = null;
switch (value.operator) {
case '+': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs + rhs, loc: value.loc};
} else if (typeof lhs === 'string' && typeof rhs === 'string') {
result = {kind: 'Primitive', value: lhs + rhs, loc: value.loc};
}
break;
}
case '-': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs - rhs, loc: value.loc};
}
break;
}
case '*': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs * rhs, loc: value.loc};
}
break;
}
case '/': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs / rhs, loc: value.loc};
}
break;
}
case '|': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs | rhs, loc: value.loc};
}
break;
}
case '&': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs & rhs, loc: value.loc};
}
break;
}
case '^': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs ^ rhs, loc: value.loc};
}
break;
}
case '<<': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs << rhs, loc: value.loc};
}
break;
}
case '>>': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs >> rhs, loc: value.loc};
}
break;
}
case '>>>': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {
kind: 'Primitive',
value: lhs >>> rhs,
loc: value.loc,
};
}
break;
}
case '%': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs % rhs, loc: value.loc};
}
break;
}
case '**': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs ** rhs, loc: value.loc};
}
break;
}
case '<': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs < rhs, loc: value.loc};
}
break;
}
case '<=': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs <= rhs, loc: value.loc};
}
break;
}
case '>': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs > rhs, loc: value.loc};
}
break;
}
case '>=': {
if (typeof lhs === 'number' && typeof rhs === 'number') {
result = {kind: 'Primitive', value: lhs >= rhs, loc: value.loc};
}
break;
}
case '==': {
result = {kind: 'Primitive', value: lhs == rhs, loc: value.loc};
break;
}
case '===': {
result = {kind: 'Primitive', value: lhs === rhs, loc: value.loc};
break;
}
case '!=': {
result = {kind: 'Primitive', value: lhs != rhs, loc: value.loc};
break;
}
case '!==': {
result = {kind: 'Primitive', value: lhs !== rhs, loc: value.loc};
break;
}
default: {
break;
}
}
if (result !== null) {
instr.value = result;
return result;
}
}
return null;
}
case 'PropertyLoad': {
const objectValue = read(constants, value.object);
if (objectValue !== null) {
if (
objectValue.kind === 'Primitive' &&
typeof objectValue.value === 'string' &&
value.property === 'length'
) {
const result: InstructionValue = {
kind: 'Primitive',
value: objectValue.value.length,
loc: value.loc,
};
instr.value = result;
return result;
}
}
return null;
}
case 'TemplateLiteral': {
if (value.subexprs.length === 0) {
const result: InstructionValue = {
kind: 'Primitive',
value: value.quasis.map(q => q.cooked).join(''),
loc: value.loc,
};
instr.value = result;
return result;
}
if (value.subexprs.length !== value.quasis.length - 1) {
return null;
}
if (value.quasis.some(q => q.cooked === undefined)) {
return null;
}
let quasiIndex = 0;
let resultString = value.quasis[quasiIndex].cooked as string;
++quasiIndex;
for (const subExpr of value.subexprs) {
const subExprValue = read(constants, subExpr);
if (!subExprValue || subExprValue.kind !== 'Primitive') {
return null;
}
const expressionValue = subExprValue.value;
if (
typeof expressionValue !== 'number' &&
typeof expressionValue !== 'string' &&
typeof expressionValue !== 'boolean' &&
!(typeof expressionValue === 'object' && expressionValue === null)
) {
// value is not supported (function, object) or invalid (symbol), or something else
return null;
}
const suffix = value.quasis[quasiIndex].cooked;
++quasiIndex;
if (suffix === undefined) {
return null;
}
/*
* Spec states that concat calls ToString(argument) internally on its parameters
* -> we don't have to implement ToString(argument) ourselves and just use the engine implementation
* Refs:
* - https://tc39.es/ecma262/2024/#sec-tostring
* - https://tc39.es/ecma262/2024/#sec-string.prototype.concat
* - https://tc39.es/ecma262/2024/#sec-template-literals-runtime-semantics-evaluation
*/
resultString = resultString.concat(expressionValue as string, suffix);
}
const result: InstructionValue = {
kind: 'Primitive',
value: resultString,
loc: value.loc,
};
instr.value = result;
return result;
}
case 'LoadLocal': {
const placeValue = read(constants, value.place);
if (placeValue !== null) {
/*
* Skip rewriting when the lvalue is used as a simple JSX tag and the
* candidate constant is a LoadGlobal whose binding name has different
* JSX component-vs-intrinsic casing than the local. Propagating would
* flip `<Comp />` (component reference) into `<base />` (intrinsic
* HTML tag) or vice versa, changing runtime semantics.
*/
if (
placeValue.kind === 'LoadGlobal' &&
jsxSimpleTagPlaces.has(instr.lvalue.identifier.id)
) {
const localName =
value.place.identifier.name?.kind === 'named'
? value.place.identifier.name.value
: null;
const globalName = placeValue.binding.name;
if (
localName !== null &&
isLikelyComponentName(localName) !==
isLikelyComponentName(globalName)
) {
return placeValue;
}
}
instr.value = placeValue;
}
return placeValue;
}
case 'StoreLocal': {
const placeValue = read(constants, value.value);
if (placeValue !== null) {
constants.set(value.lvalue.place.identifier.id, placeValue);
}
return placeValue;
}
case 'ObjectMethod':
case 'FunctionExpression': {
constantPropagationImpl(
value.loweredFunc.func,
constants,
jsxSimpleTagPlaces,
);
return null;
}
case 'StartMemoize': {
if (value.deps != null) {
for (const dep of value.deps) {
if (dep.root.kind === 'NamedLocal') {
const placeValue = read(constants, dep.root.value);
if (placeValue != null && placeValue.kind === 'Primitive') {
dep.root.constant = true;
}
}
}
}
return null;
}
default: {
// TODO: handle more cases
return null;
}
}
}
/*
* Recursively read the value of a place: if it is a constant place, attempt to read
* from that place until reaching a primitive or finding a value that is unset.
*/
function read(constants: Constants, place: Place): Constant | null {
return constants.get(place.identifier.id) ?? null;
}
type Constant = Primitive | LoadGlobal;
type Constants = Map<IdentifierId, Constant>;