forked from ballerina-platform/nballerina
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpr.bal
2159 lines (2004 loc) · 92 KB
/
expr.bal
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
import wso2/nballerina.bir;
import wso2/nballerina.types as t;
import wso2/nballerina.front.syntax as s;
import wso2/nballerina.comm.err;
import wso2/nballerina.comm.diagnostic as d;
type CodeGenError err:Semantic|err:Unimplemented;
// When doing codeGen for an expression we need to determine
// 1. when it has singleton type
// 2. when it is const (i.e. OK on the RHS of a const definition)
// Usually 1 and 2 go together, but sometimes they don't. Specifically:
// - when the type of variable has been narrowed to singleton float zero (by `== 0f`), we do not know whether its value is +0f or -0f
// (i.e. this is a case where it is singleton but not const)
// (this applies even more in case of decimal precision)
// - the type of an === expression is boolean, even if the operands have singleton type
// (i.e. this is a case when it is const but not singleton)
// These two cases can lead to cascading effects in expressions that contain them
// (particularly numeric casts extend what can be affected by this).
// In the future conditional expressions will extend it even further.
type ExprEffect record {|
bir:BasicBlock block;
bir:Operand result;
// This is non-nil when the expression is a variable reference.
Binding? binding = ();
|};
type DeclBinding record {|
string name;
bir:DeclRegister reg;
boolean isFinal;
boolean used = false;
|};
type NarrowBinding record {|
string name;
bir:NarrowRegister reg;
DeclBinding unnarrowed;
|};
type AssignmentBinding record {|
string name;
bir:DeclRegister|bir:CapturedRegister reg; // same as unnarrowed.reg and invalidates.underlying.underling...
DeclBinding unnarrowed;
bir:NarrowRegister invalidates;
Position pos;
|};
type FunctionMarker "func"; // value is chosen such that it fits in a small string
type OccurrenceBinding NarrowBinding|AssignmentBinding;
type Binding DeclBinding|NarrowBinding|AssignmentBinding;
type BindingChain record {|
Binding|FunctionMarker head;
BindingChain? prev;
|};
// Linked list of incoming branches to a TypeMerger
type TypeMergerOrigin record {|
TypeMergerOrigin? prev;
bir:Label label;
BindingChain? bindings;
|};
// A partially constructed potential TypeMergeInsn
type TypeMerger record {|
TypeMergerOrigin? origins = ();
bir:BasicBlock dest;
|};
type TypeMergerPair record {|
TypeMerger? trueMerger = ();
TypeMerger? falseMerger = ();
|};
// At least one TypeMerger is non-nil
type CondExprEffect TypeMergerPair;
// One and only one TypeMerger is non-nil
type PrevTypeMergers TypeMergerPair;
type BooleanExprEffect record {|
*ExprEffect;
bir:BooleanOperand result;
|};
type IntExprEffect record {|
*ExprEffect;
bir:IntOperand result;
|};
type StringExprEffect record {|
*ExprEffect;
bir:StringOperand result;
|};
type RegExprEffect record {|
*ExprEffect;
bir:Register result;
|};
type CalledFunctionInfo record {|
t:FunctionSignature? signature;
bir:FunctionOperand operand;
|};
class ExprContext {
*ClosureContext;
final StmtContext? sc;
final ModuleSymbols mod;
final s:ModuleLevelDefn defn;
final BindingChain? bindings;
final s:SourceFile file;
final bir:FunctionCode code;
function init(ModuleSymbols mod, s:ModuleLevelDefn defn, bir:FunctionCode code, BindingChain? bindings, StmtContext? sc) {
self.mod = mod;
self.bindings = bindings;
self.defn = defn;
self.file = defn.part.file;
self.sc = sc;
self.code = code;
}
function isClosure() returns boolean {
StmtContext? sc = self.sc;
return sc == () ? false : sc.isClosure();
}
public function semanticErr(d:Message msg, Position|Range pos, error? cause = ()) returns err:Semantic {
return err:semantic(msg, loc=self.location(pos), cause=cause, defnName=self.defn.name);
}
function unimplementedErr(d:Message msg, Position|Range pos, error? cause = ()) returns err:Unimplemented {
return err:unimplemented(msg, loc=self.location(pos), cause=cause, defnName=self.defn.name);
}
private function location(Position|Range pos) returns d:Location {
return d:location(self.file, pos);
}
function qNameRange(Position startPos) returns Range {
return self.file.qNameRange(startPos);
}
function resolveTypeDesc(s:TypeDesc td) returns t:SemType|ResolveTypeError {
return resolveSubsetTypeDesc(self.mod, self.defn, td);
}
function createTmpRegister(bir:SemType t, Position? pos = ()) returns bir:TmpRegister {
return bir:createTmpRegister(self.code, t, pos);
}
function createAssignTmpRegister(bir:SemType t, Position? pos = ()) returns bir:AssignTmpRegister {
return bir:createAssignTmpRegister(self.code, t, pos);
}
function captureOperand(bir:CapturableRegister capturedReg) returns bir:CapturableRegister {
// NOTE: this is used when creating bir:CaptureInsn (ie. from the parent function).
// we need to check if the register captured by the child is in this function
// if not we need to capture that register as well
if self.registerInCurrentFunction(capturedReg) {
if capturedReg is bir:DeclRegister {
self.stmtContext().markAsCaptured(capturedReg);
}
return capturedReg;
}
return self.getCaptureRegister(capturedReg.semType, capturedReg);
}
function markAsDirectRef(bir:VarRegister register) {
self.stmtContext().markAsDirectRef(register);
}
function markCaptureInsn() {
self.stmtContext().markCaptureInsn();
}
function isCaptured(bir:DeclRegister register) returns boolean {
return self.stmtContext().isCaptured(register);
}
private function registerInCurrentFunction(bir:Register reg) returns boolean {
return reg.number < self.code.registers.length() && self.code.registers[reg.number] === reg;
}
function createNarrowRegister(bir:SemType t, bir:Register underlying, Position? pos = ()) returns bir:NarrowRegister {
return bir:createNarrowRegister(self.code, t, underlying, pos);
}
function getCaptureRegister(bir:SemType t, bir:CapturableRegister underlying, Position? pos = ()) returns bir:CapturedRegister {
return self.stmtContext().getCaptureRegister(t, underlying, pos);
}
function createBasicBlock(string? name = ()) returns bir:BasicBlock {
return bir:createBasicBlock(self.code, name);
}
function createDummyBasicBlock(bir:BasicBlock bb) returns bir:BasicBlock {
return bb === constBasicBlock ? bb : self.createBasicBlock();
}
function discardBasicBlocksFromDummy(bir:BasicBlock dummy) {
// JBUG #34944 can't use `is readonly`
if dummy !== constBasicBlock {
bir:discardBasicBlocksFrom(self.code, dummy);
}
}
function stmtContext() returns StmtContext {
return <StmtContext>self.sc;
}
function lookupLocalVarRef(string varName, Position pos) returns t:SingleValue|BindingLookupResult|bir:FunctionRef|CodeGenError {
return check lookupLocalVarRef(self, self.mod, varName, self.bindings, pos);
}
function notInConst(s:Expr expr) returns CodeGenError? {
if self.sc == () {
return self.semanticErr("expression is not constant", s:range(expr));
}
}
function exprContext(BindingChain? bindings) returns ExprContext {
return new(self.mod, self.defn, self.code, bindings, self.sc);
}
}
function codeGenExprForBoolean(ExprContext cx, bir:BasicBlock bb, s:Expr expr) returns CodeGenError|BooleanExprEffect {
var { result, block } = check codeGenExpr(cx, bb, t:BOOLEAN, expr);
if result is bir:BooleanConstOperand || (result is bir:Register && t:isSubtypeSimple(result.semType, t:BOOLEAN)) {
return { result, block };
}
return cx.semanticErr("expected boolean operand", s:range(expr));
}
function codeGenExprForInt(ExprContext cx, bir:BasicBlock bb, s:Expr expr) returns CodeGenError|IntExprEffect {
var { result, block } = check codeGenExpr(cx, bb, t:INT, expr);
return { result: check validIntOperand(cx, result, expr), block };
}
function codeGenExprForString(ExprContext cx, bir:BasicBlock bb, s:Expr expr) returns CodeGenError|StringExprEffect {
var { result, block } = check codeGenExpr(cx, bb, t:STRING, expr);
if result is bir:StringConstOperand || (result is bir:Register && t:isSubtypeSimple(result.semType, t:STRING)) {
return { result, block };
}
return cx.semanticErr("expected string operand", s:range(expr));
}
function codeGenArgument(ExprContext cx, bir:BasicBlock bb, s:MethodCallExpr|s:FunctionCallExpr callExpr, t:FunctionSignature signature, int i) returns ExprEffect|CodeGenError {
s:Expr arg = callExpr.args[i];
int n = callExpr is s:FunctionCallExpr ? i : i + 1;
if n >= signature.paramTypes.length() {
return cx.semanticErr("too many arguments for call to function", s:range(arg));
}
return codeGenExprForType(cx, bb, signature.paramTypes[n], arg, "incorrect type for argument");
}
function codeGenExprForType(ExprContext cx, bir:BasicBlock bb, t:SemType requiredType, s:Expr expr, string msg) returns CodeGenError|ExprEffect {
ExprEffect effect = check codeGenExpr(cx, bb, requiredType, expr);
if !operandHasType(cx.mod.tc, effect.result, requiredType) {
return cx.semanticErr(msg, s:range(expr));
}
return effect;
}
function codeGenExpr(ExprContext cx, bir:BasicBlock bb, t:SemType? expected, s:Expr expr) returns CodeGenError|ExprEffect {
match expr {
var { expr: groupedExpr } => {
return codeGenExpr(cx, bb, expected, groupedExpr);
}
var { opPos: pos, arithmeticOp: op, left, right } => {
var { lhs, rhs, nextBlock, ifNilBlock } = check codeGenBinaryNilLift(cx, expected, left, right, bb, pos);
return codeGenNilLiftResult(cx, check codeGenArithmeticBinaryExpr(cx, nextBlock, op, pos, lhs, rhs), ifNilBlock, pos);
}
// Negation
{ opPos: var pos, op: "-", operand: var o } => {
var { operand, nextBlock, ifNilBlock } = check codeGenUnaryNilLift(cx, expected, o, bb, pos);
return codeGenNilLiftResult(cx, check codeGenNegateExpr(cx, nextBlock, pos, operand), ifNilBlock, pos);
}
// Bitwise complement
{ opPos: var pos, op: "~", operand: var o } => {
var { operand, nextBlock, ifNilBlock } = check codeGenUnaryNilLift(cx, expected, o, bb, pos);
bir:IntOperand intOperand = check validIntOperand(cx, operand, o);
return codeGenNilLiftResult(cx, check codeGenComplementExpr(cx, nextBlock, pos, intOperand), ifNilBlock, pos);
}
{ opPos: var pos, op: "!", operand: var o } => {
return codeGenLogicalNotExpr(cx, bb, pos, o);
}
var { checkingKeyword, operand, kwPos: pos } => {
check cx.notInConst(expr);
return codeGenCheckingExpr(cx, bb, expected, checkingKeyword, operand, pos);
}
var { opPos: pos, logicalOp: op, left, right } => {
return booleanEffectFromCondEffect(cx, check codeGenLogicalBinaryExpr(cx, bb, op, pos, left, right), pos);
}
var { opPos: pos, bitwiseOp: op, left, right } => {
var { lhs, rhs, nextBlock, ifNilBlock } = check codeGenBinaryNilLift(cx, expected, left, right, bb, pos);
bir:IntOperand l = check validIntOperand(cx, lhs, left);
bir:IntOperand r = check validIntOperand(cx, rhs, right);
return codeGenNilLiftResult(cx, check codeGenBitwiseBinaryExpr(cx, nextBlock, op, pos, l, r), ifNilBlock, pos);
}
// Equality appearing in a non-conditional stmt, eg: `x = y == 1;` no narrowing is possible
var { opPos: pos, equalityOp: op, left, right } => {
var { result: l, block: block1 } = check codeGenExpr(cx, bb, (), left);
var { result: r, block: nextBlock } = check codeGenExpr(cx, block1, (), right);
return codeGenEqualityExpr(cx, nextBlock, op, pos, l, r);
}
var { opPos: pos, relationalOp: op, left, right } => {
return codeGenRelationalExpr(cx, bb, op, pos, left, right);
}
var { td: _, operand: _ } => {
// JBUG #31782 cast needed
return codeGenTypeCast(cx, bb, expected, <s:TypeCastExpr>expr);
}
// Type test
var { td, left, negated, kwPos:pos } => {
return codeGenTypeTest(cx, bb, expected, td, left, negated, pos);
}
// Variable reference
// JBUG #33309 does not work as match pattern
var ref if ref is s:VarRefExpr => {
return codeGenVarRefExpr(cx, ref, expected, bb);
}
// Function/method call
var callExpr if callExpr is (s:FunctionCallExpr|s:MethodCallExpr) => {
check cx.notInConst(expr);
if callExpr is s:FunctionCallExpr {
return codeGenFunctionCallExpr(cx, bb, callExpr);
}
else {
return codeGenMethodCallExpr(cx, bb, callExpr);
}
}
var { func } => {
check cx.notInConst(expr);
return codeGenAnonFunction(cx, bb, func, expr.startPos);
}
// Member access E[i]
var { container, index, opPos: pos } => {
check cx.notInConst(expr);
// Do constant folding here since these expressions are not allowed in const definitions
var { result: l, block: nextBlock } = check codeGenExpr(cx, bb, (), container);
return codeGenMemberAccessExpr(cx, nextBlock, pos, l, index);
}
// Field access
var { container, fieldName, opPos: pos } => {
check cx.notInConst(expr);
var { result: l, block: nextBlock } = check codeGenExpr(cx, bb, (), container);
return codeGenFieldAccessExpr(cx, nextBlock, pos, l, fieldName);
}
// List construct
// JBUG #33309 should be able to use just `var { members }`
var listConstructorExpr if listConstructorExpr is s:ListConstructorExpr => {
check cx.notInConst(expr);
return codeGenListConstructor(cx, bb, expected, listConstructorExpr);
}
// Mapping construct
var mappingConstructorExpr if mappingConstructorExpr is s:MappingConstructorExpr => {
check cx.notInConst(expr);
return codeGenMappingConstructor(cx, bb, expected, mappingConstructorExpr);
}
// Error construct
var { message, kwPos: pos } => {
check cx.notInConst(expr);
return codeGenErrorConstructor(cx, bb, expected, message, pos);
}
// Literal
var { value } => {
return { result: { value, semType: t:singleton(cx.mod.tc, value) }, block: bb };
}
// Int literal
var { digits, base, startPos: pos } => {
bir:SingleValueConstOperand result = singletonOperand(cx, check intLiteralValue(cx, expected, base, digits, pos));
return { result, block: bb };
}
// FP literal
var { untypedLiteral, typeSuffix, startPos: pos } => {
bir:SingleValueConstOperand result = singletonOperand(cx, check fpLiteralValue(cx, expected, untypedLiteral, typeSuffix, pos));
return { result, block: bb };
}
}
panic err:impossible("unrecognized expression type in code gen: " + s:exprToString(expr));
}
function booleanEffectFromCondEffect(ExprContext cx, CondExprEffect effect, Position pos) returns BooleanExprEffect {
var { trueMerger, falseMerger } = effect;
if trueMerger == () || falseMerger == () {
var [constCond, merger] = typeMergerPairSingleton(effect);
return constBooleanExprEffect(cx, merger.dest, constCond, VALUE_CONST | VALUE_SINGLE_SHAPE);
}
else {
bir:AssignTmpRegister result = cx.createAssignTmpRegister(t:BOOLEAN, pos);
bir:BasicBlock contBlock = cx.createBasicBlock();
addAssignAndBranch(cx, true, trueMerger.dest, result, contBlock.label, pos);
addAssignAndBranch(cx, false, falseMerger.dest, result, contBlock.label, pos);
return { block: contBlock, result };
}
}
function addAssignAndBranch(ExprContext cx, boolean value, bir:BasicBlock block, bir:AssignTmpRegister result, bir:Label contBlock, Position pos) {
bir:AssignInsn assignInsn = { operand: singletonOperand(cx, value), pos, result };
bir:BranchInsn brInsn = { dest: contBlock, pos };
block.insns.push(assignInsn, brInsn);
}
function codeGenExprForCond(ExprContext cx, bir:BasicBlock bb, s:Expr expr, PrevTypeMergers? prevs = ()) returns CodeGenError|CondExprEffect {
bir:BooleanOperand operand;
bir:BasicBlock block;
match expr {
var { expr: groupedExpr } => {
return codeGenExprForCond(cx, bb, groupedExpr, prevs);
}
var { td, left, negated, kwPos: pos } => {
t:SemType semType = check cx.resolveTypeDesc(td);
var { result , block: nextBlock, binding } = check codeGenExpr(cx, bb, (), left);
if binding != () {
return codeGenTypeTestForCond(cx, nextBlock, semType, binding, negated, pos, prevs);
}
else {
{ result: operand, block } = check finishCodeGenTypeTest(cx, semType, result, nextBlock, negated, pos);
}
}
var { opPos: pos, logicalOp: op, left, right } => {
return codeGenLogicalBinaryExpr(cx, bb, op, pos, left, right, prevs);
}
var { opPos: pos, equalityOp: op, left, right } => {
var { result: l, block: block1, binding: lBinding } = check codeGenExpr(cx, bb, (), left);
var { result: r, block: nextBlock, binding: rBinding } = check codeGenExpr(cx, block1, (), right);
boolean exact = op.length() == 3;
[Binding, t:SingleValue]? narrowingCompare = ();
if !exact {
t:WrappedSingleValue? lShape = operandSingleShape(l);
t:WrappedSingleValue? rShape = operandSingleShape(r);
if lBinding is Binding && rShape !is () {
narrowingCompare = [lBinding, rShape.value];
}
else if rBinding is Binding && lShape !is () {
narrowingCompare = [rBinding, lShape.value];
}
}
boolean negated = op.startsWith("!");
if narrowingCompare == () {
{ result: operand, block } = check codeGenEqualityExpr(cx, nextBlock, op, pos, l, r);
}
else {
t:Context tc = cx.mod.tc;
var [binding, value] = narrowingCompare;
t:SemType ty = t:singleton(tc, value);
CondExprEffect result = check codeGenTypeTestForCond(cx, nextBlock, ty, binding, negated, pos, prevs);
TypeMerger? taken = negated ? result.falseMerger : result.trueMerger;
if taken == () {
return cx.semanticErr(`intersection of operands of operator ${op} is empty`, pos);
}
return result;
}
}
{ opPos: var pos, op: "!", operand: var o } => {
return codeGenLogicalNotExprForCond(cx, bb, pos, o, prevs);
}
_ => {
{ result: operand, block } = check codeGenExprForBoolean(cx, bb, expr);
}
}
var [value, flags] = booleanOperandValue(operand);
if (flags & VALUE_SINGLE_SHAPE) != 0 {
return codeGenConstCond(cx, block, value, prevs, expr.startPos);
}
bir:Register result;
if flags != 0 {
bir:TmpRegister reg = cx.createTmpRegister(t:BOOLEAN);
bir:EqualityInsn insn;
// intersection of the types of the operands of === and !=== must not be disjoint
if value {
insn = {
op: "===",
pos: expr.startPos,
operands: [{ value, semType: t:singleton(cx.mod.tc, t:BOOLEAN) }, { value: true, semType: t:BOOLEAN}],
result: reg
};
}
else {
insn = {
op: "!==",
pos: expr.startPos,
operands: [{ value, semType: t:singleton(cx.mod.tc, t:BOOLEAN) }, { value: false, semType: t:BOOLEAN}],
result: reg
};
}
block.insns.push(insn);
result = reg;
}
else {
result = <bir:Register>operand;
}
TypeMerger trueMerger = createMerger(cx, block.label, prevs?.trueMerger);
TypeMerger falseMerger = createMerger(cx, block.label, prevs?.falseMerger);
bir:CondBranchInsn condBranch = { operand: result, ifTrue: trueMerger.dest.label, ifFalse: falseMerger.dest.label, pos: expr.startPos };
block.insns.push(condBranch);
return { trueMerger, falseMerger };
}
function codeGenNilLiftResult(ExprContext cx, ExprEffect nonNilEffect, bir:BasicBlock? ifNilBlock, Position pos) returns ExprEffect {
if ifNilBlock == () {
return nonNilEffect;
}
else {
bir:BasicBlock block = cx.createBasicBlock();
bir:Operand nonNilResult = nonNilEffect.result;
bir:BasicBlock nonNilBlock = nonNilEffect.block;
bir:AssignTmpRegister result = cx.createAssignTmpRegister(t:union(operandSemType(cx.mod.tc, nonNilResult), t:NIL), pos);
bir:AssignInsn nilAssign = { result, operand: bir:NIL_OPERAND, pos };
ifNilBlock.insns.push(nilAssign);
bir:BranchInsn branchInsn = { dest: block.label, pos };
ifNilBlock.insns.push(branchInsn);
bir:AssignInsn valAssign = { result, operand: nonNilResult, pos };
nonNilBlock.insns.push(valAssign);
nonNilBlock.insns.push(branchInsn);
return { result, block };
}
}
type NilLiftResult record {|
bir:Operand[] operands;
bir:BasicBlock nextBlock;
bir:BasicBlock? ifNilBlock;
|};
type BinaryNilLiftResult record {|
bir:Operand lhs;
bir:Operand rhs;
bir:BasicBlock nextBlock;
bir:BasicBlock? ifNilBlock = ();
|};
type UnaryNilLiftResult record {|
bir:Operand operand;
bir:BasicBlock nextBlock;
bir:BasicBlock? ifNilBlock = ();
|};
function codeGenBinaryNilLift(ExprContext cx, t:SemType? expected, s:Expr left, s:Expr right, bir:BasicBlock bb, Position pos) returns BinaryNilLiftResult|CodeGenError {
var { operands, nextBlock, ifNilBlock } = check codeGenNilLift(cx, expected, [left, right], bb, pos);
return { lhs: operands[0], rhs: operands[1], nextBlock, ifNilBlock };
}
function codeGenUnaryNilLift(ExprContext cx, t:SemType? expected, s:Expr operand, bir:BasicBlock bb, Position pos) returns UnaryNilLiftResult|CodeGenError {
var { operands, nextBlock, ifNilBlock } = check codeGenNilLift(cx, expected, [operand], bb, pos);
return { operand: operands[0], nextBlock, ifNilBlock };
}
function codeGenNilLift(ExprContext cx, t:SemType? expected, s:Expr[] operands, bir:BasicBlock bb, Position pos) returns NilLiftResult|CodeGenError {
bir:BasicBlock? ifNilBlock = ();
bir:BasicBlock currentBlock = bb;
bir:Operand[] newOperands = [];
foreach s:Expr operandExpr in operands {
var { result: operand, block } = check codeGenExpr(cx, currentBlock, expected, operandExpr);
currentBlock = block;
newOperands.push(operand);
}
bir:BasicBlock nextBlock = currentBlock;
foreach int i in 0 ..< newOperands.length() {
bir:Operand operand = newOperands[i];
if operand is bir:Register && t:containsNil(operand.semType) {
nextBlock = cx.createBasicBlock();
t:SemType baseType = t:diff(operand.semType, t:NIL);
bir:NarrowRegister ifTrueRegister = cx.createNarrowRegister(t:NIL, operand);
bir:NarrowRegister ifFalseRegister = cx.createNarrowRegister(baseType, operand);
newOperands[i] = ifFalseRegister;
bir:BasicBlock ifTrueBlock = maybeCreateBasicBlock(cx, ifNilBlock);
ifNilBlock = ifTrueBlock;
bir:TypeCondBranchInsn branchInsn = {
operand,
semType: t:NIL,
ifTrue: ifTrueBlock.label,
ifFalse: nextBlock.label,
ifTrueRegister,
ifFalseRegister,
pos
};
currentBlock.insns.push(branchInsn);
currentBlock = nextBlock;
}
}
return { operands: newOperands, nextBlock, ifNilBlock };
}
type MappingAccessType "."|"["|"fill";
// if accessType is ".", k must be a string
function codeGenMappingGet(ExprContext cx, bir:BasicBlock block, bir:Register mapping, MappingAccessType accessType, bir:StringOperand k, Position pos) returns CodeGenError|RegExprEffect {
t:SemType memberType = t:mappingMemberTypeInner(cx.mod.tc, mapping.semType, k.semType);
boolean maybeMissing = true;
if !t:containsUndef(memberType) {
maybeMissing = false;
}
else if accessType == "." {
string fieldName = (<bir:StringConstOperand>k).value;
return cx.semanticErr(`field access to ${fieldName}} is invalid because field may not be present`, pos=pos);
}
bir:INSN_MAPPING_FILLING_GET|bir:INSN_MAPPING_GET name = bir:INSN_MAPPING_GET;
if maybeMissing {
memberType = t:diff(memberType, t:UNDEF);
if accessType == "fill" {
name = bir:INSN_MAPPING_FILLING_GET;
}
else {
memberType = t:union(memberType, t:NIL);
}
}
bir:TmpRegister result = cx.createTmpRegister(memberType, pos);
bir:Insn insn = { name, result, operands: [mapping, k], pos };
block.insns.push(insn);
return { result, block };
}
function codeGenFieldAccessExpr(ExprContext cx, bir:BasicBlock nextBlock, Position pos, bir:Operand l, string fieldName) returns CodeGenError|ExprEffect {
if l is bir:Register && t:isSubtypeSimple(l.semType, t:MAPPING) {
return codeGenMappingGet(cx, nextBlock, l, ".", singletonStringOperand(cx.mod.tc, fieldName), pos);
}
return cx.semanticErr("can only apply field access to mapping", pos=pos);
}
function codeGenMemberAccessExpr(ExprContext cx, bir:BasicBlock block1, Position pos, bir:Operand l, s:Expr index, boolean fill=false) returns CodeGenError|ExprEffect {
if l is bir:Register {
if t:isSubtypeSimple(l.semType, t:LIST) {
var { result: r, block: nextBlock } = check codeGenExprForInt(cx, block1, index);
t:SemType memberType = t:listMemberTypeInnerVal(cx.mod.tc, l.semType, r.semType);
if t:isEmpty(cx.mod.tc, memberType) {
return cx.semanticErr("index out of range", s:range(index));
}
// XXX this isn't correct for singletons
bir:TmpRegister result = cx.createTmpRegister(memberType, pos);
bir:ListGetInsn insn = { result, operands: [l, r], pos, fill };
nextBlock.insns.push(insn);
return { result, block: nextBlock };
}
else if t:isSubtypeSimple(l.semType, t:MAPPING) {
var { result: r, block: nextBlock } = check codeGenExprForString(cx, block1, index);
return codeGenMappingGet(cx, nextBlock, l, fill ? "fill" : "[", r, pos);
}
else if t:isSubtypeSimple(l.semType, t:STRING) {
return cx.unimplementedErr("not implemented: member access on string", pos=pos);
}
}
return cx.semanticErr("can only apply member access to list or mapping", pos=pos);
}
function codeGenComplementExpr(ExprContext cx, bir:BasicBlock nextBlock, Position pos, bir:IntOperand operand) returns CodeGenError|ExprEffect {
var [value, flags] = intOperandValue(operand);
if flags != 0 {
value = ~value;
t:SemType resultType = (flags & VALUE_SINGLE_SHAPE) != 0 ? t:singleton(cx.mod.tc, value) : t:INT;
return { result: { value, semType: resultType }, block: nextBlock };
}
bir:TmpRegister result = cx.createTmpRegister(t:INT, pos);
bir:IntBitwiseBinaryInsn insn = { op: "^", pos, operands: [singletonIntOperand(cx.mod.tc, -1), operand], result };
nextBlock.insns.push(insn);
return { result, block: nextBlock };
}
function codeGenNegateExpr(ExprContext cx, bir:BasicBlock nextBlock, Position pos, bir:Operand operand) returns CodeGenError|ExprEffect {
ArithmeticOperand? arith = arithmeticOperand(operand);
bir:TmpRegister result;
bir:Insn insn;
if arith is [t:BT_INT, bir:IntOperand] {
bir:IntOperand intOperand = arith[1];
var [value, flags] = intOperandValue(intOperand);
if flags != 0 {
value = check intNegateEval(cx, pos, value);
t:SemType resultType = (flags & VALUE_SINGLE_SHAPE) != 0 ? t:singleton(cx.mod.tc, value) : t:INT;
return { result: { value, semType: resultType }, block: nextBlock };
}
result = cx.createTmpRegister(t:INT, pos);
insn = <bir:IntArithmeticBinaryInsn> { op: "-", pos, operands: [singletonIntOperand(cx.mod.tc, 0), intOperand], result };
}
else if arith is [t:BT_FLOAT, bir:FloatOperand] {
bir:FloatOperand floatOperand = arith[1];
var [value, flags] = floatOperandValue(floatOperand);
t:SemType resultType = t:FLOAT;
if flags != 0 {
value = -value; // shouldn't ever panic
if (flags & VALUE_SINGLE_SHAPE) != 0 {
resultType = t:singleton(cx.mod.tc, value);
}
if value != 0f || (flags & VALUE_CONST) != 0 {
return { result: { value, semType: resultType }, block: nextBlock };
}
}
result = cx.createTmpRegister(resultType, pos);
insn = <bir:FloatNegateInsn> { operand: <bir:Register>floatOperand, result, pos };
}
else if arith is [t:BT_DECIMAL, bir:DecimalOperand] {
bir:DecimalOperand decimalOperand = arith[1];
var [value, flags] = decimalOperandValue(decimalOperand);
t:SemType resultType = t:DECIMAL;
if flags != 0 {
value = -value; // shouldn't ever panic
if (flags & VALUE_SINGLE_SHAPE) != 0 {
resultType = t:singleton(cx.mod.tc, value);
}
if (flags & VALUE_CONST) != 0 {
return { result: { value, semType: resultType }, block: nextBlock };
}
}
result = cx.createTmpRegister(resultType, pos);
insn = <bir:DecimalNegateInsn> { operand: <bir:Register>decimalOperand, result, pos };
}
else {
return cx.semanticErr(`operand of ${"-"} must be int or float or decimal`, pos);
}
nextBlock.insns.push(insn);
return { result, block: nextBlock };
}
function codeGenArithmeticBinaryExpr(ExprContext cx, bir:BasicBlock bb, bir:ArithmeticBinaryOp op, Position pos, bir:Operand lhs, bir:Operand rhs) returns CodeGenError|ExprEffect {
ArithmeticOperandPair? pair = arithmeticOperandPair(lhs, rhs);
bir:TmpRegister result;
if pair is IntOperandPair {
readonly & bir:IntOperand[2] operands = pair[1];
var [leftVal, leftFlags] = intOperandValue(operands[0]);
var [rightVal, rightFlags] = intOperandValue(operands[1]);
ValueFlags resultFlags = leftFlags & rightFlags;
if resultFlags != 0 {
int value = check intArithmeticEval(cx, pos, op, leftVal, rightVal);
t:SemType resultType = (resultFlags & VALUE_SINGLE_SHAPE) != 0 ? t:singleton(cx.mod.tc, value) : t:INT;
return { result: { value, semType: resultType }, block: bb };
}
result = cx.createTmpRegister(t:INT, pos);
bir:Insn insn;
// JBUG #34987: can't use a function to return the name directly
// var name = intArithmeticOpNeverPanics(op, operands);
// insn = { op, pos, name, operand, result };
if intArithmeticOpNeverPanics(op, operands) {
insn = { op, pos, name: bir:INSN_INT_NO_PANIC_ARITHMETIC_BINARY, operands, result };
}
else {
insn = { op, pos, name: bir:INSN_INT_ARITHMETIC_BINARY, operands, result };
}
bb.insns.push(insn);
}
else if pair is FloatOperandPair {
readonly & bir:FloatOperand[2] operands = pair[1];
var [leftVal, leftFlags] = floatOperandValue(operands[0]);
var [rightVal, rightFlags] = floatOperandValue(operands[1]);
ValueFlags resultFlags = leftFlags & rightFlags;
t:SemType resultType = t:FLOAT;
if op == "/" && rightVal == 0f {
resultFlags &= ~VALUE_SINGLE_SHAPE;
}
if resultFlags != 0 {
float value = floatArithmeticEval(op, leftVal, rightVal);
if (resultFlags & VALUE_SINGLE_SHAPE) != 0 {
resultType = t:singleton(cx.mod.tc, value);
}
// If the shape isn't 0f, then we can infer the value from the shape.
if value != 0f || (resultFlags & VALUE_CONST) != 0 {
return { result: { value, semType: resultType }, block: bb };
}
}
result = cx.createTmpRegister(resultType, pos);
bir:FloatArithmeticBinaryInsn insn = { op, pos, operands, result };
bb.insns.push(insn);
}
else if pair is DecimalOperandPair {
readonly & bir:DecimalOperand[2] operands = pair[1];
var [leftVal, leftFlags] = decimalOperandValue(operands[0]);
var [rightVal, rightFlags] = decimalOperandValue(operands[1]);
ValueFlags resultFlags = leftFlags & rightFlags;
t:SemType resultType = t:DECIMAL;
if resultFlags != 0 {
decimal value = check decimalArithmeticEval(cx, pos, op, leftVal, rightVal);
if (resultFlags & VALUE_SINGLE_SHAPE) != 0 {
resultType = t:singleton(cx.mod.tc, value);
}
// Even if we have the shape, we need to compute the value in order to get the precision right.
if (resultFlags & VALUE_CONST) != 0 {
return { result: { value, semType: resultType }, block: bb };
}
}
result = cx.createTmpRegister(resultType, pos);
bir:DecimalArithmeticBinaryInsn insn = { op, pos, operands, result };
bb.insns.push(insn);
}
else if pair is StringOperandPair && op == "+" {
readonly & bir:StringOperand[2] operands = pair[1];
var [leftVal, leftFlags] = stringOperandValue(operands[0]);
var [rightVal, rightFlags] = stringOperandValue(operands[1]);
ValueFlags resultFlags = leftFlags & rightFlags;
if resultFlags != 0 {
return constExprEffect(cx, bb, leftVal + rightVal, resultFlags);
}
result = cx.createTmpRegister(t:STRING, pos);
bir:StringConcatInsn insn = { operands: pair[1], result, pos };
bb.insns.push(insn);
}
else {
return cx.semanticErr(`${op} not supported for operand types`, pos);
}
return { result, block: bb };
}
function intArithmeticOpNeverPanics(bir:ArithmeticBinaryOp op, bir:Operand[] operands) returns boolean {
t:IntSubtypeConstraints?[] operandConstraints = from bir:Operand operand in operands select t:intSubtypeConstraints(operand.semType);
t:IntSubtypeConstraints[] constraints = [];
foreach t:IntSubtypeConstraints? constraint in operandConstraints {
if constraint == () {
return false;
}
constraints.push(constraint);
}
int noPanicMin;
int noPanicMax;
if op is "+"|"-" {
// largest type that can't overflow is unsigned32 (positive) and signed32 (negative)
noPanicMax = int:UNSIGNED32_MAX_VALUE;
noPanicMin = int:SIGNED32_MIN_VALUE;
}
else if op is "*" {
// largest type that can't overflow is signed32
noPanicMax = int:SIGNED32_MAX_VALUE;
noPanicMin = int:SIGNED32_MIN_VALUE;
}
else {
return false;
}
foreach t:IntSubtypeConstraints constraint in constraints {
if constraint.max > noPanicMax || constraint.min < noPanicMin {
return false;
}
}
return true;
}
function codeGenLogicalNotExpr(ExprContext cx, bir:BasicBlock bb, Position pos, s:Expr expr) returns CodeGenError|ExprEffect {
var { result: operand, block: nextBlock } = check codeGenExprForBoolean(cx, bb, expr);
var [value, flags] = booleanOperandValue(operand);
if flags != 0 {
return constExprEffect(cx, nextBlock, !value, flags);
}
bir:TmpRegister result = cx.createTmpRegister(t:BOOLEAN, pos);
bir:BooleanNotInsn insn = { operand: <bir:Register>operand, result, pos };
nextBlock.insns.push(insn);
return { result, block: nextBlock };
}
function codeGenLogicalNotExprForCond(ExprContext cx, bir:BasicBlock bb, Position pos, s:Expr expr, PrevTypeMergers? prevs) returns CodeGenError|CondExprEffect {
PrevTypeMergers? flipped = prevs == () ? () : { trueMerger: prevs.falseMerger, falseMerger: prevs.trueMerger };
var { trueMerger, falseMerger } = check codeGenExprForCond(cx, bb, expr, flipped);
return { trueMerger: falseMerger, falseMerger: trueMerger };
}
function codeGenLogicalBinaryExpr(ExprContext cx, bir:BasicBlock bb, s:BinaryLogicalOp op, Position pos, s:Expr left, s:Expr right, PrevTypeMergers? prevs = ()) returns CodeGenError|CondExprEffect {
boolean isOr = op == "||";
var lhsEffect = check codeGenExprForCond(cx, bb, left, prevs);
var { trueMerger: lhsTrueMerger, falseMerger: lhsFalseMerger } = lhsEffect;
if lhsTrueMerger == () || lhsFalseMerger == () {
var [constCond, merger] = typeMergerPairSingleton(lhsEffect);
if constCond == isOr {
// Only to check errors on rhs, result is discarded.
bir:BasicBlock dummyBlock = cx.createDummyBasicBlock(merger.dest);
_ = check codeGenExprForBoolean(cx, dummyBlock, right);
cx.discardBasicBlocksFromDummy(dummyBlock);
return lhsEffect;
}
else {
return check codeGenExprForCond(cx, merger.dest, right, prevs);
}
}
else {
// When compiling a chain of && or chain of ||, keep growing falseMerger or trueMerger respectively
[TypeMerger?, TypeMerger?, TypeMerger] [trueMerger, falseMerger, rhsMerger] = isOr ? [lhsTrueMerger, (), lhsFalseMerger] : [(), lhsFalseMerger, lhsTrueMerger];
// When switching from a chain of && to chain of || or vice versa we may need a type merge insn
var { block: rhsBlock, bindings: rhsBindings } = codeGenTypeMergeFromMerger(cx, rhsMerger, pos);
return codeGenExprForCond(cx.exprContext(rhsBindings), rhsBlock, right, { trueMerger, falseMerger });
}
}
function codeGenBitwiseBinaryExpr(ExprContext cx, bir:BasicBlock bb, s:BinaryBitwiseOp op, Position pos, bir:IntOperand lhs, bir:IntOperand rhs) returns CodeGenError|ExprEffect {
var [leftValue, leftFlags] = intOperandValue(lhs);
var [rightValue, rightFlags] = intOperandValue(rhs);
ValueFlags resultFlags = leftFlags & rightFlags;
t:SemType leftWidenedType = t:widenUnsigned(lhs.semType);
t:SemType rightWidenedType = t:widenUnsigned(rhs.semType);
t:SemType resultType;
if op is s:BitwiseShiftOp {
resultType = op is ">>"|">>>" && t:isSubtype(cx.mod.tc, leftWidenedType, t:intWidthUnsigned(32)) ? leftWidenedType : t:INT;
}
else {
resultType = op == "&" ? t:intersect(leftWidenedType, rightWidenedType) : t:union(leftWidenedType, rightWidenedType);
}
if resultFlags != 0 {
int value = bitwiseEval(op, leftValue, rightValue);
if (resultFlags & VALUE_SINGLE_SHAPE) != 0 {
resultType = t:singleton(cx.mod.tc, value);
}
return { result: { value, semType: resultType }, block: bb };
}
bir:TmpRegister result = cx.createTmpRegister(resultType, pos);
bir:IntBitwiseBinaryInsn insn = { op, pos, operands: [lhs, rhs], result };
bb.insns.push(insn);
return { result, block: bb };
}
function codeGenListConstructor(ExprContext cx, bir:BasicBlock bb, t:SemType? expected, s:ListConstructorExpr expr) returns CodeGenError|ExprEffect {
bir:BasicBlock nextBlock = bb;
bir:Operand[] operands = [];
t:SemType resultType;
t:ListAtomicType atomicType;
if expected != () {
[resultType, atomicType] = check selectListInherentType(cx, expected, expr);
foreach var [i, member] in expr.members.enumerate() {
bir:Operand operand;
t:SemType requiredType = t:listAtomicTypeMemberAtInnerVal(atomicType, i);
if requiredType == t:NEVER {
return cx.semanticErr("this member is more than what is allowed by type", s:range(member));
}
{ result: operand, block: nextBlock } = check codeGenExprForType(cx, nextBlock, requiredType, member, "incorrect type for list member");
operands.push(operand);
}
}
else {
t:SemType[] memberSemTypes = [];
foreach s:Expr member in expr.members {
bir:Operand operand;
{ result: operand, block: nextBlock } = check codeGenExpr(cx, nextBlock, (), member);
operands.push(operand);
t:SemType broadType = t:singleShape(operand.semType) == () ? operand.semType : t:widenToBasicTypes(operand.semType);
memberSemTypes.push(broadType);
}
resultType = t:defineListTypeWrapped(new(), cx.mod.tc.env, memberSemTypes, memberSemTypes.length());
atomicType = <t:ListAtomicType>t:listAtomicType(cx.mod.tc, resultType);
}
check fillListOperands(cx, nextBlock, operands, atomicType, expr);
bir:TmpRegister result = cx.createTmpRegister(resultType, expr.opPos);
bir:ListConstructInsn insn = { operands: operands.cloneReadOnly(), result, pos: expr.opPos };
nextBlock.insns.push(insn);
return { result, block: nextBlock };
}
function fillListOperands(ExprContext cx, bir:BasicBlock bb, bir:Operand[] operands,
t:ListAtomicType atomicType, s:ListConstructorExpr expr) returns ResolveTypeError? {
operands.push(...from int i in operands.length() ..< atomicType.members.fixedLength select
check codeGenFillerOperand(cx, bb, check listMemberFiller(cx, atomicType, i, expr), expr));
}
function codeGenFillerOperand(ExprContext cx, bir:BasicBlock bb, t:Filler filler, s:ListConstructorExpr expr) returns bir:Operand|ResolveTypeError {
if filler is t:WrappedSingleValue {
return singletonOperand(cx, filler.value);
}
bir:ListConstructInsn|bir:MappingConstructInsn insn;
bir:TmpRegister result = cx.createTmpRegister(filler.semType);
if filler is t:ListFiller {
bir:Operand[] operands = [];
check fillListOperands(cx, bb, operands, filler.atomic, expr);
insn = { operands: operands.cloneReadOnly(), result, pos: expr.endPos };
}
else {
// We don't have named mapping fields with default values
insn = <bir:MappingConstructInsn> { fieldNames: [], operands: [], result, pos: expr.endPos };
}
bb.insns.push(insn);
return result;
}
function listMemberFiller(ExprContext cx, t:ListAtomicType atomicType, int index, s:ListConstructorExpr expr) returns t:Filler|ResolveTypeError {
t:Filler? memberFiller = t:filler(cx.mod.tc, t:listAtomicTypeMemberAtInner(atomicType, index));
if memberFiller == () {
return cx.semanticErr("no filler value", s:range(expr));
}
return memberFiller;
}
function selectListInherentType(ExprContext cx, t:SemType expectedType, s:ListConstructorExpr expr) returns [t:SemType, t:ListAtomicType]|ResolveTypeError {
// SUBSET always have contextually expected type for list constructor
t:SemType expectedListType = t:intersect(expectedType, t:LIST);
t:Context tc = cx.mod.tc;
if t:isEmpty(tc, expectedListType) {
// don't think this can happen
return cx.semanticErr("list not allowed in this context", s:range(expr));
}
t:ListAtomicType? lat = t:listAtomicType(tc, expectedListType);
if lat != () {
return [expectedListType, lat];
}
int len = expr.members.length();
t:ListAlternative[] alts =
from var alt in t:listAlternatives(tc, expectedListType)
where listAlternativeAllowsLength(alt, len)
select alt;
if alts.length() == 0 {
return cx.semanticErr("no applicable inherent type for list constructor", s:range(expr));
}
else if alts.length() > 1 {
return cx.semanticErr("ambiguous inherent type for list constructor", s:range(expr));