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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
|
/* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
\* */
// $Id$
package scalac.backend.jvm;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import ch.epfl.lamp.fjbg.*;
import ch.epfl.lamp.util.Pair;
import scala.tools.util.Position;
import scalac.*;
import scalac.ast.Tree;
import scalac.atree.AConstant;
import scalac.backend.*;
import scalac.symtab.*;
import scalac.symtab.classfile.ClassfileConstants;
import scalac.symtab.classfile.Pickle;
import scalac.transformer.*;
import scalac.util.*;
/* Several things which are done here should in fact be done in
* previous phases, namely:
*
* - code linearisation (i.e. representation of code as a list of
* instructions),
*
* - removal of implicit "this" selection,
*
* - removal of implicit "unit" values,
*
* - removal of implicit conversion,
*
* - removal of "if"s without explicit "else" part,
*
* - expansion of "==",
*
* - introduction of a special primitive for string concatenation,
*
* - initialisation of module instance variable.
*/
/**
* Backend generating JVM byte-codes.
*
* @version 2.0
* @author Michel Schinz
*/
class GenJVM {
protected final static String JAVA_LANG_OBJECT = "java.lang.Object";
protected final static String JAVA_LANG_STRING = "java.lang.String";
protected final static String JAVA_LANG_STRINGBUFFER =
"java.lang.StringBuffer";
protected final static String JAVA_RMI_REMOTE = "java.rmi.Remote";
protected final static String JAVA_RMI_REMOTEEXCEPTION =
"java.rmi.RemoteException";
protected final static String SCALA_RUNTIME_RUNTIME =
"scala.runtime.RunTime";
protected final static String SCALA_ATTR =
ClassfileConstants.SCALA_N.toString();
protected final static String MODULE_INSTANCE_FIELD_NAME = "MODULE$";
protected final static String CONSTRUCTOR_STRING =
"<init>"; // TODO get it from FJBG
protected final JObjectType JAVA_LANG_OBJECT_T =
new JObjectType(JAVA_LANG_OBJECT);
protected final JObjectType JAVA_LANG_STRING_T =
new JObjectType(JAVA_LANG_STRING);
protected final JObjectType JAVA_LANG_STRINGBUFFER_T =
new JObjectType (JAVA_LANG_STRINGBUFFER);
protected final JObjectType JAVA_LANG_THROWABLE_T =
new JObjectType("java.lang.Throwable");
protected final Symbol JAVA_RMI_REMOTE_CLASS;
protected final Global global;
protected final Definitions defs;
protected final Primitives prims;
protected final Phase refCheckPhase;
protected final AddInterfacesPhase addInterfacesPhase;
protected final FJBGContext fjbgContext;
protected final ArrayList pickles = new ArrayList();
public GenJVM(Global global) {
this.global = global;
this.defs = global.definitions;
this.prims = global.primitives;
this.refCheckPhase = global.PHASE.REFCHECK.phase();
this.addInterfacesPhase =
(AddInterfacesPhase)global.PHASE.ADDINTERFACES.phase();
this.fjbgContext = new FJBGContext();
initTypeMap();
initArithPrimMap();
JAVA_RMI_REMOTE_CLASS = defs.getClass(JAVA_RMI_REMOTE);
}
/// Code generation
//////////////////////////////////////////////////////////////////////
/**
* Generate code for the given unit.
*/
public void translate(CompilationUnit unit) {
try {
for (int i = 0; i < unit.body.length; ++i)
gen(Context.EMPTY.withSourceFileName(unit.source.getFile().getName()),
unit.body[i]);
} catch (JCode.OffsetTooBigException e) {
if (global.debug) e.printStackTrace();
global.error(e.getMessage());
}
// write .symbl files (must be generated after .class files)
for (int i = 0; i < pickles.size() / 2; i++) {
JClass clazz = (JClass)pickles.get(2 * i + 0);
Pickle pickle = (Pickle)pickles.get(2 * i + 1);
writeSymblFile(clazz, pickle);
}
pickles.clear();
}
/**
* Generate code to perform the side effects associated with the
* given tree (i.e. no value should remain on the stack
* afterwards).
*/
protected void gen(Context ctx, Tree tree) throws JCode.OffsetTooBigException {
startCodeForTree(ctx, tree);
Symbol sym = tree.symbol();
switch (tree) {
case PackageDef(_, Tree.Template impl):
gen(ctx, impl);
break;
case ClassDef(_, _, _, _, _, Tree.Template impl) : {
Tree.ClassDef classDef = (Tree.ClassDef)tree;
Context ctx1 = enterClass(ctx, sym);
addValueClassMembers(ctx1, classDef);
gen(ctx1, impl);
JMethod clinit = getClassConstructorMethod(ctx1);
if (clinit.getCode().getSize() == 0) {
Context ctx2 =
ctx1.withMethod(clinit, Collections.EMPTY_MAP, false);
completeClassConstructor(ctx2, sym);
ctx2.code.emitRETURN();
genLocalVariableTable(ctx2);
}
leaveClass(ctx1, sym);
} break;
case Template(_, Tree[] body):
gen(ctx, body);
break;
case ValDef(_, Name name, _, Tree rhs): {
if (ctx.method == null)
break; // ignore ValDefs in classes, handled elsewhere
JType valType = typeStoJ(sym.info());
JLocalVariable var =
ctx.method.addNewLocalVariable(valType, name.toString());
ctx.locals.put(sym, new Integer(var.getIndex()));
assert (rhs != Tree.Empty) : Debug.show(sym);
genLoad(ctx, rhs, valType);
ctx.code.emitSTORE(var);
} break;
case DefDef(_, _, _, _, _, Tree rhs): {
Tree.DefDef defDef = (Tree.DefDef)tree;
boolean retry = false;
do {
Context ctx1 = enterMethod(ctx, defDef, retry);
try {
if (! Modifiers.Helper.isAbstract(sym.flags)) {
JType retType = ctx1.method.getReturnType();
genLoad(ctx1, rhs, retType);
if (sym.name == Names.CLASS_CONSTRUCTOR)
completeClassConstructor(ctx1, sym.owner());
ctx1.code.emitRETURN(retType);
ctx1.method.freeze();
}
leaveMethod(ctx1);
break;
} catch (JCode.OffsetTooBigException e) {
ctx1.clazz.removeMethod(ctx1.method);
assert !retry;
retry = true;
}
} while (retry);
} break;
case Return(Tree expr): {
JType retType = ctx.method.getReturnType();
genLoad(ctx, expr, retType);
ctx.code.emitRETURN(retType);
} break;
case Typed(Tree expr, _):
gen(ctx, expr);
break;
case Empty:
case AbsTypeDef(_, _, _, _):
case AliasTypeDef(_, _, _, _):
case TypeApply(_, _):
case FunType(_, _):
case CompoundType(_, _):
case AppliedType(_,_):
break;
default:
genLoad(ctx, tree, JType.VOID);
}
endCodeForTree(ctx, tree);
}
protected void gen(Context ctx, Tree[] trees)
throws JCode.OffsetTooBigException {
for (int i = 0; i < trees.length; ++i)
gen(ctx, trees[i]);
}
/**
* Generate code to load the value of the given tree on the
* stack, and make sure it is of the given expected type.
*/
protected JType genLoad(Context ctx, Tree tree, JType expectedType)
throws JCode.OffsetTooBigException {
startCodeForTree(ctx, tree);
JType generatedType = null;
Symbol sym = tree.symbol();
switch (tree) {
case LabelDef(_, Tree.Ident[] params, Tree rhs): {
JCode.Label label = ctx.code.newLabel();
label.anchorToNext();
ctx.labels.put(sym, new Pair(label, params));
generatedType = genLoad(ctx, rhs, expectedType);
ctx.labels.remove(sym);
} break;
case Block(Tree[] stats, Tree value): {
int statsNum = stats.length;
for (int i = 0; i < stats.length; ++i)
gen(ctx, stats[i]);
genLoad(ctx, value, expectedType);
generatedType = expectedType;
} break;
case Typed(Tree expr, _):
genLoad(ctx, expr, expectedType);
generatedType = expectedType;
break;
case New(Tree init):
String className = javaName(tree.type.symbol());
ctx.code.emitNEW(className);
ctx.code.emitDUP();
gen(ctx, init);
generatedType = new JObjectType(className);
break;
case Apply(TypeApply(Tree fun, Tree[] args), _): {
genLoadQualifier(ctx, fun);
JType type = typeStoJ(args[0].type);
if (fun.symbol() == defs.ANY_IS) {
ctx.code.emitINSTANCEOF((JReferenceType)type);
generatedType = JType.BOOLEAN;
} else if (fun.symbol() == defs.ANY_AS) {
ctx.code.emitCHECKCAST((JReferenceType)type);
generatedType = type;
} else
throw Debug.abort("unexpected type application", tree);
} break;
case Apply(Tree fun, Tree[] args): {
Symbol funSym = fun.symbol();
if (funSym.isLabel()) {
Pair/*<Label, Tree[]>*/ labelAndIdents =
(Pair)ctx.labels.get(funSym);
assert labelAndIdents != null : Debug.show(funSym);
JMethodType funType = (JMethodType)typeStoJ(funSym.info());
JCode.Label label = (JCode.Label)labelAndIdents.fst;
Tree[] idents = (Tree[])labelAndIdents.snd;
assert idents.length == args.length;
for (int i = 0; i < args.length; ++i)
genLoad(ctx, args[i], typeStoJ(args[i].type));
for (int i = idents.length; i > 0; --i)
genStoreEpilogue(ctx, idents[i-1]);
ctx.code.emitGOTO_maybe_W(label, ctx.useWideJumps);
generatedType = funType.getReturnType();
} else if (isKnownPrimitive(funSym)) {
Primitive prim = prims.getPrimitive(funSym);
switch (prim) {
case CONCAT:
genStringConcatenation(ctx, liftStringConcatenations(tree));
generatedType = JAVA_LANG_STRING_T;
break;
case POS: case NEG:
case ADD: case SUB: case MUL: case DIV: case MOD:
case NOT: case OR : case XOR: case AND:
case LSL: case LSR: case ASR:
Tree[] allArgs = extractPrimitiveArgs((Tree.Apply)tree);
allArgs[0] = unbox(allArgs[0]);
JType resType = typeStoJ(tree.type);
genArithPrim(ctx, prim, allArgs, resType, expectedType);
generatedType = resType;
break;
case ID:
case EQ: case NE: case LT: case LE: case GE: case GT:
case ZNOT: case ZOR: case ZAND:
JCode.Label falseLabel = ctx.code.newLabel();
JCode.Label afterLabel = ctx.code.newLabel();
genCond(ctx, tree, falseLabel, false);
ctx.code.emitICONST_1();
ctx.code.emitGOTO_maybe_W(afterLabel, ctx.useWideJumps);
falseLabel.anchorToNext();
ctx.code.emitICONST_0();
afterLabel.anchorToNext();
generatedType = JType.BOOLEAN;
break;
case THROW:
assert args.length == 0;
genThrow(ctx, ((Tree.Select)fun).qualifier);
// We pretend that we generated something of the
// expected type, to avoid trying to generate
// bogus conversions.
generatedType = expectedType;
break;
case SYNCHRONIZED: {
assert args.length == 1;
Tree qual = ((Tree.Select)fun).qualifier;
genSynchronized(ctx, qual, args[0], expectedType);
generatedType = expectedType;
} break;
case NEW_OARRAY: {
assert args.length == 2;
genRefArrayCreate(ctx, args[0], args[1]);
generatedType = expectedType;
} break;
case NEW_ZARRAY : case NEW_BARRAY : case NEW_SARRAY :
case NEW_CARRAY : case NEW_IARRAY : case NEW_LARRAY :
case NEW_FARRAY : case NEW_DARRAY :
assert args.length == 1;
genArrayCreate(ctx, prim, args[0]);
generatedType = JAVA_LANG_OBJECT_T; // TODO refine
break;
case ZARRAY_SET : case BARRAY_SET : case SARRAY_SET :
case CARRAY_SET : case IARRAY_SET : case LARRAY_SET :
case FARRAY_SET : case DARRAY_SET : case OARRAY_SET :
assert args.length == 3;
genArrayUpdate(ctx, args[0], args[1], args[2]);
generatedType = JType.VOID;
break;
case ZARRAY_GET : case BARRAY_GET : case SARRAY_GET :
case CARRAY_GET : case IARRAY_GET : case LARRAY_GET :
case FARRAY_GET : case DARRAY_GET : case OARRAY_GET :
assert args.length == 2 : "get - " + args.length;
genArrayAccess(ctx, args[0], args[1]);
generatedType = getArrayElementType(args[0]);
break;
case ZARRAY_LENGTH : case BARRAY_LENGTH : case SARRAY_LENGTH :
case CARRAY_LENGTH : case IARRAY_LENGTH : case LARRAY_LENGTH :
case FARRAY_LENGTH : case DARRAY_LENGTH : case OARRAY_LENGTH :
assert args.length == 1 : args.length;
genArrayLength(ctx, args[0]);
generatedType = JType.INT;
break;
case B2B: case B2S: case B2C: case B2I: case B2L: case B2F: case B2D:
case S2B: case S2S: case S2C: case S2I: case S2L: case S2F: case S2D:
case C2B: case C2S: case C2C: case C2I: case C2L: case C2F: case C2D:
case I2B: case I2S: case I2C: case I2I: case I2L: case I2F: case I2D:
case L2B: case L2S: case L2C: case L2I: case L2L: case L2F: case L2D:
case F2B: case F2S: case F2C: case F2I: case F2L: case F2F: case F2D:
case D2B: case D2S: case D2C: case D2I: case D2L: case D2F: case D2D:
assert args.length == 1 : args.length;
JType fromType = typeStoJ(args[0].type);
genLoad(ctx, args[0], fromType);
ctx.code.emitT2T(fromType, expectedType);
generatedType = expectedType;
break;
default:
throw Debug.abort("unknown primitive", prim);
}
} else {
JMethodType funType = (JMethodType)typeStoJ(funSym.info());
JType[] argTypes = funType.getArgumentTypes();
boolean isConstrCall = funSym.isInitializer();
boolean isSuperCall = false;
switch (fun) {
case Select(Super(_, _), _): isSuperCall = true;
}
boolean isStatic = isStaticMember(funSym);
if (!isStatic)
genLoadQualifier(ctx, fun);
for (int i = 0; i < args.length; ++i)
genLoad(ctx, args[i], argTypes[i]);
String clsName = isSuperCall
? ctx.clazz.getSuperclassName()
: javaName(funSym.owner());
String mthName = funSym.name.toString();
funSym.owner().info(); // [HACK] ensure that flags are
// transformed.
if (funSym.owner().isInterface())
ctx.code.emitINVOKEINTERFACE(clsName, mthName, funType);
else {
if (isConstrCall || isSuperCall) {
ctx.code.emitINVOKESPECIAL(clsName, mthName, funType);
if (isConstrCall && isSuperCall && ctx.isModuleClass) {
// Initialise module instance field ASAP
ctx.code.emitALOAD_0();
ctx.code.emitPUTSTATIC(ctx.clazz.getName(),
MODULE_INSTANCE_FIELD_NAME,
ctx.clazz.getType());
}
} else if (isStatic)
ctx.code.emitINVOKESTATIC(clsName, mthName, funType);
else
ctx.code.emitINVOKEVIRTUAL(clsName, mthName, funType);
}
generatedType = funType.getReturnType();
}
} break;
case Ident(_):
JType type = typeStoJ(sym.info());
if (sym.isModule()) {
String javaSymName = javaName(sym.moduleClass());
ctx.code.emitGETSTATIC(javaSymName,
MODULE_INSTANCE_FIELD_NAME,
type);
generatedType = type;
} else if (sym.isStatic()) {
JType fieldType = typeStoJ(sym.info());
String className = javaName(sym.owner());
String fieldName = sym.name.toString();
ctx.code.emitGETSTATIC(className, fieldName, fieldType);
generatedType = type;
} else {
assert ctx.locals.containsKey(sym)
: Debug.show(sym) + " not in " + ctx.locals;
int index = ((Integer)(ctx.locals.get(sym))).intValue();
ctx.code.emitLOAD(index, type);
generatedType = type;
}
break;
case Select(Tree qualifier, _):
JType fieldType = typeStoJ(sym.info());
String className = javaName(sym.owner());
String fieldName = sym.name.toString();
if (sym.isStatic()) {
ctx.code.emitGETSTATIC(className, fieldName, fieldType);
} else {
genLoadQualifier(ctx, tree);
ctx.code.emitGETFIELD(className, fieldName, fieldType);
}
generatedType = fieldType;
break;
case Assign(Tree lhs, Tree rhs): {
genStorePrologue(ctx, lhs);
genLoad(ctx, rhs, typeStoJ(lhs.symbol().info()));
genStoreEpilogue(ctx, lhs);
generatedType = JType.VOID;
} break;
case If(Tree cond, Tree thenp, Tree elsep): {
JType finalType = typeStoJ(tree.type);
JCode.Label elseLabel = ctx.code.newLabel();
genCond(ctx, cond, elseLabel, false);
genLoad(ctx, thenp, finalType);
JCode.Label afterLabel = ctx.code.newLabel();
ctx.code.emitGOTO_maybe_W(afterLabel, ctx.useWideJumps);
elseLabel.anchorToNext();
genLoad(ctx, elsep, finalType);
afterLabel.anchorToNext();
generatedType = finalType;
} break;
case Switch(Tree test, int[] tags, Tree[] bodies, Tree otherwise): {
JCode.Label[] labels = ctx.code.newLabels(bodies.length);
JCode.Label defaultLabel = ctx.code.newLabel();
JCode.Label afterLabel = ctx.code.newLabel();
genLoad(ctx, test, JType.INT);
ctx.code.emitSWITCH(tags, labels, defaultLabel, 0.9);
for (int i = 0; i < bodies.length; ++i) {
labels[i].anchorToNext();
genLoad(ctx, bodies[i], expectedType);
ctx.code.emitGOTO_maybe_W(afterLabel, ctx.useWideJumps);
}
defaultLabel.anchorToNext();
genLoad(ctx, otherwise, expectedType);
afterLabel.anchorToNext();
generatedType = expectedType;
} break;
case This(_):
case Super(_, _):
ctx.code.emitALOAD_0();
generatedType = JAVA_LANG_OBJECT_T;
break;
case Literal(AConstant value):
generatedType = genLoadLiteral(ctx, value, expectedType);
break;
case Empty:
case AbsTypeDef(_, _, _, _):
case AliasTypeDef(_, _, _, _):
case TypeApply(_, _):
case FunType(_, _):
case CompoundType(_, _):
case AppliedType(_,_):
generatedType = JType.VOID;
break;
case Sequence(_):
case ModuleDef(_,_,_,_):
case PatDef(_,_,_):
case Import(_, _):
case CaseDef(_, _, _):
case Visitor(_):
case Function(_, _):
throw Debug.abort("unexpected node", tree);
default:
throw Debug.abort("unknown node", tree);
}
// Pop unneeded result from stack, or widen it if needed.
if (expectedType == JType.VOID && generatedType != JType.VOID) {
if (generatedType == JType.LONG || generatedType == JType.DOUBLE)
ctx.code.emitPOP2();
else
ctx.code.emitPOP();
} else if (! (expectedType == JType.VOID
|| generatedType == expectedType
|| generatedType.isReferenceType()))
ctx.code.emitT2T(generatedType, expectedType);
endCodeForTree(ctx, tree);
return expectedType;
}
/**
* Generate code to load the qualifier of the given tree, which
* can be implicitely "this".
*/
protected void genLoadQualifier(Context ctx, Tree tree)
throws JCode.OffsetTooBigException {
switch (tree) {
case Ident(_):
break;
case Select(Create(_, _), _):
break;
case Select(Tree qualifier, _):
genLoad(ctx, qualifier, JAVA_LANG_OBJECT_T);
break;
default:
throw Debug.abort("unknown qualifier", tree);
}
}
protected JType genLoadLiteral(Context ctx, AConstant lit, JType type) {
switch (lit) {
case UNIT:
return JType.VOID;
case BOOLEAN(boolean value):
ctx.code.emitPUSH(value);
return JType.BOOLEAN;
case BYTE(byte value):
ctx.code.emitPUSH(value);
return JType.BYTE;
case SHORT(short value):
ctx.code.emitPUSH(value);
return JType.SHORT;
case CHAR(char value):
ctx.code.emitPUSH(value);
return JType.CHAR;
case INT(int value):
ctx.code.emitPUSH(value);
return JType.INT;
case LONG(long value):
ctx.code.emitPUSH(value);
return JType.LONG;
case FLOAT(float value):
ctx.code.emitPUSH(value);
return JType.FLOAT;
case DOUBLE(double value):
ctx.code.emitPUSH(value);
return JType.DOUBLE;
case STRING(String value):
ctx.code.emitPUSH(value);
return JAVA_LANG_STRING_T;
case NULL:
if (type != JType.VOID) ctx.code.emitACONST_NULL();
return type;
default:
throw Debug.abort("unknown literal", lit);
}
}
/**
* Generate code to prepare the storage of a value in the location
* represented by the tree.
*/
protected void genStorePrologue(Context ctx, Tree tree)
throws JCode.OffsetTooBigException {
genLoadQualifier(ctx, tree);
}
/**
* Generate code to perform the storage of the value on top of
* stack in the location represented by the tree.
*/
protected void genStoreEpilogue(Context ctx, Tree tree) {
Symbol sym = tree.symbol();
if (sym.owner().isClass()) {
String ownerName = javaName(sym.owner());
if (isStaticMember(sym))
ctx.code.emitPUTSTATIC(ownerName,
sym.name.toString(),
typeStoJ(sym.info()));
else
ctx.code.emitPUTFIELD(ownerName,
sym.name.toString(),
typeStoJ(sym.info()));
} else {
assert ctx.locals.containsKey(sym)
: Debug.show(sym) + " not in " + ctx.locals;
int index = ((Integer)(ctx.locals.get(sym))).intValue();
ctx.code.emitSTORE(index, typeStoJ(sym.info()));
}
}
/**
* Generate code to evaluate the condition associated with the
* given tree and jump to the target when the condition is equal
* to the given value.
*/
protected void genCond(Context ctx,
Tree tree,
JCode.Label target,
boolean when)
throws JCode.OffsetTooBigException {
switch (tree) {
case Apply(Tree fun, Tree[] args):
if (isJumpingPrimitive(fun.symbol())) {
Primitive prim = prims.getPrimitive(fun.symbol());
Tree[] allArgs = extractPrimitiveArgs((Tree.Apply)tree);
switch (prim) {
case ID: case EQ: case NE:
assert allArgs.length == 2;
Tree unbox1 = unbox(allArgs[0]);
Tree unbox2 = unbox(allArgs[1]);
if (!getMaxType(unbox1, unbox2).isReferenceType()) {
allArgs[0] = unbox1;
allArgs[1] = unbox2;
genCompPrim(ctx, prim, allArgs, target, when);
} else {
genEqPrim(ctx, prim, allArgs, target, when);
}
return;
case LT: case LE: case GE: case GT:
assert allArgs.length == 2;
allArgs[0] = unbox(allArgs[0]);
genCompPrim(ctx, prim, allArgs, target, when);
return;
case ZNOT:
assert allArgs.length == 1;
genCond(ctx, unbox(allArgs[0]), target, !when);
return;
case ZOR:
case ZAND:
if (when ^ (prim == Primitive.ZAND)) {
// x || y jump if true -or- x && y jump if false
genCond(ctx, unbox(allArgs[0]), target, when);
genCond(ctx, allArgs[1], target, when);
} else {
// x || y jump if false -or- x && y jump if true
JCode.Label afterLabel = ctx.code.newLabel();
genCond(ctx, unbox(allArgs[0]), afterLabel, !when);
genCond(ctx, allArgs[1], target, when);
afterLabel.anchorToNext();
}
return;
}
}
}
// Default case: the condition is not a comparison or logical
// primitive.
genLoad(ctx, tree, JType.BOOLEAN);
if (when)
ctx.code.emitIFNE(target);
else
ctx.code.emitIFEQ(target);
}
protected Map/*<Primitive, Instruction>*/ arithPrimMap;
protected void addPrim(Primitive prim,
JOpcode z,
JOpcode i,
JOpcode l,
JOpcode f,
JOpcode d) {
arithPrimMap.put(prim, new JOpcode[] { z, i, l, f, d });
}
protected void initArithPrimMap() {
arithPrimMap = new HashMap();
/* boolean, int & al., long, float, double */
addPrim(Primitive.ADD,
null, JOpcode.IADD, JOpcode.LADD, JOpcode.FADD, JOpcode.DADD);
addPrim(Primitive.SUB,
null, JOpcode.ISUB, JOpcode.LSUB, JOpcode.FSUB, JOpcode.DSUB);
addPrim(Primitive.MUL,
null, JOpcode.IMUL, JOpcode.LMUL, JOpcode.FMUL, JOpcode.DMUL);
addPrim(Primitive.DIV,
null, JOpcode.IDIV, JOpcode.LDIV, JOpcode.FDIV, JOpcode.DDIV);
addPrim(Primitive.MOD,
null, JOpcode.IREM, JOpcode.LREM, JOpcode.FREM, JOpcode.DREM);
addPrim(Primitive.AND,
JOpcode.IAND, JOpcode.IAND, JOpcode.LAND, null, null);
addPrim(Primitive.OR,
JOpcode.IOR, JOpcode.IOR, JOpcode.LOR, null, null);
addPrim(Primitive.XOR,
JOpcode.IXOR, JOpcode.IXOR, JOpcode.LXOR, null, null);
addPrim(Primitive.LSL,
null, JOpcode.ISHL, JOpcode.LSHL, null, null);
addPrim(Primitive.LSR,
null, JOpcode.IUSHR, JOpcode.LUSHR, null, null);
addPrim(Primitive.ASR,
null, JOpcode.ISHR, JOpcode.LSHR, null, null);
addPrim(Primitive.POS,
null, null, null, null, null);
addPrim(Primitive.NEG,
null, JOpcode.INEG, JOpcode.LNEG, JOpcode.FNEG, JOpcode.DNEG);
}
/**
* Generate code for the given arithmetic primitive, applied on
* the given arguments.
*/
protected void genArithPrim(Context ctx,
Primitive prim,
Tree[] args,
JType resType,
JType expectedType)
throws JCode.OffsetTooBigException {
int arity = args.length;
int resTypeIdx = getTypeIndex(resType);
if ((prim == Primitive.LSL)
|| (prim == Primitive.LSR)
|| (prim == Primitive.ASR)) {
genLoad(ctx, args[0], resType);
genLoad(ctx, args[1], JType.INT);
} else {
for (int i = 0; i < arity; ++i)
genLoad(ctx, args[i], resType);
}
if (prim == Primitive.NOT) {
if (resType == JType.LONG) {
ctx.code.emitPUSH(-1L);
ctx.code.emitLXOR();
} else {
assert resType == JType.INT;
ctx.code.emitPUSH(-1);
ctx.code.emitIXOR();
}
} else {
assert arithPrimMap.containsKey(prim);
JOpcode primInst = ((JOpcode[])arithPrimMap.get(prim))[resTypeIdx];
if (primInst != null)
ctx.code.emit(primInst);
}
}
/** Variable in which temporary objects are stored by the
* implementation of == */
protected JLocalVariable eqEqTempVar;
/**
* Generate code for the given equality primitive, applied on the
* given arguments.
*/
protected void genEqPrim(Context ctx,
Primitive prim,
Tree[] args,
JCode.Label target,
boolean when)
throws JCode.OffsetTooBigException {
JType maxType = getMaxType(args);
assert maxType.isReferenceType(): args[0]+" - "+args[1]+" : "+maxType;
// Generate code for all arguments
for (int i = 0; i < args.length; ++i) genLoad(ctx, args[i], maxType);
if (prim == Primitive.ID) {
if (when) ctx.code.emitIF_ACMPEQ(target);
else ctx.code.emitIF_ACMPNE(target);
} else {
// Comparison between two references. We inline the code
// for the predefined (and final) "=="/"!=" operators,
// which check for null values and then forward the call
// to "equals". "==" could be defined as follows, if
// "null" was an object:
// final def ==(other: Any): boolean =
// if (this == null) other == null else this.equals(other)
assert prim == Primitive.EQ || prim == Primitive.NE;
if (eqEqTempVar == null || eqEqTempVar.getOwner() != ctx.method)
eqEqTempVar =
ctx.method.addNewLocalVariable(JObjectType.JAVA_LANG_OBJECT,
"eqEqTemp$");
ctx.code.emitSTORE(eqEqTempVar);
ctx.code.emitDUP();
JCode.Label ifNonNullLabel = ctx.code.newLabel();
ctx.code.emitIFNONNULL(ifNonNullLabel);
ctx.code.emitPOP();
ctx.code.emitLOAD(eqEqTempVar);
if (when ^ (prim != Primitive.EQ))
ctx.code.emitIFNULL(target);
else
ctx.code.emitIFNONNULL(target);
JCode.Label afterLabel = ctx.code.newLabel();
ctx.code.emitGOTO_maybe_W(afterLabel, ctx.useWideJumps);
ifNonNullLabel.anchorToNext();
ctx.code.emitLOAD(eqEqTempVar);
JMethodType equalsType =
new JMethodType(JType.BOOLEAN,
new JType[] { JObjectType.JAVA_LANG_OBJECT });
ctx.code.emitINVOKEVIRTUAL(JAVA_LANG_OBJECT, "equals", equalsType);
if (when ^ (prim != Primitive.EQ))
ctx.code.emitIFNE(target);
else
ctx.code.emitIFEQ(target);
afterLabel.anchorToNext();
}
}
/**
* Generate code for the given comparison primitive, applied on
* the given arguments.
*/
protected void genCompPrim(Context ctx,
Primitive prim,
Tree[] args,
JCode.Label target,
boolean when)
throws JCode.OffsetTooBigException {
JType maxType = getMaxType(args);
assert !maxType.isReferenceType(): args[0]+" - "+args[1]+" : "+maxType;
int maxTypeIdx = getTypeIndex(maxType);
int intTypeIdx = getTypeIndex(JType.INT);
boolean intCompareWithZero = false;
// Generate code for all arguments, while detecting
// comparisons with 0, which can be optimised.
for (int i = 0; i < args.length; ++i) {
boolean isIntZero = false;
if (maxTypeIdx <= intTypeIdx) {
switch (args[i]) {
case Literal(AConstant constant):
int intVal;
switch (constant) {
case BOOLEAN(boolean value):
intVal = value ? 1 : 0;
break;
case BYTE(byte value):
intVal = value;
break;
case SHORT(short value):
intVal = value;
break;
case CHAR(char value):
intVal = value;
break;
case INT(int value):
intVal = value;
break;
default:
throw Debug.abort("unknown literal", constant);
}
if (intVal == 0) {
isIntZero = true;
if (i == 0) prim = prim.swap();
}
}
}
if (intCompareWithZero || !isIntZero)
genLoad(ctx, args[i], maxType);
intCompareWithZero |= isIntZero;
}
if (maxTypeIdx <= intTypeIdx && !intCompareWithZero) {
// Comparison between ints, no zeros involved
switch (maybeNegatedPrim(prim, !when)) {
case LT: ctx.code.emitIF_ICMPLT(target); break;
case LE: ctx.code.emitIF_ICMPLE(target); break;
case EQ: ctx.code.emitIF_ICMPEQ(target); break;
case NE: ctx.code.emitIF_ICMPNE(target); break;
case GE: ctx.code.emitIF_ICMPGE(target); break;
case GT: ctx.code.emitIF_ICMPGT(target); break;
default: throw Debug.abort("unknown primitive", prim);
}
} else {
// Comparison between longs, floats or double, or between
// one int and zero.
switch (maxType.getTag()) {
case JType.T_LONG: ctx.code.emitLCMP(); break;
case JType.T_FLOAT: ctx.code.emitFCMPG(); break;
case JType.T_DOUBLE: ctx.code.emitDCMPG(); break;
default:
; // do nothing (int comparison with 0)
}
switch (maybeNegatedPrim(prim, !when)) {
case LT: ctx.code.emitIFLT(target); break;
case LE: ctx.code.emitIFLE(target); break;
case EQ: ctx.code.emitIFEQ(target); break;
case NE: ctx.code.emitIFNE(target); break;
case GE: ctx.code.emitIFGE(target); break;
case GT: ctx.code.emitIFGT(target); break;
default: throw Debug.abort("unknown primitive", prim);
}
}
}
/**
* Generate code to throw the value returned by the argument.
*/
protected void genThrow(Context ctx, Tree arg)
throws JCode.OffsetTooBigException {
genLoad(ctx, arg, JAVA_LANG_OBJECT_T);
ctx.code.emitCHECKCAST(JAVA_LANG_THROWABLE_T);
ctx.code.emitATHROW();
}
/**
* Generate code to synchronise on the object and evaluate the
* code fragment.
*/
protected void genSynchronized(Context ctx,
Tree object,
Tree code,
JType expectedType)
throws JCode.OffsetTooBigException {
JLocalVariable monitorVar =
ctx.method.addNewLocalVariable(JAVA_LANG_OBJECT_T, "monitor");
genLoad(ctx, object, JAVA_LANG_OBJECT_T);
ctx.code.emitSTORE(monitorVar);
ctx.code.emitLOAD(monitorVar);
ctx.code.emitMONITORENTER();
int startPC = ctx.code.getPC();
genLoad(ctx, code, expectedType);
int endPC = ctx.code.getPC();
ctx.code.emitLOAD(monitorVar);
ctx.code.emitMONITOREXIT();
JCode.Label afterLabel = ctx.code.newLabel();
ctx.code.emitGOTO(afterLabel);
int handlerPC = ctx.code.getPC();
ctx.code.emitLOAD(monitorVar);
ctx.code.emitMONITOREXIT();
ctx.code.emitATHROW();
afterLabel.anchorToNext();
ctx.code.addFinallyHandler(startPC, endPC, handlerPC);
}
/// Arrays
//////////////////////////////////////////////////////////////////////
/**
* Generate code to create an array of some basic type, whose size
* will be dynamically computed.
*/
protected void genArrayCreate(Context ctx, Primitive prim, Tree size)
throws JCode.OffsetTooBigException {
genLoad(ctx, size, JType.INT);
JType type;
switch (prim) {
case NEW_ZARRAY : type = JType.BOOLEAN; break;
case NEW_BARRAY : type = JType.BYTE; break;
case NEW_SARRAY : type = JType.SHORT; break;
case NEW_CARRAY : type = JType.CHAR; break;
case NEW_IARRAY : type = JType.INT; break;
case NEW_LARRAY : type = JType.LONG; break;
case NEW_FARRAY : type = JType.FLOAT; break;
case NEW_DARRAY : type = JType.DOUBLE; break;
default: throw Debug.abort("unexpected primitive", prim);
}
ctx.code.emitNEWARRAY(type);
}
/**
* Generate code to create an array of references, whose size will
* be dynamically computed.
*/
protected void genRefArrayCreate(Context ctx, Tree size, Tree classNameLit)
throws JCode.OffsetTooBigException {
genLoad(ctx, size, JType.INT);
String className;
switch (classNameLit) {
case Literal(STRING(String name)): className = name; break;
default: throw Debug.abort("invalid argument for oarray", classNameLit);
}
JReferenceType elemType;
switch (className.charAt(0)) {
case '[': case 'L':
elemType = (JReferenceType)JType.parseSignature(className); break;
default:
elemType = new JObjectType(className);
}
ctx.code.emitANEWARRAY(elemType);
}
/**
* Generate code to update an array.
*/
protected void genArrayUpdate(Context ctx, Tree array, Tree index, Tree value)
throws JCode.OffsetTooBigException {
genLoad(ctx, array, JAVA_LANG_OBJECT_T);
genLoad(ctx, index, JType.INT);
JType elemType = getArrayElementType(array);
if (elemType.isValueType())
value = unbox(value);
genLoad(ctx, value, elemType);
ctx.code.emitASTORE(elemType);
}
/**
* Generate code to load an element of an array.
*/
protected void genArrayAccess(Context ctx, Tree array, Tree index)
throws JCode.OffsetTooBigException {
genLoad(ctx, array, JAVA_LANG_OBJECT_T);
genLoad(ctx, index, JType.INT);
ctx.code.emitALOAD(getArrayElementType(array));
}
/**
* Generate code to load the length of an array.
*/
protected void genArrayLength(Context ctx, Tree array)
throws JCode.OffsetTooBigException {
genLoad(ctx, array, JAVA_LANG_OBJECT_T);
ctx.code.emitARRAYLENGTH();
}
/**
* Return the Java type of the elements of the array represented
* by the given tree.
*/
protected JType getArrayElementType(Tree array) {
JArrayType arrayType = (JArrayType)typeStoJ(array.type);
return arrayType.getElementType();
}
/// String concatenation
//////////////////////////////////////////////////////////////////////
protected Tree[] liftStringConcatenations(Tree tree) {
LinkedList accu = new LinkedList();
liftStringConcatenations(tree, accu);
return (Tree[])accu.toArray(new Tree[accu.size()]);
}
protected void liftStringConcatenations(Tree tree, LinkedList accu) {
switch (tree) {
case Apply(Select(Tree qualifier, Name selector), Tree[] args): {
Symbol funSym = ((Tree.Apply)tree).fun.symbol();
if (prims.isPrimitive(funSym)
&& prims.getPrimitive(funSym) == Primitive.CONCAT) {
liftStringConcatenations(qualifier, accu);
liftStringConcatenations(args[0], accu);
} else
accu.addLast(tree);
} break;
default:
accu.addLast(tree);
}
}
/**
* Generate code to concatenate a list of expressions which return
* strings.
*/
protected void genStringConcatenation(Context ctx, Tree[] elements)
throws JCode.OffsetTooBigException {
// Create string buffer
ctx.code.emitNEW(JAVA_LANG_STRINGBUFFER);
ctx.code.emitDUP();
ctx.code.emitINVOKESPECIAL(JAVA_LANG_STRINGBUFFER,
"<init>",
JMethodType.ARGLESS_VOID_FUNCTION);
// Append all strings
for (int i = 0; i < elements.length; ++i) {
JType elemType = typeStoJ(elements[i].type);
if (!elemType.equals(JObjectType.JAVA_LANG_STRING)
&& elemType.isReferenceType())
elemType = JObjectType.JAVA_LANG_OBJECT;
genLoad(ctx, elements[i], elemType);
ctx.code.emitINVOKEVIRTUAL(JAVA_LANG_STRINGBUFFER,
"append",
new JMethodType(JAVA_LANG_STRINGBUFFER_T,
new JType[] { elemType }));
}
// Get resulting string
ctx.code.emitINVOKEVIRTUAL(JAVA_LANG_STRINGBUFFER,
"toString",
new JMethodType(JObjectType.JAVA_LANG_STRING,
JType.EMPTY_ARRAY));
}
/// Primitives
//////////////////////////////////////////////////////////////////////
/**
* Return true iff the given symbol is a primitive, AND that
* primitive is recognized by this back-end, AND that primitive is
* a "jumping" one.
*/
protected boolean isJumpingPrimitive(Symbol sym) {
if (prims.isPrimitive(sym)) {
switch (prims.getPrimitive(sym)) {
case ID : case EQ : case NE :
case LT : case LE : case GE : case GT :
case ZNOT : case ZOR : case ZAND :
return true;
}
}
return false;
}
/**
* Return true iff the given symbol is a primitive, AND that
* primitive is recognized by this back-end.
*/
protected boolean isKnownPrimitive(Symbol sym) {
if (isJumpingPrimitive(sym))
return true;
if (prims.isPrimitive(sym)) {
switch (prims.getPrimitive(sym)) {
case POS : case NEG :
case ADD : case SUB : case MUL : case DIV : case MOD :
case NOT : case OR : case XOR : case AND :
case LSL : case LSR : case ASR :
case NEW_ZARRAY : case NEW_BARRAY : case NEW_SARRAY :
case NEW_CARRAY : case NEW_IARRAY : case NEW_LARRAY :
case NEW_FARRAY : case NEW_DARRAY : case NEW_OARRAY :
case ZARRAY_GET : case BARRAY_GET : case SARRAY_GET :
case CARRAY_GET : case IARRAY_GET : case LARRAY_GET :
case FARRAY_GET : case DARRAY_GET : case OARRAY_GET :
case ZARRAY_SET : case BARRAY_SET : case SARRAY_SET :
case CARRAY_SET : case IARRAY_SET : case LARRAY_SET :
case FARRAY_SET : case DARRAY_SET : case OARRAY_SET :
case ZARRAY_LENGTH : case BARRAY_LENGTH : case SARRAY_LENGTH :
case CARRAY_LENGTH : case IARRAY_LENGTH : case LARRAY_LENGTH :
case FARRAY_LENGTH : case DARRAY_LENGTH : case OARRAY_LENGTH :
case IS : case AS : case ID :
case CONCAT : case THROW : case SYNCHRONIZED:
case B2B: case B2S: case B2C: case B2I: case B2L: case B2F: case B2D:
case S2B: case S2S: case S2C: case S2I: case S2L: case S2F: case S2D:
case C2B: case C2S: case C2C: case C2I: case C2L: case C2F: case C2D:
case I2B: case I2S: case I2C: case I2I: case I2L: case I2F: case I2D:
case L2B: case L2S: case L2C: case L2I: case L2L: case L2F: case L2D:
case F2B: case F2S: case F2C: case F2I: case F2L: case F2F: case F2D:
case D2B: case D2S: case D2C: case D2I: case D2L: case D2F: case D2D:
return true;
case EQUALS :
case HASHCODE :
case TOSTRING :
case COERCE :
case BOX :
case UNBOX :
case APPLY : case UPDATE : case LENGTH :
return false;
default:
throw Debug.abort("unknown primitive", sym);
}
} else
return false;
}
/**
* Negate the given primitive only if the second argument is
* true, otherwise return it as is.
*/
protected Primitive maybeNegatedPrim(Primitive prim, boolean negate) {
return negate ? prim.negate() : prim;
}
/**
* Return all the arguments associated with the primitive
* represented by the given function call.
*/
protected Tree[] extractPrimitiveArgs(Tree.Apply call) {
Tree[] allArgs = Tree.cloneArray(1, call.args);
allArgs[0] = ((Tree.Select)(call.fun)).qualifier;
return allArgs;
}
/**
* Return the unboxed version of the given tree.
*/
protected Tree unbox(Tree tree) {
switch (tree) {
case Apply(Tree fun, Tree[] args):
if (prims.getPrimitive(fun.symbol()) == Primitive.BOX) {
assert args.length == 1;
return args[0];
} else
return tree;
default:
return tree;
}
}
/// Modules
//////////////////////////////////////////////////////////////////////
/**
* Add field containing module instance, and code to initialize
* it, to current class.
*/
protected void addModuleInstanceField(Context ctx) {
ctx.clazz.addNewField(JAccessFlags.ACC_PUBLIC
| JAccessFlags.ACC_FINAL
| JAccessFlags.ACC_STATIC,
MODULE_INSTANCE_FIELD_NAME,
ctx.clazz.getType());
ctx.code.emitNEW(ctx.clazz.getName());
ctx.code.emitINVOKESPECIAL(ctx.clazz.getName(),
CONSTRUCTOR_STRING,
JMethodType.ARGLESS_VOID_FUNCTION);
// The field is initialised by the constructor, so we don't
// need to do it here, creating the instance is sufficient.
}
protected JMethod addNewScalaMethod(JClass clazz,
Symbol method,
int addFlags) {
JMethodType methodType = (JMethodType)typeStoJ(method.type());
Symbol[] params = method.valueParams();
String[] argNames = new String[params.length];
for (int i = 0; i < argNames.length; ++i)
argNames[i] = params[i].name.toString();
return clazz.addNewMethod(javaModifiers(method) | addFlags,
method.name.toString(),
methodType.getReturnType(),
methodType.getArgumentTypes(),
argNames);
}
/**
* Create a class which mirrors all public methods of the given
* module class as static methods, to enable the use of the module
* from Java.
*/
protected void dumpModuleMirrorClass(Context ctx, Symbol cSym, Pickle pickle) {
String mainName = javaName(cSym);
String mirrorName = mainName.substring(0, mainName.length() - 1);
JClass mirrorClass = fjbgContext.JClass(JAccessFlags.ACC_SUPER
| JAccessFlags.ACC_PUBLIC
| JAccessFlags.ACC_FINAL,
mirrorName,
JAVA_LANG_OBJECT,
JClass.NO_INTERFACES,
ctx.sourceFileName);
Scope.SymbolIterator memberIt =
cSym.members().iterator();
while (memberIt.hasNext()) {
Symbol member = memberIt.next();
if (!member.isMethod()
|| member.isInitializer()
|| member.isStatic())
continue;
JMethod mirrorMeth =
addNewScalaMethod(mirrorClass, member, JAccessFlags.ACC_STATIC);
JExtendedCode mirrorCode = (JExtendedCode)mirrorMeth.getCode();
mirrorCode.emitGETSTATIC(mainName,
MODULE_INSTANCE_FIELD_NAME,
new JObjectType(mainName));
JType[] argTypes = mirrorMeth.getArgumentTypes();
for (int index = 0, i = 0; i < argTypes.length; ++i) {
mirrorCode.emitLOAD(index, argTypes[i]);
index += argTypes[i].getSize();
}
mirrorCode.emitINVOKEVIRTUAL(mainName,
mirrorMeth.getName(),
(JMethodType)mirrorMeth.getType());
mirrorCode.emitRETURN(mirrorMeth.getReturnType());
mirrorCode.setLineNumber(0,
mirrorCode.getPC(),
Position.line(member.pos));
}
addScalaAttr(mirrorClass, pickle);
writeClassFile(mirrorClass);
}
/**
* Add the "Scala" attribute to the given class, in which the
* symbol table is saved.
*/
protected void addScalaAttr(JClass cls, Pickle pickle) {
pickles.add(cls);
pickles.add(pickle);
JOtherAttribute scalaAttr =
fjbgContext.JOtherAttribute(cls,
cls,
SCALA_ATTR,
pickle.bytes,
pickle.size());
cls.addAttribute(scalaAttr);
}
/// Names
//////////////////////////////////////////////////////////////////////
protected HashMap nameMap/*<Symbol,String>*/ = new HashMap();
/**
* Return a Java-compatible version of the name of the given
* symbol. The returned name is mangled and includes the names of
* the owners.
*/
protected String javaName(Symbol sym) {
Object value = nameMap.get(sym);
if (value != null) return (String)value;
String name = prims.getJREClassName(sym);
nameMap.put(sym, name);
return name;
}
/// Types
//////////////////////////////////////////////////////////////////////
/**
* Return the Java modifiers for the given Scala symbol.
*/
protected int javaModifiers(Symbol sym) {
int flags = sym.flags;
int jFlags = 0;
if (Modifiers.Helper.isPrivate(flags))
jFlags |= JAccessFlags.ACC_PRIVATE;
else
jFlags |= JAccessFlags.ACC_PUBLIC;
if (Modifiers.Helper.isAbstract(flags))
jFlags |= JAccessFlags.ACC_ABSTRACT;
if (Modifiers.Helper.isInterface(flags))
jFlags |= JAccessFlags.ACC_INTERFACE;
if (Modifiers.Helper.isFinal(flags)
&& !(Modifiers.Helper.isAbstract(flags)
|| Modifiers.Helper.isInterface(flags)))
jFlags |= JAccessFlags.ACC_FINAL;
if (sym.isStatic())
jFlags |= JAccessFlags.ACC_STATIC;
return jFlags;
}
protected HashMap typeMap/*<Symbol,Type>*/ = new HashMap();
protected void initTypeMap() {
typeMap.put(defs.ANY_CLASS, JObjectType.JAVA_LANG_OBJECT);
typeMap.put(defs.ANYREF_CLASS, JObjectType.JAVA_LANG_OBJECT);
}
/**
* Return the Java type corresponding to the given Scala type.
*/
protected JType typeStoJ(Type tp) {
switch (tp) {
case ConstantType(Type base, _):
return typeStoJ(base);
case TypeRef(_, Symbol sym, _):
Object value = typeMap.get(sym);
if (value != null) return (JType)value;
JType jTp = new JObjectType(javaName(sym));
typeMap.put(sym, jTp);
return jTp;
case UnboxedType(TypeTags.BYTE):
return JType.BYTE;
case UnboxedType(TypeTags.CHAR):
return JType.CHAR;
case UnboxedType(TypeTags.SHORT):
return JType.SHORT;
case UnboxedType(TypeTags.INT):
return JType.INT;
case UnboxedType(TypeTags.LONG):
return JType.LONG;
case UnboxedType(TypeTags.FLOAT):
return JType.FLOAT;
case UnboxedType(TypeTags.DOUBLE):
return JType.DOUBLE;
case UnboxedType(TypeTags.BOOLEAN):
return JType.BOOLEAN;
case UnboxedType(TypeTags.UNIT):
return JType.VOID;
case UnboxedType(TypeTags.STRING):
return JObjectType.JAVA_LANG_STRING;
case UnboxedArrayType(Type elementType):
return new JArrayType(typeStoJ(elementType));
case MethodType(Symbol[] vparams, Type result):
JType[] argTypes = new JType[vparams.length];
for (int i = 0; i < vparams.length; ++i)
argTypes[i] = typeStoJ(vparams[i].info());
return new JMethodType(typeStoJ(result), argTypes);
default:
throw Debug.abort("invalid type", tp);
}
}
/**
* Return the "index" of the given type. This index encodes the
* level in the hierarchy of basic types, with arrays and objects
* on top of everything.
*/
protected int getTypeIndex(JType tp) {
return getTypeIndex(tp.getTag());
}
/**
* Return the "index" of the given type.
*/
protected int getTypeIndex(int tp) {
switch (tp) {
case JType.T_BOOLEAN: return 0;
case JType.T_BYTE:
case JType.T_CHAR:
case JType.T_SHORT:
case JType.T_INT: return 1;
case JType.T_LONG: return 2;
case JType.T_FLOAT: return 3;
case JType.T_DOUBLE: return 4;
case JType.T_ARRAY:
case JType.T_OBJECT: return 5;
default: return -1;
}
}
/**
* Return the maximum of the types of all the given trees. All
* reference types are considered to be equivalent, and if several
* reference types are present in the trees, any one of them is
* returned.
*/
protected JType getMaxType(Tree[] trees) {
JType maxType = JType.BOOLEAN;
int maxTypeIdx = getTypeIndex(maxType);
for (int i = 0; i < trees.length; ++i) {
JType argType = typeStoJ(trees[i].type);
if (getTypeIndex(argType) > maxTypeIdx) {
maxType = argType;
maxTypeIdx = getTypeIndex(maxType);
}
}
return maxType;
}
protected JType getMaxType(Tree tree1, Tree tree2) {
JType type1 = typeStoJ(tree1.type);
JType type2 = typeStoJ(tree2.type);
return getTypeIndex(type1) > getTypeIndex(type2) ? type1 : type2;
}
/// Line numbers
//////////////////////////////////////////////////////////////////////
int[] pcStack = new int[32];
int pcStackDepth = 0;
void startCodeForTree(Context ctx, Tree tree) {
if (pcStackDepth == pcStack.length) {
int[] newPCStack = new int[pcStack.length * 2];
System.arraycopy(pcStack, 0, newPCStack, 0, pcStack.length);
pcStack = newPCStack;
}
pcStack[pcStackDepth++] = (ctx.code == null ? 0 : ctx.code.getPC());
}
void endCodeForTree(Context ctx, Tree tree) {
assert pcStackDepth > 0;
int startPC = pcStack[--pcStackDepth];
if (ctx.code != null)
ctx.code.completeLineNumber(startPC,
ctx.code.getPC(),
Position.line(tree.pos));
}
protected void genLocalVariableTable(Context ctx) {
JLocalVariable[] vars = ctx.method.getLocalVariables();
if (!global.debuginfo || vars.length == 0)
return;
JConstantPool pool = ctx.clazz.getConstantPool();
int pc = ctx.code.getPC();
int anonCounter = 1;
ByteBuffer lvTab = ByteBuffer.allocate(2 + 10 * vars.length);
lvTab.putShort((short)vars.length);
for (int i = 0; i < vars.length; i++) {
JLocalVariable lv = vars[i];
String name = (lv.getName() == null)
? "<anon" + (anonCounter++) + ">" : lv.getName();
lvTab.putShort((short)0);
lvTab.putShort((short)pc);
lvTab.putShort((short)pool.addUtf8(name));
lvTab.putShort((short)pool.addUtf8(lv.getType().getSignature()));
lvTab.putShort((short)lv.getIndex());
}
JAttribute attr =
fjbgContext.JOtherAttribute(ctx.clazz,
ctx.method,
"LocalVariableTable",
lvTab.array());
ctx.code.addAttribute(attr);
}
/// Context
//////////////////////////////////////////////////////////////////////
/**
* Record the entry into a class, and return the appropriate
* context.
*/
protected Context enterClass(Context ctx, Symbol cSym) {
String javaName = javaName(cSym);
scalac.symtab.Type[] baseTps = cSym.info().parents();
assert baseTps.length > 0 : Debug.show(cSym);
int offset;
String superClassName;
if (cSym.isInterface()) {
offset = baseTps[0].symbol() == defs.ANY_CLASS ? 1 : 0;
superClassName = JAVA_LANG_OBJECT;
} else {
offset = 1;
superClassName = javaName(baseTps[0].symbol());
}
String[] interfaceNames = new String[baseTps.length - offset];
for (int i = offset; i < baseTps.length; ++i) {
Symbol baseSym = baseTps[i].symbol();
assert baseSym.isInterface() : cSym + " implements " + baseSym;
interfaceNames[i - offset] = javaName(baseSym);
}
JClass cls = fjbgContext.JClass(javaModifiers(cSym)
| JAccessFlags.ACC_SUPER,
javaName,
superClassName,
interfaceNames,
ctx.sourceFileName);
return ctx.withClass(cls,
cSym.isModuleClass() && ctx.clazz == null,
cSym.isSubClass(JAVA_RMI_REMOTE_CLASS));
}
protected void leaveClass(Context ctx, Symbol cSym) {
JClass clazz = ctx.clazz;
Pickle pickle = (Pickle)global.symdata.get(cSym);
if (pickle != null)
if (ctx.isModuleClass)
dumpModuleMirrorClass(ctx, cSym, pickle);
else
addScalaAttr(clazz, pickle);
writeClassFile(clazz);
}
/**
* Record the entry into a method, and return the appropriate
* context.
*/
protected Context enterMethod(Context ctx,
Tree.DefDef mDef,
boolean useWideJumps) {
Symbol mSym = mDef.symbol();
global.log("entering method " + Debug.show(mSym)
+ " (type: " + Debug.show(mSym.info()) + ")"
+ " wide jumps? " + useWideJumps);
JMethod method = addNewScalaMethod(ctx.clazz, mSym, 0);
Map locals = new HashMap();
Symbol[] args = mSym.valueParams();
JType[] argTypes = method.getArgumentTypes();
int firstPos = mSym.isStatic() ? 0 : 1;
for (int i = 0, pos = firstPos; i < argTypes.length; ++i) {
locals.put(args[i], new Integer(pos));
pos += argTypes[i].getSize();
}
if ((mSym.flags & Modifiers.BRIDGE) != 0)
method.addAttribute(fjbgContext.JOtherAttribute(ctx.clazz,
method,
"Bridge",
new byte[]{}));
if (ctx.isRemote && mSym.isPublic()) {
// (see http://java.sun.com/docs/books/vmspec/html/ClassFile.doc.html#3129)
// Exceptions_attribute {
// ..
// u2 number_of_exceptions;
// u2 exception_index_table[number_of_exceptions];
// }
JConstantPool cp = ctx.clazz.getConstantPool();
int reInx = cp.addClass(JAVA_RMI_REMOTEEXCEPTION);
ByteBuffer contents = ByteBuffer.allocate(4); // u2 + u2[1]
contents.putShort((short)1);
contents.putShort((short)reInx);
global.log("adding 'Exceptions_attribute' " + contents.toString()
+ " for remote method " + mSym.name.toString());
method.addAttribute(fjbgContext.JOtherAttribute(ctx.clazz,
method,
"Exceptions",
contents.array()));
}
return ctx.withMethod(method, locals, useWideJumps);
}
protected void leaveMethod(Context ctx) {
genLocalVariableTable(ctx);
global.log("leaving method");
}
/// I/O
//////////////////////////////////////////////////////////////////////
/** Writes the given class to a file. */
protected void writeClassFile(JClass clazz) {
File file = getFile(clazz, ".class");
try {
clazz.writeTo(file);
global.operation("wrote " + file);
} catch (IOException exception) {
if (global.debug) exception.printStackTrace();
global.error("could not write file " + file);
}
}
/** Writes the given pickle for given class to a file. */
protected void writeSymblFile(JClass clazz, Pickle pickle) {
File file = getFile(clazz, ".symbl");
try {
pickle.writeTo(file);
global.operation("wrote " + file);
} catch (IOException exception) {
if (global.debug) exception.printStackTrace();
global.error("could not write file " + file);
}
}
/** Returns the file with the given suffix for the given class. */
protected File getFile(JClass clazz, String suffix) {
String path = clazz.getName().replace('.', File.separatorChar);
return new File(global.outpath + File.separatorChar + path + suffix);
}
/// Misc.
//////////////////////////////////////////////////////////////////////
private void completeClassConstructor(Context ctx, Symbol classSym) {
if (ctx.isModuleClass)
addModuleInstanceField(ctx);
addStaticClassMembers(ctx, classSym);
}
/**
* Return the class constructor method of the given class.
*/
private JMethod getClassConstructorMethod(Context ctx) {
JMethod[] methods = ctx.clazz.getMethods();
JMethod clinit = null;
for (int i = 0; i < methods.length; ++i) {
if (methods[i].getName().equals("<clinit>")) {
clinit = methods[i];
break;
}
}
return clinit != null
? clinit
: ctx.clazz.addNewMethod(JAccessFlags.ACC_PUBLIC
| JAccessFlags.ACC_STATIC,
"<clinit>",
JType.VOID,
JType.EMPTY_ARRAY,
Strings.EMPTY_ARRAY);
}
/**
* Add value members (i.e. fields) to current class.
*/
protected void addValueClassMembers(Context ctx, Tree.ClassDef cDef) {
Symbol cSym = cDef.symbol();
Scope.SymbolIterator memberIt =
cSym.members().iterator();
while (memberIt.hasNext()) {
Symbol member = memberIt.next();
if (member.isTerm() && !member.isMethod())
ctx.clazz.addNewField(javaModifiers(member),
member.name.toString(),
typeStoJ(member.info()));
}
}
// The following function is a single big hack.
protected void addStaticClassMembers(Context ctx, Symbol cSym) {
HashMap/*<Symbol, AConstant>*/ staticMembers = new HashMap();
Symbol iSym = ctx.isModuleClass
? cSym : addInterfacesPhase.getInterfaceSymbol(cSym);
if (iSym != null) {
// Compute the list of static members to add.
Phase bkpCurrent = global.currentPhase;
global.currentPhase = refCheckPhase;
Scope.SymbolIterator memberIt =
iSym.members().iterator();
while (memberIt.hasNext()) {
Symbol member = memberIt.next();
if (member.isTerm() && !member.isMethod() && member.isPrivate())
switch (member.info()) {
case ConstantType(_, AConstant value):
staticMembers.put(member, value);
}
}
global.currentPhase = bkpCurrent;
// Add them and initialize them.
Iterator smIt = staticMembers.keySet().iterator();
while (smIt.hasNext()) {
Symbol sm = (Symbol)smIt.next();
String smName = sm.name.toString();
JType tp = typeStoJ(sm.info());
JField field =
ctx.clazz.addNewField((javaModifiers(sm)
| JAccessFlags.ACC_STATIC
| JAccessFlags.ACC_PUBLIC)
& ~JAccessFlags.ACC_PRIVATE,
smName.substring(0,
smName.length()-1),
tp);
genLoadLiteral(ctx, (AConstant)staticMembers.get(sm), tp);
ctx.code.emitPUTSTATIC(ctx.clazz.getName(),
field.getName(),
tp);
}
}
}
/**
* Return true iff the given symbol is a static (in the Java
* sense) member of its owner.
*/
protected boolean isStaticMember(Symbol sym) {
return sym.isStatic();
}
}
/**
* A compilation context, which records information about the class
* and the method currently being generated.
*/
class Context {
public final String sourceFileName;
public final JClass clazz;
public final JMethod method;
public final JExtendedCode code;
public final Map/*<Symbol,JLocalVariable>*/ locals;
public final Map/*<Symbol,Pair<JCode.Label,Tree[]>>*/ labels;
public final boolean useWideJumps;
public final boolean isModuleClass;
public final boolean isRemote;
public final static Context EMPTY =
new Context(null, null, null, null, null, false, false, false);
private Context(String sourceFileName,
JClass clazz,
JMethod method,
Map locals,
Map labels,
boolean useWideJumps,
boolean isModuleClass,
boolean isRemote) {
this.sourceFileName = sourceFileName;
this.clazz = clazz;
this.method = method;
if (method == null || method.isAbstract())
this.code = null;
else
this.code = (JExtendedCode)method.getCode();
this.locals = locals;
this.labels = labels;
this.useWideJumps = useWideJumps;
this.isModuleClass = isModuleClass;
this.isRemote = isRemote;
}
public Context withSourceFileName(String sourceFileName) {
return new Context(sourceFileName,
null,
null,
null,
null,
false,
false,
false);
}
public Context withClass(JClass clazz, boolean isModuleClass, boolean isRemote) {
return new Context(this.sourceFileName,
clazz,
null,
null,
null,
false,
isModuleClass,
isRemote);
}
public Context withMethod(JMethod method, Map locals, boolean useWideJumps) {
assert this.clazz == method.getOwner();
return new Context(this.sourceFileName,
this.clazz,
method,
locals,
new HashMap(),
useWideJumps,
this.isModuleClass,
this.isRemote);
}
}
|