forked from AssemblyScript/assemblyscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflow.ts
More file actions
1140 lines (1048 loc) · 42 KB
/
flow.ts
File metadata and controls
1140 lines (1048 loc) · 42 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
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
/**
* A control flow analyzer.
* @module flow
*//***/
import {
Type,
TypeFlags,
TypeKind
} from "./types";
import {
Local,
Function,
Element,
ElementKind,
Global
} from "./program";
import {
NativeType,
ExpressionId,
ExpressionRef,
getExpressionId,
getLocalGetIndex,
isLocalTee,
getLocalSetValue,
getGlobalGetName,
getBinaryOp,
BinaryOp,
getBinaryLeft,
getConstValueI32,
getBinaryRight,
getUnaryOp,
UnaryOp,
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 returns. */
RETURNS = 1 << 0,
/** This flow returns a wrapped value. */
RETURNS_WRAPPED = 1 << 1,
/** This flow returns a non-null value. */
RETURNS_NONNULL = 1 << 2,
/** This flow throws. */
THROWS = 1 << 3,
/** This flow breaks. */
BREAKS = 1 << 4,
/** This flow continues. */
CONTINUES = 1 << 5,
/** This flow allocates. Constructors only. */
ALLOCATES = 1 << 6,
/** This flow calls super. Constructors only. */
CALLS_SUPER = 1 << 7,
/** This flow terminates (returns, throws or continues). */
TERMINATES = 1 << 8,
// 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 terminates in a child flow. */
CONDITIONALLY_TERMINATES = 1 << 11,
/** This flow conditionally breaks in a child flow. */
CONDITIONALLY_BREAKS = 1 << 12,
/** This flow conditionally continues in a child flow. */
CONDITIONALLY_CONTINUES = 1 << 13,
/** This flow conditionally allocates in a child flow. Constructors only. */
CONDITIONALLY_ALLOCATES = 1 << 14,
// special
/** This is an inlining flow. */
INLINE_CONTEXT = 1 << 15,
/** This is a flow with explicitly disabled bounds checking. */
UNCHECKED_CONTEXT = 1 << 16,
// masks
/** Any categorical flag. */
ANY_CATEGORICAL = FlowFlags.RETURNS
| FlowFlags.RETURNS_WRAPPED
| FlowFlags.RETURNS_NONNULL
| FlowFlags.THROWS
| FlowFlags.BREAKS
| FlowFlags.CONTINUES
| FlowFlags.ALLOCATES
| FlowFlags.CALLS_SUPER
| FlowFlags.TERMINATES,
/** Any conditional flag. */
ANY_CONDITIONAL = FlowFlags.CONDITIONALLY_RETURNS
| FlowFlags.CONDITIONALLY_THROWS
| FlowFlags.CONDITIONALLY_BREAKS
| FlowFlags.CONDITIONALLY_CONTINUES
| FlowFlags.CONDITIONALLY_ALLOCATES
}
/** Flags indicating the current state of a local. */
export enum LocalFlags {
/** No specific conditions. */
NONE = 0,
/** Local is constant. */
CONSTANT = 1 << 0,
/** Local is a function parameter. */
PARAMETER = 1 << 1,
/** Local is properly wrapped. Relevant for small integers. */
WRAPPED = 1 << 2,
/** Local is non-null. */
NONNULL = 1 << 3,
/** Local is read from. */
READFROM = 1 << 4,
/** Local is written to. */
WRITTENTO = 1 << 5,
/** Local is retained. */
RETAINED = 1 << 6,
/** Local is returned. */
RETURNED = 1 << 7,
/** Local is conditionally read from. */
CONDITIONALLY_READFROM = 1 << 8,
/** Local is conditionally written to. */
CONDITIONALLY_WRITTENTO = 1 << 9,
/** Local must be conditionally retained. */
CONDITIONALLY_RETAINED = 1 << 10,
/** Local is conditionally returned. */
CONDITIONALLY_RETURNED = 1 << 11,
/** Any categorical flag. */
ANY_CATEGORICAL = CONSTANT
| PARAMETER
| WRAPPED
| NONNULL
| READFROM
| WRITTENTO
| RETAINED
| RETURNED,
/** Any conditional flag. */
ANY_CONDITIONAL = RETAINED
| CONDITIONALLY_READFROM
| CONDITIONALLY_WRITTENTO
| CONDITIONALLY_RETAINED
| CONDITIONALLY_RETURNED,
/** Any written to flag. */
ANY_WRITTENTO = WRITTENTO
| CONDITIONALLY_WRITTENTO,
/** Any retained flag. */
ANY_RETAINED = RETAINED
| CONDITIONALLY_RETAINED,
/** Any returned flag. */
ANY_RETURNED = RETURNED
| CONDITIONALLY_RETURNED
}
export namespace LocalFlags {
export function join(left: LocalFlags, right: LocalFlags): LocalFlags {
return ((left & LocalFlags.ANY_CATEGORICAL) & (right & LocalFlags.ANY_CATEGORICAL))
| (left & LocalFlags.ANY_CONDITIONAL) | (right & LocalFlags.ANY_CONDITIONAL);
}
}
/** Flags indicating the current state of a field. */
export enum FieldFlags {
/** No specific conditions. */
NONE = 0,
/** Field is initialized. Relevant in constructors. */
INITIALIZED = 1 << 0,
/** Field is conditionally initialized. Relevant in constructors. */
CONDITIONALLY_INITIALIZED = 1 << 1,
/** Any categorical flag. */
ANY_CATEGORICAL = INITIALIZED,
/** Any conditional flag. */
ANY_CONDITIONAL = CONDITIONALLY_INITIALIZED
}
export namespace FieldFlags {
export function join(left: FieldFlags, right: FieldFlags): FieldFlags {
return ((left & FieldFlags.ANY_CATEGORICAL) & (right & FieldFlags.ANY_CATEGORICAL))
| (left & FieldFlags.ANY_CONDITIONAL) | (right & FieldFlags.ANY_CONDITIONAL);
}
}
/** A control flow evaluator. */
export class Flow {
/** Parent flow. */
parent: Flow | null;
/** Flow flags indicating specific conditions. */
flags: FlowFlags;
/** Function this flow belongs to. */
parentFunction: Function;
/** The label we break to when encountering a continue statement. */
continueLabel: string | null;
/** The label we break to when encountering a break statement. */
breakLabel: string | null;
/** The current return type. */
returnType: Type;
/** The current contextual type arguments. */
contextualTypeArguments: Map<string,Type> | null;
/** Scoped local variables. */
scopedLocals: Map<string,Local> | null = null;
/** Local flags. */
localFlags: LocalFlags[];
/** Field flags. Relevant in constructors. */
fieldFlags: Map<string,FieldFlags> | null = null;
/** Function being inlined, when inlining. */
inlineFunction: Function | null;
/** The label we break to when encountering a return statement, when inlining. */
inlineReturnLabel: string | null;
/** Creates the parent flow of the specified function. */
static create(parentFunction: Function): Flow {
var flow = new Flow();
flow.parent = null;
flow.flags = FlowFlags.NONE;
flow.parentFunction = parentFunction;
flow.continueLabel = null;
flow.breakLabel = null;
flow.returnType = parentFunction.signature.returnType;
flow.contextualTypeArguments = parentFunction.contextualTypeArguments;
flow.localFlags = [];
flow.inlineFunction = null;
flow.inlineReturnLabel = null;
return flow;
}
/** Creates an inline flow within `parentFunction`. */
static createInline(parentFunction: Function, inlineFunction: Function): Flow {
var flow = Flow.create(parentFunction);
flow.set(FlowFlags.INLINE_CONTEXT);
flow.inlineFunction = inlineFunction;
flow.inlineReturnLabel = inlineFunction.internalName + "|inlined." + (inlineFunction.nextInlineId++).toString(10);
flow.returnType = inlineFunction.signature.returnType;
flow.contextualTypeArguments = inlineFunction.contextualTypeArguments;
return flow;
}
private constructor() { }
/** Gets the actual function being compiled, The inlined function when inlining, otherwise the parent function. */
get actualFunction(): Function {
return this.inlineFunction || this.parentFunction;
}
/** 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(): Flow {
var branch = new Flow();
branch.parent = this;
branch.flags = this.flags;
branch.parentFunction = this.parentFunction;
branch.continueLabel = this.continueLabel;
branch.breakLabel = this.breakLabel;
branch.returnType = this.returnType;
branch.contextualTypeArguments = this.contextualTypeArguments;
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 (type.toNativeType()) {
case NativeType.I32: { temps = parentFunction.tempI32s; break; }
case NativeType.I64: { temps = parentFunction.tempI64s; break; }
case NativeType.F32: { temps = parentFunction.tempF32s; break; }
case NativeType.F64: { temps = parentFunction.tempF64s; break; }
case NativeType.V128: { temps = parentFunction.tempV128s; break; }
case NativeType.Anyref: { temps = parentFunction.tempAnyrefs; break; }
case NativeType.Exnref: { temps = parentFunction.tempExnrefs; break; }
default: throw new Error("concrete type expected");
}
var local: Local;
if (except) {
if (temps && temps.length) {
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 && temps.length) {
local = 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++), 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
switch (local.type.toNativeType()) {
case NativeType.I32: {
temps = parentFunction.tempI32s || (parentFunction.tempI32s = []);
break;
}
case NativeType.I64: {
temps = parentFunction.tempI64s || (parentFunction.tempI64s = []);
break;
}
case NativeType.F32: {
temps = parentFunction.tempF32s || (parentFunction.tempF32s = []);
break;
}
case NativeType.F64: {
temps = parentFunction.tempF64s || (parentFunction.tempF64s = []);
break;
}
case NativeType.V128: {
temps = parentFunction.tempV128s || (parentFunction.tempV128s = []);
break;
}
case NativeType.Anyref: {
temps = parentFunction.tempAnyrefs || (parentFunction.tempAnyrefs = []);
break;
}
case NativeType.Exnref: {
temps = parentFunction.tempExnrefs || (parentFunction.tempExnrefs = []);
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 && scopedLocals.has(name)) return 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);
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 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 {
if (!this.scopedLocals) this.scopedLocals = new Map();
else {
let existingLocal = this.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
this.scopedLocals.set(name, scopedAlias);
return scopedAlias;
}
/** Tests if this flow has any scoped locals that must be free'd. */
get hasScopedLocals(): bool {
if (this.scopedLocals) {
for (let scopedLocal of this.scopedLocals.values()) {
if (scopedLocal.is(CommonFlags.SCOPED)) { // otherwise an alias
return true;
}
}
}
return false;
}
/** Frees this flow's scoped variables and returns its parent flow. */
freeScopedLocals(): void {
if (this.scopedLocals) {
for (let scopedLocal of this.scopedLocals.values()) {
if (scopedLocal.is(CommonFlags.SCOPED)) { // otherwise an alias
this.freeTempLocal(scopedLocal);
}
}
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;
var scope: Map<String,Local> | null;
do if ((scope = current.scopedLocals) && scope.has(name)) return scope.get(name)!;
while (current = current.parent);
return this.parentFunction.localsByName.get(name)!;
}
/** 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);
return parentFunction.breakLabel = id.toString(10);
}
/** 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(10);
} else {
parentFunction.breakLabel = null;
parentFunction.breakStack = null;
}
}
/** Inherits flags and local wrap states from the specified flow (e.g. blocks). */
inherit(other: Flow): void {
this.flags |= other.flags & (FlowFlags.ANY_CATEGORICAL | FlowFlags.ANY_CONDITIONAL);
this.localFlags = other.localFlags; // no need to slice because other flow is finished
}
/** Inherits categorical flags as conditional flags from the specified flow (e.g. then without else). */
inheritConditional(other: Flow): void {
this.set(other.flags & FlowFlags.ANY_CONDITIONAL);
if (other.is(FlowFlags.RETURNS)) {
this.set(FlowFlags.CONDITIONALLY_RETURNS);
}
if (other.is(FlowFlags.THROWS)) {
this.set(FlowFlags.CONDITIONALLY_THROWS);
}
if (other.is(FlowFlags.BREAKS) && other.breakLabel == this.breakLabel) {
this.set(FlowFlags.CONDITIONALLY_BREAKS);
}
if (other.is(FlowFlags.CONTINUES) && other.continueLabel == this.continueLabel) {
this.set(FlowFlags.CONDITIONALLY_CONTINUES);
}
if (other.is(FlowFlags.ALLOCATES)) {
this.set(FlowFlags.CONDITIONALLY_ALLOCATES);
}
var localFlags = other.localFlags;
for (let i = 0, k = localFlags.length; i < k; ++i) {
let flags = localFlags[i];
this.setLocalFlag(i, flags & LocalFlags.ANY_CONDITIONAL);
if (flags & LocalFlags.RETAINED) this.setLocalFlag(i, LocalFlags.CONDITIONALLY_RETAINED);
if (flags & LocalFlags.READFROM) this.setLocalFlag(i, LocalFlags.CONDITIONALLY_READFROM);
if (flags & LocalFlags.WRITTENTO) this.setLocalFlag(i, LocalFlags.CONDITIONALLY_WRITTENTO);
if (flags & LocalFlags.RETURNED) this.setLocalFlag(i, LocalFlags.CONDITIONALLY_RETURNED);
}
}
/** Inherits mutual flags and local wrap states from the specified flows (e.g. then with else). */
inheritMutual(left: Flow, right: Flow): void {
// categorical flags set in both arms
this.set(left.flags & right.flags & FlowFlags.ANY_CATEGORICAL);
// conditional flags set in any arm
this.set(left.flags & FlowFlags.ANY_CONDITIONAL);
this.set(right.flags & FlowFlags.ANY_CONDITIONAL);
// categorical flags in either arm as conditional
this.inheritConditional(left);
this.inheritConditional(right);
// categorical local flags set in both arms / conditional local flags set in at least one arm
var leftLocalFlags = left.localFlags;
var numLeftLocalFlags = leftLocalFlags.length;
var rightLocalFlags = right.localFlags;
var numRightLocalFlags = rightLocalFlags.length;
var combinedFlags = new Array<LocalFlags>(max<i32>(numLeftLocalFlags, numRightLocalFlags));
for (let i = 0; i < numLeftLocalFlags; ++i) {
combinedFlags[i] = LocalFlags.join(
unchecked(leftLocalFlags[i]),
i < numRightLocalFlags
? unchecked(rightLocalFlags[i])
: 0
);
}
for (let i = numLeftLocalFlags; i < numRightLocalFlags; ++i) {
combinedFlags[i] = LocalFlags.join(
0,
unchecked(rightLocalFlags[i])
);
}
this.localFlags = combinedFlags;
}
/** 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(expr: ExpressionRef): void {
// A: `expr` is true-ish -> Q: how did that happen?
switch (getExpressionId(expr)) {
case ExpressionId.LocalSet: {
if (!isLocalTee(expr)) break;
let local = this.parentFunction.localsByIndex[getLocalSetIndex(expr)];
this.setLocalFlag(local.index, LocalFlags.NONNULL);
this.inheritNonnullIfTrue(getLocalSetValue(expr)); // must have been true-ish as well
break;
}
case ExpressionId.LocalGet: {
let local = this.parentFunction.localsByIndex[getLocalGetIndex(expr)];
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));
this.inheritNonnullIfTrue(getIfTrue(expr));
}
}
break;
}
case ExpressionId.Unary: {
switch (getUnaryOp(expr)) {
case UnaryOp.EqzI32:
case UnaryOp.EqzI64: {
this.inheritNonnullIfFalse(getUnaryValue(expr)); // !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); // TRUE == right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI32(right) != 0) {
this.inheritNonnullIfTrue(left); // 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); // TRUE == right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && (getConstValueI64Low(right) != 0 && getConstValueI64High(right) != 0)) {
this.inheritNonnullIfTrue(left); // 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); // FALSE != right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI32(right) == 0) {
this.inheritNonnullIfTrue(left); // 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); // FALSE != right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI64Low(right) == 0 && getConstValueI64High(right) == 0) {
this.inheritNonnullIfTrue(left); // left != FALSE -> left must have been true
}
break;
}
}
break;
}
case ExpressionId.Call: {
let name = getCallTarget(expr);
let program = this.parentFunction.program;
switch (name) {
case program.retainInstance.internalName: {
this.inheritNonnullIfTrue(getCallOperand(expr, 0));
break;
}
}
break;
}
}
}
/** Updates local states to reflect that this branch is only taken when `expr` is false-ish. */
inheritNonnullIfFalse(expr: ExpressionRef): void {
// A: `expr` is false-ish -> Q: how did that happen?
switch (getExpressionId(expr)) {
case ExpressionId.Unary: {
switch (getUnaryOp(expr)) {
case UnaryOp.EqzI32:
case UnaryOp.EqzI64: {
this.inheritNonnullIfTrue(getUnaryValue(expr)); // !value -> value must have been true
break;
}
}
break;
}
case ExpressionId.If: {
let ifTrue = getIfTrue(expr);
if (getExpressionId(ifTrue) == ExpressionId.Const) {
let ifFalse = getIfFalse(expr);
if (!ifFalse) break;
// Logical OR: (if (condition 1 ifFalse))
// the only way this had become false is if condition and ifFalse are false
let exprType = getExpressionType(ifTrue);
if (
(exprType == NativeType.I32 && getConstValueI32(ifTrue) != 0) ||
(exprType == NativeType.I64 && (getConstValueI64Low(ifTrue) != 0 || getConstValueI64High(ifTrue) != 0))
) {
this.inheritNonnullIfFalse(getIfCondition(expr));
this.inheritNonnullIfFalse(getIfFalse(expr));
}
}
break;
}
case ExpressionId.Binary: {
switch (getBinaryOp(expr)) {
// remember: we want to know how the _entire_ expression became FALSE (!)
case BinaryOp.EqI32: {
let left = getBinaryLeft(expr);
let right = getBinaryRight(expr);
if (getExpressionId(left) == ExpressionId.Const && getConstValueI32(left) == 0) {
this.inheritNonnullIfTrue(right); // FALSE == right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI32(right) == 0) {
this.inheritNonnullIfTrue(left); // left == FALSE -> 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); // FALSE == right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI64Low(right) == 0 && getConstValueI64High(right) == 0) {
this.inheritNonnullIfTrue(left); // left == FALSE -> 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); // TRUE != right -> right must have been true
} else if (getExpressionId(right) == ExpressionId.Const && getConstValueI32(right) != 0) {
this.inheritNonnullIfTrue(left); // left != TRUE -> 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); // TRUE != right -> right must have been true for this to become false
} else if (getExpressionId(right) == ExpressionId.Const && (getConstValueI64Low(right) != 0 || getConstValueI64High(right) != 0)) {
this.inheritNonnullIfTrue(left); // left != TRUE -> left must have been true for this to become false
}
break;
}
}
break;
}
}
}
/**
* Tests if an expression can possibly overflow in the context of this flow. Assumes that the
* expression might already have overflown and returns `false` only if the operation neglects
* any possible combination of garbage bits being present.
*/
canOverflow(expr: ExpressionRef, type: Type): bool {
// TODO: the following catches most common and a few uncommon cases, but there are additional
// opportunities here, obviously.
assert(type != Type.void);
// types other than i8, u8, i16, u16 and bool do not overflow
if (!type.is(TypeFlags.SHORT | TypeFlags.INTEGER)) return false;
var operand: ExpressionRef;
switch (getExpressionId(expr)) {
// overflows if the local isn't wrapped or the conversion does
case ExpressionId.LocalGet: {
let local = this.parentFunction.localsByIndex[getLocalGetIndex(expr)];
return !this.isLocalFlag(local.index, LocalFlags.WRAPPED, true)
|| canConversionOverflow(local.type, type);
}
// overflows if the value does
case ExpressionId.LocalSet: { // tee
assert(isLocalTee(expr));
return this.canOverflow(getLocalSetValue(expr), type);
}
// overflows if the conversion does (globals are wrapped on set)
case ExpressionId.GlobalGet: {
// TODO: this is inefficient because it has to read a string
let global = assert(this.parentFunction.program.elementsByName.get(assert(getGlobalGetName(expr)))!);
assert(global.kind == ElementKind.GLOBAL);
return canConversionOverflow(assert((<Global>global).type), type);
}
case ExpressionId.Binary: {
switch (getBinaryOp(expr)) {
// comparisons do not overflow (result is 0 or 1)
case BinaryOp.EqI32:
case BinaryOp.EqI64:
case BinaryOp.EqF32:
case BinaryOp.EqF64:
case BinaryOp.NeI32:
case BinaryOp.NeI64:
case BinaryOp.NeF32:
case BinaryOp.NeF64:
case BinaryOp.LtI32:
case BinaryOp.LtU32:
case BinaryOp.LtI64:
case BinaryOp.LtU64:
case BinaryOp.LtF32:
case BinaryOp.LtF64:
case BinaryOp.LeI32:
case BinaryOp.LeU32:
case BinaryOp.LeI64:
case BinaryOp.LeU64:
case BinaryOp.LeF32:
case BinaryOp.LeF64:
case BinaryOp.GtI32:
case BinaryOp.GtU32:
case BinaryOp.GtI64:
case BinaryOp.GtU64:
case BinaryOp.GtF32:
case BinaryOp.GtF64:
case BinaryOp.GeI32:
case BinaryOp.GeU32:
case BinaryOp.GeI64:
case BinaryOp.GeU64:
case BinaryOp.GeF32:
case BinaryOp.GeF64: return false;
// result won't overflow if one side is 0 or if one side is 1 and the other wrapped
case BinaryOp.MulI32: {
return !(
(
getExpressionId(operand = getBinaryLeft(expr)) == ExpressionId.Const &&
(
getConstValueI32(operand) == 0 ||
(
getConstValueI32(operand) == 1 &&
!this.canOverflow(getBinaryRight(expr), type)
)
)
) || (
getExpressionId(operand = getBinaryRight(expr)) == ExpressionId.Const &&
(
getConstValueI32(operand) == 0 ||
(
getConstValueI32(operand) == 1 &&
!this.canOverflow(getBinaryLeft(expr), type)
)
)
)
);
}
// result won't overflow if one side is a constant less than this type's mask or one side
// is wrapped
case BinaryOp.AndI32: {
// note that computeSmallIntegerMask returns the mask minus the MSB for signed types
// because signed value garbage bits must be guaranteed to be equal to the MSB.
return !(
(
(
getExpressionId(operand = getBinaryLeft(expr)) == ExpressionId.Const &&
getConstValueI32(operand) <= type.computeSmallIntegerMask(Type.i32)
) || !this.canOverflow(operand, type)
) || (
(
getExpressionId(operand = getBinaryRight(expr)) == ExpressionId.Const &&
getConstValueI32(operand) <= type.computeSmallIntegerMask(Type.i32)
) || !this.canOverflow(operand, type)
)
);
}
// overflows if the shift doesn't clear potential garbage bits
case BinaryOp.ShlI32: {
let shift = 32 - type.size;
return getExpressionId(operand = getBinaryRight(expr)) != ExpressionId.Const
|| getConstValueI32(operand) < shift;
}
// overflows if the value does and the shift doesn't clear potential garbage bits
case BinaryOp.ShrI32: {
let shift = 32 - type.size;
return this.canOverflow(getBinaryLeft(expr), type) && (
getExpressionId(operand = getBinaryRight(expr)) != ExpressionId.Const ||
getConstValueI32(operand) < shift
);
}
// overflows if the shift does not clear potential garbage bits. if an unsigned value is
// wrapped, it can't overflow.
case BinaryOp.ShrU32: {
let shift = 32 - type.size;
return type.is(TypeFlags.SIGNED)
? !(
getExpressionId(operand = getBinaryRight(expr)) == ExpressionId.Const &&
getConstValueI32(operand) > shift // must clear MSB
)
: this.canOverflow(getBinaryLeft(expr), type) && !(
getExpressionId(operand = getBinaryRight(expr)) == ExpressionId.Const &&
getConstValueI32(operand) >= shift // can leave MSB
);
}
// overflows if any side does