-
-
Notifications
You must be signed in to change notification settings - Fork 670
/
Copy pathflow.ts
1410 lines (1292 loc) · 52.5 KB
/
flow.ts
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview A concurrent code flow analyzer.
*
* Flows keep track of compilation state and can be queried for various
* conditions, like whether the current branch always terminates, whether
* a local is known to be non-null or whether an expression has possibly
* overflown its value range.
*
* To accomplish this, compilation of each function begins with a clean
* flow populated with initial local states etc. While compilation
* progresses, statements and expressions update flow state while control
* constructs fork, potentially add scoped locals and later merge these
* forked branches as necessary.
*
* @license Apache-2.0
*/
import {
Type,
TypeFlags,
TypeKind
} from "./types";
import {
Local,
Function,
Element,
ElementKind,
Global
} from "./program";
import {
NativeType,
ExpressionId,
ExpressionRef,
BinaryOp,
UnaryOp,
getExpressionId,
getLocalGetIndex,
isLocalTee,
getLocalSetValue,
getGlobalGetName,
getBinaryOp,
getBinaryLeft,
getConstValueI32,
getBinaryRight,
getUnaryOp,
getExpressionType,
getConstValueI64Low,
getConstValueF32,
getConstValueF64,
getLoadBytes,
isLoadSigned,
getBlockName,
getBlockChildCount,
getBlockChild,
getIfTrue,
getIfFalse,
getSelectThen,
getSelectElse,
getCallTarget,
getLocalSetIndex,
getIfCondition,
getConstValueI64High,
getUnaryValue,
getCallOperand,
traverse
} from "./module";
import {
CommonFlags
} from "./common";
import {
DiagnosticCode
} from "./diagnostics";
import {
Node
} from "./ast";
/** Control flow flags indicating specific conditions. */
export const enum FlowFlags {
/** No specific conditions. */
NONE = 0,
// categorical
/** This flow always returns. */
RETURNS = 1 << 0,
/** This flow always returns a wrapped value. */
RETURNS_WRAPPED = 1 << 1,
/** This flow always returns a non-null value. */
RETURNS_NONNULL = 1 << 2,
/** This flow always throws. */
THROWS = 1 << 3,
/** This flow always breaks. */
BREAKS = 1 << 4,
/** This flow always continues. */
CONTINUES = 1 << 5,
/** This flow always accesses `this`. Constructors only. */
ACCESSES_THIS = 1 << 6,
/** This flow always calls `super`. Constructors only. */
CALLS_SUPER = 1 << 7,
/** This flow always terminates (returns, throws or continues). */
TERMINATES = 1 << 8, // Note that this doesn't cover BREAKS, which is separate
// conditional
/** This flow conditionally returns in a child flow. */
CONDITIONALLY_RETURNS = 1 << 9,
/** This flow conditionally throws in a child flow. */
CONDITIONALLY_THROWS = 1 << 10,
/** This flow conditionally breaks in a child flow. */
CONDITIONALLY_BREAKS = 1 << 11,
/** This flow conditionally continues in a child flow. */
CONDITIONALLY_CONTINUES = 1 << 12,
/** This flow conditionally accesses `this` in a child flow. Constructors only. */
CONDITIONALLY_ACCESSES_THIS = 1 << 13,
/** This flow may return a non-this value. Constructors only. */
MAY_RETURN_NONTHIS = 1 << 14,
// other
/** This is a flow with explicitly disabled bounds checking. */
UNCHECKED_CONTEXT = 1 << 15,
// masks
/** Any categorical flag. */
ANY_CATEGORICAL = FlowFlags.RETURNS
| FlowFlags.RETURNS_WRAPPED
| FlowFlags.RETURNS_NONNULL
| FlowFlags.THROWS
| FlowFlags.BREAKS
| FlowFlags.CONTINUES
| FlowFlags.ACCESSES_THIS
| FlowFlags.CALLS_SUPER
| FlowFlags.TERMINATES,
/** Any conditional flag. */
ANY_CONDITIONAL = FlowFlags.CONDITIONALLY_RETURNS
| FlowFlags.CONDITIONALLY_THROWS
| FlowFlags.CONDITIONALLY_BREAKS
| FlowFlags.CONDITIONALLY_CONTINUES
| FlowFlags.CONDITIONALLY_ACCESSES_THIS
}
/** Flags indicating the current state of a local. */
export enum LocalFlags {
/** No specific conditions. */
NONE = 0,
/** Local is constant. */
CONSTANT = 1 << 0,
/** Local is properly wrapped. Relevant for small integers. */
WRAPPED = 1 << 1,
/** Local is non-null. */
NONNULL = 1 << 2,
/** Local is initialized. */
INITIALIZED = 1 << 3,
/** Local is retained. */
RETAINED = 1 << 4,
/** Local must be conditionally retained. */
CONDITIONALLY_RETAINED = 1 << 5,
/** Any retained flag. */
ANY_RETAINED = RETAINED
| CONDITIONALLY_RETAINED
}
/** Condition kinds. */
export const enum ConditionKind {
/** Outcome of the condition is unknown */
UNKNOWN,
/** Condition is always true. */
TRUE,
/** Condition is always false. */
FALSE
}
/** A control flow evaluator. */
export class Flow {
/** Creates the parent flow of the specified function. */
static createParent(parentFunction: Function): Flow {
return new Flow(parentFunction);
}
/** Creates an inline flow within `parentFunction`. */
static createInline(parentFunction: Function, inlineFunction: Function): Flow {
var flow = new Flow(parentFunction);
flow.inlineFunction = inlineFunction;
flow.inlineReturnLabel = inlineFunction.internalName + "|inlined." + (inlineFunction.nextInlineId++).toString();
return flow;
}
private constructor(
/** Function this flow belongs to. */
public parentFunction: Function
) {
/* nop */
}
/** Parent flow. */
parent: Flow | null = null;
/** Flow flags indicating specific conditions. */
flags: FlowFlags = FlowFlags.NONE;
/** The label we break to when encountering a continue statement. */
continueLabel: string | null = null;
/** The label we break to when encountering a break statement. */
breakLabel: string | null = null;
/** Scoped local variables. */
scopedLocals: Map<string,Local> | null = null;
/** Local flags. */
localFlags: LocalFlags[] = [];
/** Function being inlined, when inlining. */
inlineFunction: Function | null = null;
/** The label we break to when encountering a return statement, when inlining. */
inlineReturnLabel: string | null = null;
/** Tests if this is an inline flow. */
get isInline(): bool {
return this.inlineFunction !== null;
}
/** Gets the actual function being compiled, The inlined function when inlining, otherwise the parent function. */
get actualFunction(): Function {
var inlineFunction = this.inlineFunction;
if (inlineFunction) return inlineFunction;
return this.parentFunction;
}
/** Gets the current return type. */
get returnType(): Type {
return this.actualFunction.signature.returnType;
}
/** Gets the current contextual type arguments. */
get contextualTypeArguments(): Map<string,Type> | null {
return this.actualFunction.contextualTypeArguments;
}
/** Tests if this flow has the specified flag or flags. */
is(flag: FlowFlags): bool { return (this.flags & flag) == flag; }
/** Tests if this flow has one of the specified flags. */
isAny(flag: FlowFlags): bool { return (this.flags & flag) != 0; }
/** Sets the specified flag or flags. */
set(flag: FlowFlags): void { this.flags |= flag; }
/** Unsets the specified flag or flags. */
unset(flag: FlowFlags): void { this.flags &= ~flag; }
/** Forks this flow to a child flow. */
fork(resetBreakContext: bool = false): Flow {
var branch = new Flow(this.parentFunction);
branch.parent = this;
if (resetBreakContext) {
branch.flags = this.flags & ~(
FlowFlags.BREAKS |
FlowFlags.CONDITIONALLY_BREAKS |
FlowFlags.CONTINUES |
FlowFlags.CONDITIONALLY_CONTINUES
);
} else {
branch.flags = this.flags;
branch.continueLabel = this.continueLabel;
branch.breakLabel = this.breakLabel;
}
branch.localFlags = this.localFlags.slice();
branch.inlineFunction = this.inlineFunction;
branch.inlineReturnLabel = this.inlineReturnLabel;
return branch;
}
/** Gets a free temporary local of the specified type. */
getTempLocal(type: Type, except: Set<i32> | null = null): Local {
var parentFunction = this.parentFunction;
var temps: Local[] | null;
switch (<u32>type.toNativeType()) {
case <u32>NativeType.I32: { temps = parentFunction.tempI32s; break; }
case <u32>NativeType.I64: { temps = parentFunction.tempI64s; break; }
case <u32>NativeType.F32: { temps = parentFunction.tempF32s; break; }
case <u32>NativeType.F64: { temps = parentFunction.tempF64s; break; }
case <u32>NativeType.V128: { temps = parentFunction.tempV128s; break; }
case <u32>NativeType.Anyref: { temps = parentFunction.tempAnyrefs; break; }
case <u32>NativeType.Exnref: { temps = parentFunction.tempExnrefs; break; }
default: throw new Error("concrete type expected");
}
var local: Local;
if (except) {
if (temps !== null && temps.length > 0) {
for (let i = 0, k = temps.length; i < k; ++i) {
if (!except.has(temps[i].index)) {
local = temps[i];
let k = temps.length - 1;
while (i < k) unchecked(temps[i] = temps[i++ + 1]);
temps.length = k;
local.type = type;
local.flags = CommonFlags.NONE;
this.unsetLocalFlag(local.index, ~0);
return local;
}
}
}
local = parentFunction.addLocal(type);
} else {
if (temps !== null && temps.length > 0) {
local = assert(temps.pop());
local.type = type;
local.flags = CommonFlags.NONE;
} else {
local = parentFunction.addLocal(type);
}
}
this.unsetLocalFlag(local.index, ~0);
return local;
}
/** Gets a local that sticks around until this flow is exited, and then released. */
getAutoreleaseLocal(type: Type, except: Set<i32> | null = null): Local {
var local = this.getTempLocal(type, except);
local.set(CommonFlags.SCOPED);
var scopedLocals = this.scopedLocals;
if (!scopedLocals) this.scopedLocals = scopedLocals = new Map();
scopedLocals.set("~auto" + (this.parentFunction.nextAutoreleaseId++).toString(), local);
this.setLocalFlag(local.index, LocalFlags.RETAINED);
return local;
}
/** Frees the temporary local for reuse. */
freeTempLocal(local: Local): void {
if (local.is(CommonFlags.INLINED)) return;
assert(local.index >= 0);
var parentFunction = this.parentFunction;
var temps: Local[];
assert(local.type != null); // internal error
local.resetTemporaryName();
switch (<u32>local.type.toNativeType()) {
case <u32>NativeType.I32: {
let tempI32s = parentFunction.tempI32s;
if (tempI32s) temps = tempI32s;
else parentFunction.tempI32s = temps = [];
break;
}
case <u32>NativeType.I64: {
let tempI64s = parentFunction.tempI64s;
if (tempI64s) temps = tempI64s;
else parentFunction.tempI64s = temps = [];
break;
}
case <u32>NativeType.F32: {
let tempF32s = parentFunction.tempF32s;
if (tempF32s) temps = tempF32s;
else parentFunction.tempF32s = temps = [];
break;
}
case <u32>NativeType.F64: {
let tempF64s = parentFunction.tempF64s;
if (tempF64s) temps = tempF64s;
else parentFunction.tempF64s = temps = [];
break;
}
case <u32>NativeType.V128: {
let tempV128s = parentFunction.tempV128s;
if (tempV128s) temps = tempV128s;
else parentFunction.tempV128s = temps = [];
break;
}
case <u32>NativeType.Anyref: {
let tempAnyrefs = parentFunction.tempAnyrefs;
if (tempAnyrefs) temps = tempAnyrefs;
else parentFunction.tempAnyrefs = temps = [];
break;
}
case <u32>NativeType.Exnref: {
let tempExnrefs = parentFunction.tempExnrefs;
if (tempExnrefs) temps = tempExnrefs;
else parentFunction.tempExnrefs = temps = [];
break;
}
default: throw new Error("concrete type expected");
}
assert(local.index >= 0);
temps.push(local);
}
/** Gets the scoped local of the specified name. */
getScopedLocal(name: string): Local | null {
var scopedLocals = this.scopedLocals;
if (scopedLocals !== null && scopedLocals.has(name)) return assert(scopedLocals.get(name));
return null;
}
/** Adds a new scoped local of the specified name. */
addScopedLocal(name: string, type: Type, except: Set<i32> | null = null): Local {
var scopedLocal = this.getTempLocal(type, except);
scopedLocal.setTemporaryName(name);
var scopedLocals = this.scopedLocals;
if (!scopedLocals) this.scopedLocals = scopedLocals = new Map();
else assert(!scopedLocals.has(name));
scopedLocal.set(CommonFlags.SCOPED);
scopedLocals.set(name, scopedLocal);
return scopedLocal;
}
/** Adds a new scoped dummy local of the specified name. */
addScopedDummyLocal(name: string, type: Type): Local {
var scopedDummy = new Local(name, -1, type, this.parentFunction);
var scopedLocals = this.scopedLocals;
if (!scopedLocals) this.scopedLocals = scopedLocals = new Map();
else assert(!scopedLocals.has(name));
scopedDummy.set(CommonFlags.SCOPED);
scopedLocals.set(name, scopedDummy);
return scopedDummy;
}
/** Adds a new scoped alias for the specified local. For example `super` aliased to the `this` local. */
addScopedAlias(name: string, type: Type, index: i32, reportNode: Node | null = null): Local {
var scopedLocals = this.scopedLocals;
if (!scopedLocals) this.scopedLocals = scopedLocals = new Map();
else {
let existingLocal = scopedLocals.get(name);
if (existingLocal) {
if (reportNode) {
if (!existingLocal.declaration.range.source.isNative) {
this.parentFunction.program.errorRelated(
DiagnosticCode.Duplicate_identifier_0,
reportNode.range,
existingLocal.declaration.name.range,
name
);
} else {
this.parentFunction.program.error(
DiagnosticCode.Duplicate_identifier_0,
reportNode.range, name
);
}
}
return existingLocal;
}
}
assert(index < this.parentFunction.localsByIndex.length);
var scopedAlias = new Local(name, index, type, this.parentFunction);
// not flagged as SCOPED as it must not be free'd when the flow is finalized
scopedLocals.set(name, scopedAlias);
return scopedAlias;
}
/** Tests if this flow has any scoped locals that must be free'd. */
get hasScopedLocals(): bool {
var scopedLocals = this.scopedLocals;
if (scopedLocals) {
// TODO: for (let local of scopedLocals.values()) {
for (let _values = Map_values(scopedLocals), i = 0, k = _values.length; i < k; ++i) {
let local = unchecked(_values[i]);
if (local.is(CommonFlags.SCOPED)) { // otherwise an alias
return true;
}
}
}
return false;
}
/** Frees a single scoped local by its name. */
freeScopedDummyLocal(name: string): void {
var scopedLocals = assert(this.scopedLocals);
assert(scopedLocals.has(name));
let local = assert(scopedLocals.get(name));
assert(local.index == -1);
scopedLocals.delete(name);
}
/** Frees this flow's scoped variables and returns its parent flow. */
freeScopedLocals(): void {
var scopedLocals = this.scopedLocals;
if (scopedLocals) {
// TODO: for (let local of scopedLocals.values()) {
for (let _values = Map_values(scopedLocals), i = 0, k = _values.length; i < k; ++i) {
let local = unchecked(_values[i]);
if (local.is(CommonFlags.SCOPED)) { // otherwise an alias
this.freeTempLocal(local);
}
}
this.scopedLocals = null;
}
}
/** Looks up the local of the specified name in the current scope. */
lookupLocal(name: string): Local | null {
var current: Flow | null = this;
do {
let scope = current.scopedLocals;
if (scope !== null && scope.has(name)) return assert(scope.get(name));
current = current.parent;
} while (current);
var localsByName = this.parentFunction.localsByName;
if (localsByName.has(name)) return assert(localsByName.get(name));
return null;
}
/** Looks up the element with the specified name relative to the scope of this flow. */
lookup(name: string): Element | null {
var element = this.lookupLocal(name);
if (element) return element;
return this.actualFunction.lookup(name);
}
/** Tests if the local at the specified index has the specified flag or flags. */
isLocalFlag(index: i32, flag: LocalFlags, defaultIfInlined: bool = true): bool {
if (index < 0) return defaultIfInlined;
var localFlags = this.localFlags;
return index < localFlags.length && (unchecked(localFlags[index]) & flag) == flag;
}
/** Tests if the local at the specified index has any of the specified flags. */
isAnyLocalFlag(index: i32, flag: LocalFlags, defaultIfInlined: bool = true): bool {
if (index < 0) return defaultIfInlined;
var localFlags = this.localFlags;
return index < localFlags.length && (unchecked(localFlags[index]) & flag) != 0;
}
/** Sets the specified flag or flags on the local at the specified index. */
setLocalFlag(index: i32, flag: LocalFlags): void {
if (index < 0) return;
var localFlags = this.localFlags;
var flags = index < localFlags.length ? unchecked(localFlags[index]) : 0;
localFlags[index] = flags | flag;
}
/** Unsets the specified flag or flags on the local at the specified index. */
unsetLocalFlag(index: i32, flag: LocalFlags): void {
if (index < 0) return;
var localFlags = this.localFlags;
var flags = index < localFlags.length ? unchecked(localFlags[index]) : 0;
localFlags[index] = flags & ~flag;
}
/** Pushes a new break label to the stack, for example when entering a loop that one can `break` from. */
pushBreakLabel(): string {
var parentFunction = this.parentFunction;
var id = parentFunction.nextBreakId++;
var stack = parentFunction.breakStack;
if (!stack) parentFunction.breakStack = [ id ];
else stack.push(id);
var label = id.toString();
parentFunction.breakLabel = label;
return label;
}
/** Pops the most recent break label from the stack. */
popBreakLabel(): void {
var parentFunction = this.parentFunction;
var stack = assert(parentFunction.breakStack);
var length = assert(stack.length);
stack.pop();
if (length > 1) {
parentFunction.breakLabel = stack[length - 2].toString();
} else {
parentFunction.breakLabel = null;
parentFunction.breakStack = null;
}
}
/** Inherits flags of another flow into this one, i.e. a finished inner block. */
inherit(other: Flow): void {
assert(other.parentFunction == this.parentFunction);
assert(other.parent == this); // currently the case, but might change
var otherFlags = other.flags;
// respective inner flags are irrelevant if contexts differ
if (this.breakLabel != other.breakLabel) {
if (otherFlags & (FlowFlags.BREAKS | FlowFlags.CONDITIONALLY_BREAKS)) {
otherFlags &= ~FlowFlags.TERMINATES;
}
otherFlags &= ~(FlowFlags.BREAKS | FlowFlags.CONDITIONALLY_BREAKS);
}
if (this.continueLabel != other.continueLabel) {
otherFlags &= ~(FlowFlags.CONTINUES | FlowFlags.CONDITIONALLY_CONTINUES);
}
this.flags = this.flags | otherFlags; // what happens before is still true
this.localFlags = other.localFlags;
}
/** Inherits flags of a conditional branch joining again with this one, i.e. then without else. */
inheritBranch(other: Flow, conditionKind: ConditionKind = ConditionKind.UNKNOWN): void {
assert(other.parentFunction == this.parentFunction);
switch (conditionKind) {
case ConditionKind.TRUE: this.inherit(other); // always executes
case ConditionKind.FALSE: return; // never executes
}
// Note that flags in `this` flow have already happened. For instance,
// a return cannot be undone no matter what'd happen in subsequent branches,
// but an allocation, which doesn't terminate, can become conditional. Not
// all flags have a corresponding conditional flag that's tracked.
var thisFlags = this.flags;
var otherFlags = other.flags;
var newFlags = FlowFlags.NONE;
if (thisFlags & FlowFlags.RETURNS) { // nothing can change that
newFlags |= FlowFlags.RETURNS;
} else if (otherFlags & FlowFlags.RETURNS) {
newFlags |= FlowFlags.CONDITIONALLY_RETURNS;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.CONDITIONALLY_RETURNS;
}
// must be the case in both
newFlags |= thisFlags & otherFlags & FlowFlags.RETURNS_WRAPPED;
newFlags |= thisFlags & otherFlags & FlowFlags.RETURNS_NONNULL;
if (thisFlags & FlowFlags.THROWS) { // nothing can change that
newFlags |= FlowFlags.THROWS;
} else if (otherFlags & FlowFlags.THROWS) {
newFlags |= FlowFlags.CONDITIONALLY_THROWS;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.CONDITIONALLY_THROWS;
}
if (thisFlags & FlowFlags.BREAKS) { // nothing can change that
newFlags |= FlowFlags.BREAKS;
} else if (other.breakLabel == this.breakLabel) {
if (otherFlags & FlowFlags.BREAKS) {
newFlags |= FlowFlags.CONDITIONALLY_BREAKS;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.CONDITIONALLY_BREAKS;
}
} else {
newFlags |= thisFlags & FlowFlags.CONDITIONALLY_BREAKS;
}
if (thisFlags & FlowFlags.CONTINUES) { // nothing can change that
newFlags |= FlowFlags.CONTINUES;
} else if (other.continueLabel === this.continueLabel) {
if (otherFlags & FlowFlags.CONTINUES) {
newFlags |= FlowFlags.CONDITIONALLY_CONTINUES;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.CONDITIONALLY_CONTINUES;
}
} else {
newFlags |= thisFlags & FlowFlags.CONDITIONALLY_CONTINUES;
}
if (thisFlags & FlowFlags.ACCESSES_THIS) { // can become conditional
if (otherFlags & FlowFlags.ACCESSES_THIS) {
newFlags |= FlowFlags.ACCESSES_THIS;
} else {
newFlags |= FlowFlags.CONDITIONALLY_ACCESSES_THIS;
}
} else if (otherFlags & FlowFlags.ACCESSES_THIS) {
newFlags |= FlowFlags.CONDITIONALLY_ACCESSES_THIS;
}
// may be the case in any
newFlags |= (thisFlags | otherFlags) & FlowFlags.MAY_RETURN_NONTHIS;
// must be the case in both
newFlags |= thisFlags & otherFlags & FlowFlags.CALLS_SUPER;
if (thisFlags & FlowFlags.TERMINATES) { // nothing can change that
newFlags |= FlowFlags.TERMINATES;
}
this.flags = newFlags | (thisFlags & FlowFlags.UNCHECKED_CONTEXT);
var thisLocalFlags = this.localFlags;
var numThisLocalFlags = thisLocalFlags.length;
var otherLocalFlags = other.localFlags;
var numOtherLocalFlags = otherLocalFlags.length;
var maxLocalFlags = max(numThisLocalFlags, numOtherLocalFlags);
for (let i = 0; i < maxLocalFlags; ++i) {
let thisFlags = i < numThisLocalFlags ? thisLocalFlags[i] : 0;
let otherFlags = i < numOtherLocalFlags ? otherLocalFlags[i] : 0;
let newFlags = thisFlags & otherFlags & (
LocalFlags.CONSTANT |
LocalFlags.WRAPPED |
LocalFlags.NONNULL |
LocalFlags.INITIALIZED
);
if (thisFlags & LocalFlags.RETAINED) {
if (otherFlags & LocalFlags.RETAINED) {
newFlags |= LocalFlags.RETAINED;
} else {
newFlags |= LocalFlags.CONDITIONALLY_RETAINED;
}
} else if (otherFlags & LocalFlags.RETAINED) {
newFlags |= LocalFlags.CONDITIONALLY_RETAINED;
} else {
newFlags |= (thisFlags | otherFlags) & LocalFlags.CONDITIONALLY_RETAINED;
}
thisLocalFlags[i] = newFlags;
}
}
/** Inherits mutual flags of two alternate branches becoming this one, i.e. then with else. */
inheritMutual(left: Flow, right: Flow): void {
assert(left.parentFunction == right.parentFunction);
assert(left.parentFunction == this.parentFunction);
// This differs from the previous method in that no flags are guaranteed
// to happen unless it is the case in both flows.
var leftFlags = left.flags;
var rightFlags = right.flags;
var newFlags = FlowFlags.NONE;
if (leftFlags & FlowFlags.RETURNS) {
if (rightFlags & FlowFlags.RETURNS) {
newFlags |= FlowFlags.RETURNS;
} else {
newFlags |= FlowFlags.CONDITIONALLY_RETURNS;
}
} else if (rightFlags & FlowFlags.RETURNS) {
newFlags |= FlowFlags.CONDITIONALLY_RETURNS;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.CONDITIONALLY_RETURNS;
}
if ((leftFlags & FlowFlags.RETURNS_WRAPPED) && (rightFlags & FlowFlags.RETURNS_WRAPPED)) {
newFlags |= FlowFlags.RETURNS_WRAPPED;
}
if ((leftFlags & FlowFlags.RETURNS_NONNULL) && (rightFlags & FlowFlags.RETURNS_NONNULL)) {
newFlags |= FlowFlags.RETURNS_NONNULL;
}
if (leftFlags & FlowFlags.THROWS) {
if (rightFlags & FlowFlags.THROWS) {
newFlags |= FlowFlags.THROWS;
} else {
newFlags |= FlowFlags.CONDITIONALLY_THROWS;
}
} else if (rightFlags & FlowFlags.THROWS) {
newFlags |= FlowFlags.CONDITIONALLY_THROWS;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.CONDITIONALLY_THROWS;
}
if (leftFlags & FlowFlags.BREAKS) {
if (rightFlags & FlowFlags.BREAKS) {
newFlags |= FlowFlags.BREAKS;
} else {
newFlags |= FlowFlags.CONDITIONALLY_BREAKS;
}
} else if (rightFlags & FlowFlags.BREAKS) {
newFlags |= FlowFlags.CONDITIONALLY_BREAKS;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.CONDITIONALLY_BREAKS;
}
if (leftFlags & FlowFlags.CONTINUES) {
if (rightFlags & FlowFlags.CONTINUES) {
newFlags |= FlowFlags.CONTINUES;
} else {
newFlags |= FlowFlags.CONDITIONALLY_CONTINUES;
}
} else if (rightFlags & FlowFlags.CONTINUES) {
newFlags |= FlowFlags.CONDITIONALLY_CONTINUES;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.CONDITIONALLY_CONTINUES;
}
if (leftFlags & FlowFlags.ACCESSES_THIS) {
if (rightFlags & FlowFlags.ACCESSES_THIS) {
newFlags |= FlowFlags.ACCESSES_THIS;
} else {
newFlags |= FlowFlags.CONDITIONALLY_ACCESSES_THIS;
}
} else if (rightFlags & FlowFlags.ACCESSES_THIS) {
newFlags |= FlowFlags.CONDITIONALLY_ACCESSES_THIS;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.CONDITIONALLY_ACCESSES_THIS;
}
newFlags |= (leftFlags | rightFlags) & FlowFlags.MAY_RETURN_NONTHIS;
if ((leftFlags & FlowFlags.CALLS_SUPER) && (rightFlags & FlowFlags.CALLS_SUPER)) {
newFlags |= FlowFlags.CALLS_SUPER;
}
if ((leftFlags & FlowFlags.TERMINATES) && (rightFlags & FlowFlags.TERMINATES)) {
newFlags |= FlowFlags.TERMINATES;
}
this.flags = newFlags | (this.flags & FlowFlags.UNCHECKED_CONTEXT);
var thisLocalFlags = this.localFlags;
if (leftFlags & FlowFlags.TERMINATES) {
if (!(rightFlags & FlowFlags.TERMINATES)) {
let rightLocalFlags = right.localFlags;
for (let i = 0, k = rightLocalFlags.length; i < k; ++i) {
thisLocalFlags[i] = rightLocalFlags[i];
}
}
} else if (rightFlags & FlowFlags.TERMINATES) {
let leftLocalFlags = left.localFlags;
for (let i = 0, k = leftLocalFlags.length; i < k; ++i) {
thisLocalFlags[i] = leftLocalFlags[i];
}
} else {
let leftLocalFlags = left.localFlags;
let numLeftLocalFlags = leftLocalFlags.length;
let rightLocalFlags = right.localFlags;
let numRightLocalFlags = rightLocalFlags.length;
let maxLocalFlags = max(numLeftLocalFlags, numRightLocalFlags);
for (let i = 0; i < maxLocalFlags; ++i) {
let leftFlags = i < numLeftLocalFlags ? leftLocalFlags[i] : 0;
let rightFlags = i < numRightLocalFlags ? rightLocalFlags[i] : 0;
let newFlags = leftFlags & rightFlags & (
LocalFlags.CONSTANT |
LocalFlags.WRAPPED |
LocalFlags.NONNULL |
LocalFlags.INITIALIZED
);
if (leftFlags & LocalFlags.RETAINED) {
if (rightFlags & LocalFlags.RETAINED) {
newFlags |= LocalFlags.RETAINED;
} else {
newFlags |= LocalFlags.CONDITIONALLY_RETAINED;
}
} else if (rightFlags & LocalFlags.RETAINED) {
newFlags |= LocalFlags.CONDITIONALLY_RETAINED;
} else {
newFlags |= (leftFlags | rightFlags) & LocalFlags.CONDITIONALLY_RETAINED;
}
thisLocalFlags[i] = newFlags;
}
}
}
/** Tests if the specified flows have differing local states. */
static hasIncompatibleLocalStates(before: Flow, after: Flow): bool {
var numThisLocalFlags = before.localFlags.length;
var numOtherLocalFlags = after.localFlags.length;
var parentFunction = before.parentFunction;
assert(parentFunction === after.parentFunction);
var localsByIndex = parentFunction.localsByIndex;
assert(localsByIndex === after.parentFunction.localsByIndex);
for (let i = 0, k = min<i32>(numThisLocalFlags, numOtherLocalFlags); i < k; ++i) {
let local = localsByIndex[i];
let type = local.type;
if (type.is(TypeFlags.SHORT | TypeFlags.INTEGER)) {
if (before.isLocalFlag(i, LocalFlags.WRAPPED) && !after.isLocalFlag(i, LocalFlags.WRAPPED)) {
return true;
}
}
if (type.is(TypeFlags.REFERENCE)) {
if (before.isLocalFlag(i, LocalFlags.NONNULL) && !after.isLocalFlag(i, LocalFlags.NONNULL)) {
return true;
}
}
}
return false;
}
/** Unifies local flags between this and the other flow. */
unifyLocalFlags(other: Flow): void {
var numThisLocalFlags = this.localFlags.length;
var numOtherLocalFlags = other.localFlags.length;
for (let i = 0, k = min<i32>(numThisLocalFlags, numOtherLocalFlags); i < k; ++i) {
if (this.isLocalFlag(i, LocalFlags.WRAPPED) != other.isLocalFlag(i, LocalFlags.WRAPPED)) {
this.unsetLocalFlag(i, LocalFlags.WRAPPED); // assume not wrapped
}
if (this.isLocalFlag(i, LocalFlags.NONNULL) != other.isLocalFlag(i, LocalFlags.NONNULL)) {
this.unsetLocalFlag(i, LocalFlags.NONNULL); // assume possibly null
}
assert(
// having different retain states would be a problem because the compiler
// either can't release a retained local or would release a non-retained local
this.isAnyLocalFlag(i, LocalFlags.ANY_RETAINED) == other.isAnyLocalFlag(i, LocalFlags.ANY_RETAINED)
);
}
}
/** Checks if an expression of the specified type is known to be non-null, even if the type might be nullable. */
isNonnull(expr: ExpressionRef, type: Type): bool {
if (!type.is(TypeFlags.NULLABLE)) return true;
// below, only teeLocal/getLocal are relevant because these are the only expressions that
// depend on a dynamic nullable state (flag = LocalFlags.NONNULL), while everything else
// has already been handled by the nullable type check above.
switch (getExpressionId(expr)) {
case ExpressionId.LocalSet: {
if (!isLocalTee(expr)) break;
let local = this.parentFunction.localsByIndex[getLocalSetIndex(expr)];
return !local.type.is(TypeFlags.NULLABLE) || this.isLocalFlag(local.index, LocalFlags.NONNULL, false);
}
case ExpressionId.LocalGet: {
let local = this.parentFunction.localsByIndex[getLocalGetIndex(expr)];
return !local.type.is(TypeFlags.NULLABLE) || this.isLocalFlag(local.index, LocalFlags.NONNULL, false);
}
}
return false;
}
/** Updates local states to reflect that this branch is only taken when `expr` is true-ish. */
inheritNonnullIfTrue(
/** Expression being true. */
expr: ExpressionRef,
/** If specified, only set the flag if also nonnull in this flow. */
iff: Flow | null = null
): void {
// A: `expr` is true-ish -> Q: how did that happen?
// The iff argument is useful in situations like
//
// if (!ref) {
// ref = new Ref();
// }
// // inheritNonnullIfFalse(`!ref`, thenFlow) -> ref != null
//
switch (getExpressionId(expr)) {
case ExpressionId.LocalSet: {
if (!isLocalTee(expr)) break;
let local = this.parentFunction.localsByIndex[getLocalSetIndex(expr)];
if (!iff || iff.isLocalFlag(local.index, LocalFlags.NONNULL)) {
this.setLocalFlag(local.index, LocalFlags.NONNULL);
}
this.inheritNonnullIfTrue(getLocalSetValue(expr), iff); // must have been true-ish as well
break;
}
case ExpressionId.LocalGet: {
let local = this.parentFunction.localsByIndex[getLocalGetIndex(expr)];
if (!iff || iff.isLocalFlag(local.index, LocalFlags.NONNULL)) {
this.setLocalFlag(local.index, LocalFlags.NONNULL);
}
break;
}
case ExpressionId.If: {
let ifFalse = getIfFalse(expr);
if (!ifFalse) break;
if (getExpressionId(ifFalse) == ExpressionId.Const) {
// Logical AND: (if (condition ifTrue 0))
// the only way this had become true is if condition and ifTrue are true
if (
(getExpressionType(ifFalse) == NativeType.I32 && getConstValueI32(ifFalse) == 0) ||
(getExpressionType(ifFalse) == NativeType.I64 && getConstValueI64Low(ifFalse) == 0 && getConstValueI64High(ifFalse) == 0)
) {
this.inheritNonnullIfTrue(getIfCondition(expr), iff);
this.inheritNonnullIfTrue(getIfTrue(expr), iff);
}
}
break;
}
case ExpressionId.Unary: {
switch (getUnaryOp(expr)) {
case UnaryOp.EqzI32:
case UnaryOp.EqzI64: {
this.inheritNonnullIfFalse(getUnaryValue(expr), iff); // !value -> value must have been false
break;
}
}
break;
}
case ExpressionId.Binary: {
switch (getBinaryOp(expr)) {
case BinaryOp.EqI32: {
let left = getBinaryLeft(expr);
let right = getBinaryRight(expr);
if (getExpressionId(left) == ExpressionId.Const && getConstValueI32(left) != 0) {
this.inheritNonnullIfTrue(right, iff); // TRUE == right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI32(right) != 0) {
this.inheritNonnullIfTrue(left, iff); // left == TRUE -> left must have been true
}
break;
}
case BinaryOp.EqI64: {
let left = getBinaryLeft(expr);
let right = getBinaryRight(expr);
if (getExpressionId(left) == ExpressionId.Const && (getConstValueI64Low(left) != 0 || getConstValueI64High(left) != 0)) {
this.inheritNonnullIfTrue(right, iff); // TRUE == right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && (getConstValueI64Low(right) != 0 && getConstValueI64High(right) != 0)) {
this.inheritNonnullIfTrue(left, iff); // left == TRUE -> left must have been true
}
break;
}
case BinaryOp.NeI32: {
let left = getBinaryLeft(expr);
let right = getBinaryRight(expr);
if (getExpressionId(left) == ExpressionId.Const && getConstValueI32(left) == 0) {
this.inheritNonnullIfTrue(right, iff); // FALSE != right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI32(right) == 0) {
this.inheritNonnullIfTrue(left, iff); // left != FALSE -> left must have been true
}
break;
}
case BinaryOp.NeI64: {
let left = getBinaryLeft(expr);
let right = getBinaryRight(expr);
if (getExpressionId(left) == ExpressionId.Const && getConstValueI64Low(left) == 0 && getConstValueI64High(left) == 0) {
this.inheritNonnullIfTrue(right, iff); // FALSE != right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI64Low(right) == 0 && getConstValueI64High(right) == 0) {
this.inheritNonnullIfTrue(left, iff); // left != FALSE -> left must have been true
}
break;
}
}