forked from AssemblyScript/assemblyscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflow.ts
1477 lines (1347 loc) · 53.7 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 {
Program,
Local,
Function,
Element,
ElementKind,
Class,
TypedElement,
mangleInternalName,
Property,
PropertyPrototype,
TypeDefinition
} from "./program";
import {
TypeRef,
ExpressionId,
ExpressionRef,
BinaryOp,
UnaryOp,
getExpressionId,
getLocalGetIndex,
isLocalTee,
getLocalSetValue,
getGlobalGetName,
getBinaryOp,
getBinaryLeft,
getConstValueI32,
getBinaryRight,
getUnaryOp,
getExpressionType,
getConstValueI64Low,
getConstValueF32,
getConstValueF64,
getLoadBytes,
isLoadSigned,
getBlockName,
getBlockChildCount,
getBlockChildAt,
getIfTrue,
getIfFalse,
getSelectThen,
getSelectElse,
getCallTarget,
getLocalSetIndex,
getIfCondition,
getUnaryValue,
getCallOperandAt,
getCallOperandCount,
isConstZero,
isConstNonZero
} from "./module";
import {
CommonFlags
} from "./common";
import {
UncheckedBehavior
} from "./compiler";
import {
DiagnosticCode
} from "./diagnostics";
import {
Node
} from "./ast";
import {
cloneMap
} from "./util";
import {
BuiltinNames
} from "./builtins";
/** 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. */
ReturnsWrapped = 1 << 1,
/** This flow always returns a non-null value. */
ReturnsNonNull = 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. */
AccessesThis = 1 << 6,
/** This flow always calls `super`. Constructors only. */
CallsSuper = 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. */
ConditionallyReturns = 1 << 9,
/** This flow conditionally throws in a child flow. */
ConditionallyThrows = 1 << 10,
/** This flow conditionally breaks in a child flow. */
ConditionallyBreaks = 1 << 11,
/** This flow conditionally continues in a child flow. */
ConditionallyContinues = 1 << 12,
/** This flow conditionally accesses `this` in a child flow. Constructors only. */
ConditionallyAccessesThis = 1 << 13,
/** This flow may return a non-this value. Constructors only. */
MayReturnNonThis = 1 << 14,
// other
/** This is a flow with explicitly disabled bounds checking. */
UncheckedContext = 1 << 15,
/** This is a flow compiling a constructor parameter. */
CtorParamContext = 1 << 16,
// masks
/** Any categorical flag. */
AnyCategorical = FlowFlags.Returns
| FlowFlags.ReturnsWrapped
| FlowFlags.ReturnsNonNull
| FlowFlags.Throws
| FlowFlags.Breaks
| FlowFlags.Continues
| FlowFlags.AccessesThis
| FlowFlags.CallsSuper
| FlowFlags.Terminates,
/** Any conditional flag. */
AnyConditional = FlowFlags.ConditionallyReturns
| FlowFlags.ConditionallyThrows
| FlowFlags.ConditionallyBreaks
| FlowFlags.ConditionallyContinues
| FlowFlags.ConditionallyAccessesThis
}
/** Flags indicating the current state of a local. */
export const 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
}
/** Flags indicating the current state of a field. */
export const enum FieldFlags {
None = 0,
Initialized = 1 << 0
}
/** 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 default top-level flow of the specified function. */
static createDefault(targetFunction: Function): Flow {
let flow = new Flow(targetFunction);
if (targetFunction.is(CommonFlags.Constructor)) {
flow.initThisFieldFlags();
}
if (targetFunction.program.options.uncheckedBehavior === UncheckedBehavior.Always) {
flow.set(FlowFlags.UncheckedContext);
}
return flow;
}
/** Creates an inline flow, compiling `inlineFunction` into `targetFunction`. */
static createInline(targetFunction: Function, inlineFunction: Function): Flow {
// Note that `targetFunction` and `inlineFunction` can be the same function
// when it is inlined into itself.
let flow = new Flow(targetFunction, inlineFunction);
flow.inlineReturnLabel = `${inlineFunction.internalName}|inlined.${(inlineFunction.nextInlineId++)}`;
if (inlineFunction.is(CommonFlags.Constructor)) {
flow.initThisFieldFlags();
}
if (targetFunction.program.options.uncheckedBehavior === UncheckedBehavior.Always) {
flow.set(FlowFlags.UncheckedContext);
}
return flow;
}
private constructor(
/** Target function this flow generates code into. */
public targetFunction: Function,
/** Inline function this flow generates code from, if any. */
public inlineFunction: Function | null = null
) {
// Setup is performed above so inline ids and field flags are not reset
// when forking flows, which also uses the constructor.
}
/** Parent flow. */
parent: Flow | null = null;
/** Outer flow. Only relevant for first-class functions. */
outer: 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;
/** Scoped type alias. */
scopedTypeAlias: Map<string,TypeDefinition> | null = null;
/** Local flags. */
localFlags: LocalFlags[] = [];
/** Field flags on `this`. Constructors only. */
thisFieldFlags: Map<Property,FieldFlags> | null = null;
/** The label we break to when encountering a return statement, when inlining. */
inlineReturnLabel: string | null = null;
/** Alternative flows if a compound expression is true-ish. */
trueFlows: Map<ExpressionRef,Flow> | null = null;
/** Alternative flows if a compound expression is false-ish. */
falseFlows: Map<ExpressionRef,Flow> | null = null;
/** Tests if this is an inline flow. */
get isInline(): bool {
return this.inlineFunction != null;
}
/** Gets the source function being compiled. Differs from target when inlining. */
get sourceFunction(): Function {
// Obtaining the source function is useful when resolving elements relative
// to their source location. Note that the source function does not necessarily
// materialize in the binary, as it might be inlined. Code, locals, etc. must
// always be added to / maintained in the materializing target function instead.
let inlineFunction = this.inlineFunction;
if (inlineFunction) return inlineFunction;
return this.targetFunction;
}
/** Gets the program this flow belongs to. */
get program(): Program {
return this.targetFunction.program;
}
/** Gets the current return type. */
get returnType(): Type {
return this.sourceFunction.signature.returnType;
}
/** Gets the current contextual type arguments. */
get contextualTypeArguments(): Map<string,Type> | null {
return this.sourceFunction.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; }
deriveConditionalFlags(): FlowFlags {
let condiFlags = this.flags & FlowFlags.AnyConditional;
if (this.is(FlowFlags.Returns)) {
condiFlags |= FlowFlags.ConditionallyReturns;
}
if (this.is(FlowFlags.Throws)) {
condiFlags |= FlowFlags.ConditionallyThrows;
}
if (this.is(FlowFlags.Breaks)) {
condiFlags |= FlowFlags.ConditionallyBreaks;
}
if (this.is(FlowFlags.Continues)) {
condiFlags |= FlowFlags.ConditionallyContinues;
}
if (this.is(FlowFlags.AccessesThis)) {
condiFlags |= FlowFlags.ConditionallyAccessesThis;
}
return condiFlags;
}
/** Forks this flow to a child flow. */
fork(
/** Whether a new break context is established, e.g. by a block. */
newBreakContext: bool = false,
/** Whether a new continue context is established, e.g. by a loop. */
newContinueContext: bool = newBreakContext
): Flow {
let branch = new Flow(this.targetFunction, this.inlineFunction);
branch.parent = this;
branch.flags = this.flags;
branch.outer = this.outer;
if (newBreakContext) {
branch.flags &= ~(
FlowFlags.Breaks |
FlowFlags.ConditionallyBreaks
);
} else {
branch.breakLabel = this.breakLabel;
}
if (newContinueContext) {
branch.flags &= ~(
FlowFlags.Continues |
FlowFlags.ConditionallyContinues
);
} else {
branch.continueLabel = this.continueLabel;
}
branch.localFlags = this.localFlags.slice();
if (this.sourceFunction.is(CommonFlags.Constructor)) {
let thisFieldFlags = assert(this.thisFieldFlags);
branch.thisFieldFlags = cloneMap(thisFieldFlags);
} else {
assert(!this.thisFieldFlags);
}
branch.inlineReturnLabel = this.inlineReturnLabel;
return branch;
}
/** Forks this flow to a child flow where `condExpr` is true-ish. */
forkThen(
/** Condition that turned out to be true. */
condExpr: ExpressionRef,
/** Whether a new break context is established, e.g. by a block. */
newBreakContext: bool = false,
/** Whether a new continue context is established, e.g. by a loop. */
newContinueContext: bool = newBreakContext
): Flow {
let flow = this.fork(newBreakContext, newContinueContext);
let trueFlows = this.trueFlows;
if (trueFlows && trueFlows.has(condExpr)) {
flow.inherit(changetype<Flow>(trueFlows.get(condExpr)));
}
flow.inheritNonnullIfTrue(condExpr);
return flow;
}
/** Remembers the alternative flow if `condExpr` turns out `true`. */
noteThen(condExpr: ExpressionRef, trueFlow: Flow): void {
let trueFlows = this.trueFlows;
if (!trueFlows) this.trueFlows = trueFlows = new Map();
trueFlows.set(condExpr, trueFlow);
}
/** Forks this flow to a child flow where `condExpr` is false-ish. */
forkElse(
/** Condition that turned out to be false. */
condExpr: ExpressionRef
): Flow {
let flow = this.fork();
let falseFlows = this.falseFlows;
if (falseFlows && falseFlows.has(condExpr)) {
flow.inherit(changetype<Flow>(falseFlows.get(condExpr)));
}
flow.inheritNonnullIfFalse(condExpr);
return flow;
}
/** Remembers the alternative flow if `condExpr` turns out `false`. */
noteElse(condExpr: ExpressionRef, falseFlow: Flow): void {
let falseFlows = this.falseFlows;
if (!falseFlows) this.falseFlows = falseFlows = new Map();
falseFlows.set(condExpr, falseFlow);
}
addScopedTypeAlias(name: string, definition: TypeDefinition): void {
let scopedTypeAlias = this.scopedTypeAlias;
if (!scopedTypeAlias) this.scopedTypeAlias = scopedTypeAlias = new Map();
scopedTypeAlias.set(name, definition);
}
lookupScopedTypeAlias(name: string): TypeDefinition | null {
let current: Flow | null = this;
do {
let scopedTypeAlias = current.scopedTypeAlias;
if (scopedTypeAlias && scopedTypeAlias.has(name)) {
return assert(scopedTypeAlias.get(name));
}
current = current.parent;
} while (current);
return null;
}
lookupTypeAlias(name: string): TypeDefinition | null {
let definition: TypeDefinition | null = null;
if (definition = this.lookupScopedTypeAlias(name)) return definition;
let sourceParent = this.sourceFunction.parent;
if (sourceParent.kind == ElementKind.Function) {
// lookup parent function.
let parentFunction = <Function>sourceParent;
return parentFunction.flow.lookupTypeAlias(name);
}
return null;
}
/** Gets a free temporary local of the specified type. */
getTempLocal(type: Type): Local {
let local = this.targetFunction.addLocal(type);
this.unsetLocalFlag(local.index, ~0);
return local;
}
/** Gets the scoped local of the specified name. */
getScopedLocal(name: string): Local | null {
let scopedLocals = this.scopedLocals;
if (scopedLocals && scopedLocals.has(name)) return assert(scopedLocals.get(name));
return null;
}
/** Adds a new scoped local of the specified name. */
addScopedLocal(name: string, type: Type): Local {
let scopedLocal = this.getTempLocal(type);
scopedLocal.name = name;
scopedLocal.internalName = mangleInternalName(name, scopedLocal.parent, false);
let 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, declarationNode: Node): Local {
let scopedDummy = new Local(name, -1, type, this.targetFunction);
let scopedLocals = this.scopedLocals;
if (!scopedLocals) this.scopedLocals = scopedLocals = new Map();
else if (scopedLocals.has(name)) {
this.program.error(
DiagnosticCode.Cannot_redeclare_block_scoped_variable_0,
declarationNode.range, 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 {
let scopedLocals = this.scopedLocals;
if (!scopedLocals) {
this.scopedLocals = scopedLocals = new Map();
} else if (scopedLocals.has(name)) {
let existingLocal = assert(scopedLocals.get(name));
if (reportNode) {
if (!existingLocal.declaration.range.source.isNative) {
this.program.errorRelated(
DiagnosticCode.Duplicate_identifier_0,
reportNode.range,
existingLocal.declaration.name.range,
name
);
} else {
this.program.error(
DiagnosticCode.Duplicate_identifier_0,
reportNode.range, name
);
}
}
return existingLocal;
}
assert(index < this.targetFunction.localsByIndex.length);
let scopedAlias = new Local(name, index, type, this.targetFunction);
scopedAlias.set(CommonFlags.Scoped);
scopedLocals.set(name, scopedAlias);
return scopedAlias;
}
/** Frees a single scoped local by its name. */
freeScopedDummyLocal(name: string): void {
let scopedLocals = assert(this.scopedLocals);
assert(scopedLocals.has(name));
let local = assert(scopedLocals.get(name));
assert(local.index == -1);
scopedLocals.delete(name);
}
/** Looks up the local of the specified name in the current scope. */
lookupLocal(name: string): Local | null {
let current: Flow | null = this;
do {
let scope = current.scopedLocals;
if (scope && scope.has(name)) return assert(scope.get(name));
current = current.parent;
} while (current);
return null;
}
/** Looks up the element with the specified name relative to the scope of this flow. */
lookup(name: string): Element | null {
let element = this.lookupLocal(name);
if (element) return element;
return this.sourceFunction.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;
let 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;
let 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;
let localFlags = this.localFlags;
let 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;
let localFlags = this.localFlags;
let flags = index < localFlags.length ? unchecked(localFlags[index]) : 0;
localFlags[index] = flags & ~flag;
}
/** Initializes `this` field flags. */
initThisFieldFlags(): void {
let sourceFunction = this.sourceFunction;
assert(sourceFunction.is(CommonFlags.Constructor));
let parent = sourceFunction.parent;
assert(parent.kind == ElementKind.Class);
let classInstance = <Class>parent;
this.thisFieldFlags = new Map();
let members = classInstance.members;
if (members) {
for (let _values = Map_values(members), i = 0, k = _values.length; i < k; ++i) {
let member = _values[i];
if (member.kind != ElementKind.PropertyPrototype) continue;
// only interested in fields (resolved during class finalization)
let property = (<PropertyPrototype>member).instance;
if (!property || !property.isField) continue;
if (
// guaranteed by super
property.prototype.parent != classInstance ||
// has field initializer
property.initializerNode ||
// is initialized as a ctor parameter
property.prototype.parameterIndex != -1 ||
// is safe to initialize with zero
property.type.isAny(TypeFlags.Value | TypeFlags.Nullable)
) {
this.setThisFieldFlag(property, FieldFlags.Initialized);
}
}
}
}
/** Tests if the specified `this` field has the specified flag or flags. */
isThisFieldFlag(field: Property, flag: FieldFlags): bool {
let fieldFlags = this.thisFieldFlags;
if (fieldFlags != null && fieldFlags.has(field)) {
return (changetype<FieldFlags>(fieldFlags.get(field)) & flag) == flag;
}
return false;
}
/** Sets the specified flag or flags on the given `this` field. */
setThisFieldFlag(field: Property, flag: FieldFlags): void {
let fieldFlags = this.thisFieldFlags;
if (fieldFlags) {
assert(this.sourceFunction.is(CommonFlags.Constructor));
if (fieldFlags.has(field)) {
let flags = changetype<FieldFlags>(fieldFlags.get(field));
fieldFlags.set(field, flags | flag);
} else {
fieldFlags.set(field, flag);
}
} else {
assert(!this.sourceFunction.is(CommonFlags.Constructor));
}
}
/** Pushes a new control flow label, for example when entering a loop that one can `break` from. */
pushControlFlowLabel(): i32 {
let targetFunction = this.targetFunction;
let id = targetFunction.nextBreakId++;
let stack = targetFunction.breakStack;
if (!stack) targetFunction.breakStack = [ id ];
else stack.push(id);
return id;
}
/** Pops the most recent control flow label and validates that it matches. */
popControlFlowLabel(expectedLabel: i32): void {
let targetFunction = this.targetFunction;
let stack = assert(targetFunction.breakStack); // should exist
assert(stack.length); // should not be empty
assert(stack.pop() == expectedLabel); // should match
}
/** Inherits flags of another flow into this one, i.e. a finished inner block. */
inherit(other: Flow): void {
assert(other.targetFunction == this.targetFunction);
let otherFlags = other.flags;
// respective inner flags are irrelevant if contexts differ
if (this.breakLabel != other.breakLabel) {
if (otherFlags & (FlowFlags.Breaks | FlowFlags.ConditionallyBreaks)) {
otherFlags &= ~FlowFlags.Terminates;
}
otherFlags &= ~(FlowFlags.Breaks | FlowFlags.ConditionallyBreaks);
}
if (this.continueLabel != other.continueLabel) {
otherFlags &= ~(FlowFlags.Continues | FlowFlags.ConditionallyContinues);
}
this.flags = this.flags | otherFlags; // what happens before is still true
this.localFlags = other.localFlags;
this.thisFieldFlags = other.thisFieldFlags;
}
/** Merges only the side effects of a branch, i.e. when not taken. */
mergeSideEffects(other: Flow): void {
assert(other.targetFunction == this.targetFunction);
let thisFlags = this.flags;
let otherFlags = other.flags;
let newFlags = FlowFlags.None;
if (thisFlags & FlowFlags.Returns) { // nothing can change that
newFlags |= FlowFlags.Returns;
} else if (otherFlags & FlowFlags.Returns) {
newFlags |= FlowFlags.ConditionallyReturns;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.ConditionallyReturns;
}
// must be the case in both
newFlags |= thisFlags & otherFlags & FlowFlags.ReturnsWrapped;
newFlags |= thisFlags & otherFlags & FlowFlags.ReturnsNonNull;
if (thisFlags & FlowFlags.Throws) { // nothing can change that
newFlags |= FlowFlags.Throws;
} else if (otherFlags & FlowFlags.Throws) {
newFlags |= FlowFlags.ConditionallyThrows;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.ConditionallyThrows;
}
if (thisFlags & FlowFlags.Breaks) { // nothing can change that
newFlags |= FlowFlags.Breaks;
} else if (other.breakLabel == this.breakLabel) {
if (otherFlags & FlowFlags.Breaks) {
newFlags |= FlowFlags.ConditionallyBreaks;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.ConditionallyBreaks;
}
} else {
newFlags |= thisFlags & FlowFlags.ConditionallyBreaks;
}
if (thisFlags & FlowFlags.Continues) { // nothing can change that
newFlags |= FlowFlags.Continues;
} else if (other.continueLabel == this.continueLabel) {
if (otherFlags & FlowFlags.Continues) {
newFlags |= FlowFlags.ConditionallyContinues;
} else {
newFlags |= (thisFlags | otherFlags) & FlowFlags.ConditionallyContinues;
}
} else {
newFlags |= thisFlags & FlowFlags.ConditionallyContinues;
}
if (thisFlags & FlowFlags.AccessesThis) { // can become conditional
if (otherFlags & FlowFlags.AccessesThis) {
newFlags |= FlowFlags.AccessesThis;
} else {
newFlags |= FlowFlags.ConditionallyAccessesThis;
}
} else if (otherFlags & FlowFlags.AccessesThis) {
newFlags |= FlowFlags.ConditionallyAccessesThis;
}
// may be the case in any
newFlags |= (thisFlags | otherFlags) & FlowFlags.MayReturnNonThis;
// must be the case in both
newFlags |= thisFlags & otherFlags & FlowFlags.CallsSuper;
if (thisFlags & FlowFlags.Terminates) { // nothing can change that
newFlags |= FlowFlags.Terminates;
}
this.flags = newFlags | (thisFlags & (FlowFlags.UncheckedContext | FlowFlags.CtorParamContext));
}
/** Merges a branch joining again with this flow, i.e. then without else. */
mergeBranch(other: Flow): void {
this.mergeSideEffects(other);
// Local flags matter if the branch does not terminate
let thisLocalFlags = this.localFlags;
let numThisLocalFlags = thisLocalFlags.length;
let otherLocalFlags = other.localFlags;
let numOtherLocalFlags = otherLocalFlags.length;
let 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;
thisLocalFlags[i] = thisFlags & otherFlags & (
LocalFlags.Constant |
LocalFlags.Wrapped |
LocalFlags.NonNull |
LocalFlags.Initialized
);
}
// field flags do not matter here since there's only INITIALIZED, which can
// only be set if it has been observed prior to entering the branch.
}
/** Inherits two alternate branches to become this flow, i.e. then with else. */
inheritAlternatives(left: Flow, right: Flow): void {
assert(left.targetFunction == right.targetFunction);
assert(left.targetFunction == this.targetFunction);
// Differs from `mergeBranch` in that the alternatives are intersected to
// then become this branch.
let leftFlags = left.flags;
let rightFlags = right.flags;
let newFlags = FlowFlags.None;
if (leftFlags & FlowFlags.Returns) {
if (rightFlags & FlowFlags.Returns) {
newFlags |= FlowFlags.Returns;
} else {
newFlags |= FlowFlags.ConditionallyReturns;
}
} else if (rightFlags & FlowFlags.Returns) {
newFlags |= FlowFlags.ConditionallyReturns;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.ConditionallyReturns;
}
if ((leftFlags & FlowFlags.ReturnsWrapped) && (rightFlags & FlowFlags.ReturnsWrapped)) {
newFlags |= FlowFlags.ReturnsWrapped;
}
if ((leftFlags & FlowFlags.ReturnsNonNull) && (rightFlags & FlowFlags.ReturnsNonNull)) {
newFlags |= FlowFlags.ReturnsNonNull;
}
if (leftFlags & FlowFlags.Throws) {
if (rightFlags & FlowFlags.Throws) {
newFlags |= FlowFlags.Throws;
} else {
newFlags |= FlowFlags.ConditionallyThrows;
}
} else if (rightFlags & FlowFlags.Throws) {
newFlags |= FlowFlags.ConditionallyThrows;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.ConditionallyThrows;
}
if (leftFlags & FlowFlags.Breaks) {
if (rightFlags & FlowFlags.Breaks) {
newFlags |= FlowFlags.Breaks;
} else {
newFlags |= FlowFlags.ConditionallyBreaks;
}
} else if (rightFlags & FlowFlags.Breaks) {
newFlags |= FlowFlags.ConditionallyBreaks;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.ConditionallyBreaks;
}
if (leftFlags & FlowFlags.Continues) {
if (rightFlags & FlowFlags.Continues) {
newFlags |= FlowFlags.Continues;
} else {
newFlags |= FlowFlags.ConditionallyContinues;
}
} else if (rightFlags & FlowFlags.Continues) {
newFlags |= FlowFlags.ConditionallyContinues;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.ConditionallyContinues;
}
if (leftFlags & FlowFlags.AccessesThis) {
if (rightFlags & FlowFlags.AccessesThis) {
newFlags |= FlowFlags.AccessesThis;
} else {
newFlags |= FlowFlags.ConditionallyAccessesThis;
}
} else if (rightFlags & FlowFlags.AccessesThis) {
newFlags |= FlowFlags.ConditionallyAccessesThis;
} else {
newFlags |= (leftFlags | rightFlags) & FlowFlags.ConditionallyAccessesThis;
}
newFlags |= (leftFlags | rightFlags) & FlowFlags.MayReturnNonThis;
if ((leftFlags & FlowFlags.CallsSuper) && (rightFlags & FlowFlags.CallsSuper)) {
newFlags |= FlowFlags.CallsSuper;
}
if ((leftFlags & FlowFlags.Terminates) && (rightFlags & FlowFlags.Terminates)) {
newFlags |= FlowFlags.Terminates;
}
this.flags = newFlags | (this.flags & (FlowFlags.UncheckedContext | FlowFlags.CtorParamContext));
// local flags
let 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;
thisLocalFlags[i] = leftFlags & rightFlags & (
LocalFlags.Constant |
LocalFlags.Wrapped |
LocalFlags.NonNull |
LocalFlags.Initialized
);
}
}
// field flags (currently only INITIALIZED, so can simplify)
let leftFieldFlags = left.thisFieldFlags;
if (leftFieldFlags) {
let newFieldFlags = new Map<Property,FieldFlags>();
let rightFieldFlags = assert(right.thisFieldFlags);
for (let _keys = Map_keys(leftFieldFlags), i = 0, k = _keys.length; i < k; ++i) {
let key = _keys[i];
let leftFlags = changetype<FieldFlags>(leftFieldFlags.get(key));
if (
(leftFlags & FieldFlags.Initialized) != 0 && rightFieldFlags.has(key) &&
(changetype<FieldFlags>(rightFieldFlags.get(key)) & FieldFlags.Initialized)
) {
newFieldFlags.set(key, FieldFlags.Initialized);
}
}
this.thisFieldFlags = newFieldFlags;
} else {
assert(!right.thisFieldFlags);
}
}
/** Tests if recompilation is needed due to incompatible local flags between loops, and resets if necessary. */
resetIfNeedsRecompile(
/** Resulting flow of the current compilation attempt. */
other: Flow,
/** Number of locals before the compilation attempt. */
numLocalsBefore: i32
): bool {
let numThisLocalFlags = this.localFlags.length;
let numOtherLocalFlags = other.localFlags.length;
let targetFunction = this.targetFunction;
assert(targetFunction == other.targetFunction);
let localsByIndex = targetFunction.localsByIndex;
assert(localsByIndex == other.targetFunction.localsByIndex);
let needsRecompile = false;
for (let i = 0, k = min<i32>(numThisLocalFlags, numOtherLocalFlags); i < k; ++i) {
let local = localsByIndex[i];
let type = local.type;
if (type.isShortIntegerValue) {
if (this.isLocalFlag(i, LocalFlags.Wrapped) && !other.isLocalFlag(i, LocalFlags.Wrapped)) {
this.unsetLocalFlag(i, LocalFlags.Wrapped); // assume not wrapped
needsRecompile = true;
}
}
if (type.isNullableReference) {
if (this.isLocalFlag(i, LocalFlags.NonNull) && !other.isLocalFlag(i, LocalFlags.NonNull)) {
this.unsetLocalFlag(i, LocalFlags.NonNull); // assume possibly null
needsRecompile = true;
}
}
}
if (needsRecompile) {
// Reset function locals to state before the compilation attempt
assert(localsByIndex.length >= numLocalsBefore);
localsByIndex.length = numLocalsBefore;
if (this.localFlags.length > numLocalsBefore) {
this.localFlags.length = numLocalsBefore;
}
}
return needsRecompile;
}
/** 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.isNullableReference) 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.targetFunction.localsByIndex[getLocalSetIndex(expr)];
return !local.type.isNullableReference || this.isLocalFlag(local.index, LocalFlags.NonNull, false);
}
case ExpressionId.LocalGet: {
let local = this.targetFunction.localsByIndex[getLocalGetIndex(expr)];
return !local.type.isNullableReference || 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. */
private 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.targetFunction.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