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
|
/* NSC -- new scala compiler
* Copyright 2005 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
package scala.tools.nsc.backend.jvm;
import java.io.File;
import java.nio.ByteBuffer;
import scala.collection.mutable.{Map, HashMap};
import scala.tools.nsc.symtab._;
import scala.tools.nsc.util.Position;
import ch.epfl.lamp.fjbg._;
/**
*/
abstract class GenJVM extends SubComponent {
import global._;
import icodes._;
import icodes.opcodes._;
val phaseName = "jvm";
/** Create a new phase */
override def newPhase(p: Phase) = new JvmPhase(p);
/** JVM code generation phase
*/
class JvmPhase(prev: Phase) extends GlobalPhase(prev) {
def name = phaseName;
override def newFlags = phaseNewFlags;
override def erasedTypes = true;
val codeGenerator = new BytecodeGenerator;
override def run: Unit = {
if (settings.debug.value) inform("[running phase " + name + " on icode]");
classes.values foreach codeGenerator.genClass;
}
override def apply(unit: CompilationUnit): Unit =
abort("JVM works on icode classes, not on compilation units!");
}
var pickledBytes = 0 // statistics
/**
* Java bytecode generator.
*
*/
class BytecodeGenerator {
val MIN_SWITCH_DENSITY = 0.7;
val MODULE_INSTANCE_NAME = "MODULE$";
val JAVA_LANG_STRINGBUFFER = "java.lang.StringBuffer";
val JAVA_RMI_REMOTEEXCEPTION = "java.rmi.RemoteException";
val stringBufferType = new JObjectType(JAVA_LANG_STRINGBUFFER);
val toStringType = new JMethodType(JObjectType.JAVA_LANG_STRING, JType.EMPTY_ARRAY);
// Scala attributes
val SerializableAttr = definitions.SerializableAttr.tpe;
val SerialVersionUID = definitions.getClass("scala.SerialVersionUID").tpe;
val CloneableAttr = definitions.getClass("scala.cloneable").tpe;
val TransientAtt = definitions.getClass("scala.transient").tpe;
val VolatileAttr = definitions.getClass("scala.volatile").tpe;
val RemoteAttr = definitions.getClass("scala.remote").tpe;
val ThrowsAttr = definitions.getClass("scala.throws").tpe
val CloneableClass = if (forCLDC) null else definitions.getClass("java.lang.Cloneable");
val RemoteInterface = if (forCLDC) null else definitions.getClass("java.rmi.Remote");
var clasz: IClass = _;
var method: IMethod = _;
var code: Code = _;
var jclass: JClass = _;
var jmethod: JMethod = _;
var jcode: JExtendedCode = _;
val fjbgContext = if (settings.target.value == "jvm-1.5") new FJBGContext(49, 0) else new FJBGContext();
def emitClass(jclass: JClass, sym: Symbol): Unit = {
def addScalaAttr(sym: Symbol): Unit = currentRun.symData.get(sym) match {
case Some(pickle) =>
val scalaAttr = fjbgContext.JOtherAttribute(jclass,
jclass,
nme.ScalaSignatureATTR.toString(),
pickle.bytes,
pickle.writeIndex);
pickledBytes = pickledBytes + pickle.writeIndex;
jclass.addAttribute(scalaAttr);
currentRun.symData -= sym;
currentRun.symData -= sym.linkedSym;
//System.out.println("Generated ScalaSig Attr for " + sym);//debug
case _ =>
log("Could not find pickle information for " + sym);
}
if (!(jclass.getName().endsWith("$") && sym.isModuleClass))
addScalaAttr(if (isTopLevelModule(sym)) sym.sourceModule else sym);
val outfile = getFile(jclass, ".class");
jclass.writeTo(outfile);
val file = scala.tools.nsc.io.AbstractFile.getFile(outfile);
informProgress("wrote " + outfile + " " +
(if (file != null) "" + file.file + " " + file.file.exists()
else "no file"));
}
var serialVUID: Option[Long] = None;
var remoteClass: Boolean = false;
def genClass(c: IClass): Unit = {
if (settings.debug.value)
log("Generating class " + c.symbol + " flags: " + Flags.flagsToString(c.symbol.flags));
clasz = c;
var parents = c.symbol.info.parents;
var ifaces = JClass.NO_INTERFACES;
val name = javaName(c.symbol);
serialVUID = None;
remoteClass = false;
if (parents.isEmpty)
parents = definitions.ObjectClass.tpe :: parents;
c.symbol.attributes foreach { a => a match {
case Pair(SerializableAttr, _) if (!forCLDC) =>
parents = parents ::: List(definitions.SerializableClass.tpe);
case Pair(CloneableAttr, _) if (!forCLDC) =>
parents = parents ::: List(CloneableClass.tpe);
case Pair(SerialVersionUID, value :: _) if (!forCLDC) =>
serialVUID = Some(value.longValue);
case Pair(RemoteAttr, _) if (!forCLDC) =>
parents = parents ::: List(RemoteInterface.tpe);
remoteClass = true;
case _ => ();
}
}
parents = parents.removeDuplicates;
if (parents.length > 1 ) {
ifaces = new Array[String](parents.length - 1);
parents.drop(1).map((s) => javaName(s.symbol)).copyToArray(ifaces, 0);
()
}
jclass = fjbgContext.JClass(javaFlags(c.symbol),
name,
javaName(parents(0).symbol),
ifaces,
c.cunit.source.toString());
if (isStaticModule(c.symbol) || serialVUID != None) {
if (isStaticModule(c.symbol))
addModuleInstanceField;
addStaticInit(jclass);
if (isTopLevelModule(c.symbol)) {
if (c.symbol.linkedClass == NoSymbol)
dumpMirrorClass;
else if (c.symbol.linkedClass != NoSymbol &&
!currentRun.compiles(c.symbol.linkedClass)) {
log("Dumping mirror class for " + c.symbol + " even though linked class exists, but is not compiled in this run");
dumpMirrorClass;
} else
log("No mirror class for module with linked class: " + c.symbol.fullNameString);
}
}
clasz.fields foreach genField;
clasz.methods foreach genMethod;
addAttributes(jclass, c.symbol.attributes);
emitClass(jclass, c.symbol)
}
def addExceptionsAttribute(jm: JMethod, throws: List[AttrInfo]): Unit = {
if (throws.forall(a => a match {
case Pair(ThrowsAttr, _) => false
case _ => true
})) return;
val cpool = jm.getConstantPool();
val buf: ByteBuffer = ByteBuffer.allocate(512);
var nattr = 0;
// put some radom value; the actual number is determined at the end
buf.putShort(0xbaba.toShort)
for (val Pair(ThrowsAttr, List(exc)) <- throws) {
buf.putShort(cpool.addClass(exc.typeValue.toString()).shortValue)
nattr = nattr + 1;
}
assert (nattr > 0);
val length = buf.position();
buf.putShort(0, nattr.toShort)
val arr = buf.array().subArray(0, length);
val attr = jm.getContext().JOtherAttribute(jm.getJClass(), jm,
nme.ExceptionsATTR.toString(),
arr, length)
jm.addAttribute(attr)
}
def addAttributes(jmember: JMember, attributes: List[AttrInfo]): Unit = {
if (attributes.isEmpty) return;
val cpool = jmember.getConstantPool();
val buf: ByteBuffer = ByteBuffer.allocate(2048);
var nattr = 0;
// put some radom value; the actual number is determined at the end
buf.putShort(0xbaba.toShort)
for (val Pair(typ, consts) <- attributes; typ.symbol.hasFlag(Flags.JAVA)) {
nattr = nattr + 1;
val jtype = javaType(typ);
buf.putShort(cpool.addUtf8(jtype.getSignature()).toShort);
assert(consts.length == 1, consts.toString())
buf.putShort(1.toShort); // for now only 1 constructor parameter
buf.putShort(cpool.addUtf8("value").toShort);
for (val const <- consts) {
const.tag match {
case BooleanTag =>
buf.put('Z'.toByte)
buf.putShort(cpool.addInteger(if(const.booleanValue) 1 else 0).toShort)
case ByteTag =>
buf.put('B'.toByte)
buf.putShort(cpool.addInteger(const.byteValue).toShort)
case ShortTag =>
buf.put('S'.toByte)
buf.putShort(cpool.addInteger(const.shortValue).toShort)
case CharTag =>
buf.put('C'.toByte)
buf.putShort(cpool.addInteger(const.charValue).toShort)
case IntTag =>
buf.put('I'.toByte)
buf.putShort(cpool.addInteger(const.intValue).toShort)
case LongTag =>
buf.put('J'.toByte)
buf.putShort(cpool.addLong(const.longValue).toShort)
case FloatTag =>
buf.put('F'.toByte)
buf.putShort(cpool.addFloat(const.floatValue).toShort)
case DoubleTag =>
buf.put('D'.toByte)
buf.putShort(cpool.addDouble(const.doubleValue).toShort)
case StringTag =>
buf.put('s'.toByte)
buf.putShort(cpool.addUtf8(const.stringValue).toShort)
case ClassTag =>
buf.put('c'.toByte)
buf.putShort(cpool.addUtf8(javaType(const.typeValue).getSignature()).toShort)
case EnumTag =>
buf.put('e'.toByte)
buf.putShort(cpool.addUtf8(javaType(const.tpe).getSignature()).toShort)
buf.putShort(cpool.addUtf8(const.symbolValue.name.toString()).toShort)
//case NullTag => AllRefClass.tpe
}
}
}
if (nattr > 0) {
val length = buf.position();
buf.putShort(0, nattr.toShort)
val arr = buf.array().subArray(0, length);
val attr = jmember.getContext().JOtherAttribute(jmember.getJClass(),
jmember,
nme.RuntimeAnnotationATTR.toString(),
arr,
length)
jmember.addAttribute(attr)
}
}
def isTopLevelModule(sym: Symbol): Boolean =
atPhase (currentRun.refchecksPhase) {
sym.isModuleClass && !sym.isImplClass && !sym.isNestedClass
}
def isStaticModule(sym: Symbol): Boolean = {
sym.isModuleClass && !sym.isImplClass && !sym.hasFlag(Flags.LIFTED)
}
def genField(f: IField): Unit = {
if (settings.debug.value)
log("Adding field: " + f.symbol.fullNameString);
var attributes = 0;
f.symbol.attributes foreach { a => a match {
case Pair(TransientAtt, _) => attributes = attributes | JAccessFlags.ACC_TRANSIENT;
case Pair(VolatileAttr, _) => attributes = attributes | JAccessFlags.ACC_VOLATILE;
case _ => ();
}}
val jfield =
jclass.addNewField(javaFlags(f.symbol) | attributes,
javaName(f.symbol),
javaType(f.symbol.tpe));
addAttributes(jfield, f.symbol.attributes)
}
def genMethod(m: IMethod): Unit = {
if (settings.debug.value)
log("Generating method " + m.symbol + " flags: " + Flags.flagsToString(m.symbol.flags) +
" owner: " + m.symbol.owner);
method = m;
endPC.clear;
computeLocalVarsIndex(m);
var resTpe = javaType(m.symbol.tpe.resultType);
if (m.symbol.isClassConstructor)
resTpe = JType.VOID;
var flags = javaFlags(m.symbol);
if (jclass.isInterface())
flags = flags | JAccessFlags.ACC_ABSTRACT;
jmethod = jclass.addNewMethod(flags,
javaName(m.symbol),
resTpe,
javaTypes(m.params map (.kind)),
javaNames(m.params map (.sym)));
if (m.symbol.hasFlag(Flags.BRIDGE))
jmethod.addAttribute(fjbgContext.JOtherAttribute(jclass, jmethod, "Bridge",
new Array[Byte](0)));
if (remoteClass || (m.symbol.attributes contains Pair(RemoteAttr, Nil)))
if (jmethod.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];
// }
val cp = jclass.getConstantPool();
val reInx = cp.addClass(JAVA_RMI_REMOTEEXCEPTION);
val contents = ByteBuffer.allocate(4); // u2 + u2[1]
contents.putShort(1.asInstanceOf[Short]);
contents.putShort(reInx.asInstanceOf[Short]);
if (settings.debug.value)
log("adding 'Exceptions_attribute' " + contents + " for remote method " + method);
jmethod.addAttribute(
fjbgContext.JOtherAttribute(jclass, jmethod, "Exceptions", contents.array()));
}
if (!jmethod.isAbstract()) {
for (val local <- m.locals; (! m.params.contains(local))) {
if (settings.debug.value)
log("add local var: " + local);
jmethod.addNewLocalVariable(javaType(local.kind), javaName(local.sym));
}
jcode = jmethod.getCode().asInstanceOf[JExtendedCode];
genCode(m);
genLocalVariableTable;
}
addExceptionsAttribute(jmethod, m.symbol.attributes)
addAttributes(jmethod, m.symbol.attributes)
}
def addModuleInstanceField: Unit = {
import JAccessFlags._;
jclass.addNewField(ACC_PUBLIC | ACC_FINAL | ACC_STATIC,
MODULE_INSTANCE_NAME,
jclass.getType());
}
def addStaticInit(cls: JClass): Unit = {
import JAccessFlags._;
val clinitMethod = cls.addNewMethod(ACC_PUBLIC | ACC_STATIC,
"<clinit>",
JType.VOID,
JType.EMPTY_ARRAY,
new Array[String](0));
val clinit = clinitMethod.getCode().asInstanceOf[JExtendedCode];
if (isStaticModule(clasz.symbol)) {
clinit.emitNEW(cls.getName());
clinit.emitDUP();
clinit.emitINVOKESPECIAL(cls.getName(),
JMethod.INSTANCE_CONSTRUCTOR_NAME,
JMethodType.ARGLESS_VOID_FUNCTION);
}
serialVUID match {
case Some(value) =>
val fieldName = "serialVersionUID";
jclass.addNewField(JAccessFlags.ACC_STATIC | JAccessFlags.ACC_PUBLIC,
fieldName,
JType.LONG);
clinit.emitPUSH(value);
clinit.emitPUTSTATIC(jclass.getName(), fieldName, JType.LONG);
case None => ();
}
clinit.emitRETURN();
}
def dumpMirrorClass: Unit = {
import JAccessFlags._;
assert(clasz.symbol.isModuleClass);
if (settings.debug.value)
log("Dumping mirror class for object: " + clasz);
val moduleName = javaName(clasz.symbol); // + "$";
val mirrorName = moduleName.substring(0, moduleName.length() - 1);
val mirrorClass = fjbgContext.JClass(ACC_SUPER | ACC_PUBLIC | ACC_FINAL,
mirrorName,
"java.lang.Object",
JClass.NO_INTERFACES,
clasz.cunit.source.toString());
for (val m <- clasz.symbol.tpe.nonPrivateMembers;
m.owner != definitions.ObjectClass && !m.hasFlag(Flags.PROTECTED) &&
m.isMethod && !m.isConstructor && !isStaticSymbol(m) )
{
val paramJavaTypes = m.tpe.paramTypes map (t => toTypeKind(t));
val paramNames: Array[String] = new Array[String](paramJavaTypes.length);
for (val i <- Iterator.range(0, paramJavaTypes.length))
paramNames(i) = "x_" + i;
val mirrorMethod = mirrorClass
.addNewMethod(ACC_PUBLIC | ACC_FINAL | ACC_STATIC,
javaName(m),
javaType(m.tpe.resultType),
javaTypes(paramJavaTypes),
paramNames);
val mirrorCode = mirrorMethod.getCode().asInstanceOf[JExtendedCode];
mirrorCode.emitGETSTATIC(moduleName,
MODULE_INSTANCE_NAME,
new JObjectType(moduleName));
var i = 0;
var index = 0;
var argTypes = mirrorMethod.getArgumentTypes();
while (i < argTypes.length) {
mirrorCode.emitLOAD(index, argTypes(i));
index = index + argTypes(i).getSize();
i = i + 1;
}
mirrorCode.emitINVOKEVIRTUAL(moduleName, mirrorMethod.getName(), mirrorMethod.getType().asInstanceOf[JMethodType]);
mirrorCode.emitRETURN(mirrorMethod.getReturnType());
}
emitClass(mirrorClass, clasz.symbol);
}
var linearization: List[BasicBlock] = Nil;
var isModuleInitialized = false;
def genCode(m: IMethod): Unit = {
labels.clear;
isModuleInitialized = false;
code = m.code;
linearization = linearizer.linearize(m);
makeLabels(linearization);
genBlocks(linearization);
if (this.method.exh != Nil)
genExceptionHandlers;
}
var nextBlock: BasicBlock = _;
def genBlocks(l: List[BasicBlock]): Unit = l match {
case Nil => ();
case x :: Nil => nextBlock = null; genBlock(x);
case x :: y :: ys => nextBlock = y; genBlock(x); genBlocks(y :: ys);
}
/** Generate exception handlers for the current method. */
def genExceptionHandlers: Unit = {
/** Return a list of pairs of intervals where the handler is active.
* The intervals in the list have to be inclusive in the beginning and
* exclusive in the end: [start, end).
*/
def ranges(e: ExceptionHandler): List[Pair[Int, Int]] = {
var covered = e.covered;
var ranges: List[Pair[Int, Int]] = Nil;
var start = -1;
var end = -1;
linearization foreach ((b) => {
if (! (covered contains b) ) {
if (start >= 0) { // we're inside a handler range
end = labels(b).getAnchor();
ranges = Pair(start, end) :: ranges;
start = -1;
}
} else {
if (start >= 0) { // we're inside a handler range
end = endPC(b);
} else {
start = labels(b).getAnchor();
end = endPC(b);
}
covered = covered remove b.==;
}
});
/* Add the last interval. Note that since the intervals are
* open-ended to the right, we have to give a number past the actual
* code!
*/
if (start >= 0) {
ranges = Pair(start, jcode.getPC()) :: ranges;
}
if (covered != Nil)
if (settings.debug.value)
log("Some covered blocks were not found in method: " + method +
" covered: " + covered + " not in " + linearization);
ranges
}
this.method.exh foreach ((e) => {
ranges(e).sort({ (p1, p2) => p1._1 < p2._1 })
.foreach ((p) => {
if (settings.debug.value)
log("Adding exception handler " + e + "at block: " + e.startBlock + " for " + method +
" from: " + p._1 + " to: " + p._2 + " catching: " + e.cls);
jcode.addExceptionHandler(p._1, p._2,
labels(e.startBlock).getAnchor(),
if (e.cls == NoSymbol)
null
else javaName(e.cls))
})
});
}
def genBlock(b: BasicBlock): Unit = {
labels(b).anchorToNext();
if (settings.debug.value)
log("Generating code for block: " + b + " at pc: " + labels(b).getAnchor());
var lastMappedPC = 0;
var lastLineNr =0;
var crtPC = 0;
b traverse ( instr => {
if (b.lastInstruction == instr)
endPC(b) = jcode.getPC();
instr match {
case THIS(clasz) =>
jcode.emitALOAD_0();
case CONSTANT(const) =>
const.tag match {
case UnitTag => ();
case BooleanTag => jcode.emitPUSH(const.booleanValue);
case ByteTag => jcode.emitPUSH(const.byteValue);
case ShortTag => jcode.emitPUSH(const.shortValue);
case CharTag => jcode.emitPUSH(const.charValue);
case IntTag => jcode.emitPUSH(const.intValue);
case LongTag => jcode.emitPUSH(const.longValue);
case FloatTag => jcode.emitPUSH(const.floatValue);
case DoubleTag => jcode.emitPUSH(const.doubleValue);
case StringTag => jcode.emitPUSH(const.stringValue);
case NullTag => jcode.emitACONST_NULL();
case ClassTag =>
val kind = toTypeKind(const.typeValue);
if (kind.isValueType)
jcode.emitPUSH(classLiteral(kind));
else
jcode.emitPUSH(javaType(kind).asInstanceOf[JReferenceType]);
case EnumTag =>
val sym = const.symbolValue
jcode.emitGETSTATIC(javaName(sym.owner),
javaName(sym),
javaType(const.tpe))
case _ => abort("Unknown constant value: " + const);
}
case LOAD_ARRAY_ITEM(kind) =>
jcode.emitALOAD(javaType(kind));
case LOAD_LOCAL(local) =>
jcode.emitLOAD(indexOf(local), javaType(local.kind));
case LOAD_FIELD(field, isStatic) =>
var owner = javaName(field.owner);
// if (field.owner.hasFlag(Flags.MODULE)) owner = owner + "$";
if (settings.debug.value)
log("LOAD_FIELD with owner: " + owner + " flags: " + Flags.flagsToString(field.owner.flags));
if (isStatic)
jcode.emitGETSTATIC(owner,
javaName(field),
javaType(field));
else
jcode.emitGETFIELD(owner,
javaName(field),
javaType(field));
case LOAD_MODULE(module) =>
assert(module.isModule || module.isModuleClass, "Expected module: " + module);
if (settings.debug.value)
log("genearting LOAD_MODULE for: " + module + " flags: " +
Flags.flagsToString(module.flags));
jcode.emitGETSTATIC(javaName(module) /* + "$" */ ,
MODULE_INSTANCE_NAME,
javaType(module));
case STORE_ARRAY_ITEM(kind) =>
jcode.emitASTORE(javaType(kind));
case STORE_LOCAL(local) =>
jcode.emitSTORE(indexOf(local), javaType(local.kind));
case STORE_FIELD(field, isStatic) =>
val owner = javaName(field.owner); // + (if (field.owner.hasFlag(Flags.MODULE)) "$" else "");
if (isStatic)
jcode.emitPUTSTATIC(owner,
javaName(field),
javaType(field));
else
jcode.emitPUTFIELD(owner,
javaName(field),
javaType(field));
case CALL_PRIMITIVE(primitive) =>
genPrimitive(primitive, instr.pos);
// TODO: reference the type of the receiver instead of the
// method owner.
case CALL_METHOD(method, style) =>
val owner = javaName(method.owner); // + (if (method.owner.isModuleClass) "$" else "");
style match {
case Dynamic =>
if (method.owner.hasFlag(Flags.INTERFACE))
jcode.emitINVOKEINTERFACE(owner,
javaName(method),
javaType(method).asInstanceOf[JMethodType])
else
jcode.emitINVOKEVIRTUAL(owner,
javaName(method),
javaType(method).asInstanceOf[JMethodType]);
case Static(instance) =>
if (instance) {
jcode.emitINVOKESPECIAL(owner,
javaName(method),
javaType(method).asInstanceOf[JMethodType]);
} else
jcode.emitINVOKESTATIC(owner,
javaName(method),
javaType(method).asInstanceOf[JMethodType]);
case SuperCall(_) =>
jcode.emitINVOKESPECIAL(owner,
javaName(method),
javaType(method).asInstanceOf[JMethodType]);
// we initialize the MODULE$ field immediately after the super ctor
if (isStaticModule(clasz.symbol) && !isModuleInitialized &&
jmethod.getName() == JMethod.INSTANCE_CONSTRUCTOR_NAME &&
javaName(method) == JMethod.INSTANCE_CONSTRUCTOR_NAME) {
isModuleInitialized = true;
jcode.emitALOAD_0();
jcode.emitPUTSTATIC(jclass.getName(),
MODULE_INSTANCE_NAME,
jclass.getType());
}
}
case NEW(REFERENCE(cls)) =>
val className = javaName(cls);
jcode.emitNEW(className);
case CREATE_ARRAY(elem) => elem match {
case REFERENCE(_) | ARRAY(_) =>
jcode.emitANEWARRAY(javaType(elem).asInstanceOf[JReferenceType]);
case _ =>
jcode.emitNEWARRAY(javaType(elem));
}
case IS_INSTANCE(tpe) =>
tpe match {
case REFERENCE(cls) => jcode.emitINSTANCEOF(new JObjectType(javaName(cls)));
case ARRAY(elem) => jcode.emitINSTANCEOF(new JArrayType(javaType(elem)));
case _ => abort("Unknown reference type in IS_INSTANCE: " + tpe);
}
case CHECK_CAST(tpe) =>
tpe match {
case REFERENCE(cls) => jcode.emitCHECKCAST(new JObjectType(javaName(cls)));
case ARRAY(elem) => jcode.emitCHECKCAST(new JArrayType(javaType(elem)));
case _ => abort("Unknown reference type in IS_INSTANCE: " + tpe);
}
case SWITCH(tags, branches) =>
val tagArray = new Array[Array[Int]](tags.length);
var caze = tags;
var i = 0;
while (i < tagArray.length) {
tagArray(i) = new Array[Int](caze.head.length);
caze.head.copyToArray(tagArray(i), 0);
i = i + 1;
caze = caze.tail;
}
val branchArray = new Array[JCode$Label](tagArray.length);
if (settings.debug.value)
log("Emitting SWITHCH:\ntags: " + tags + "\nbranches: " + branches);
jcode.emitSWITCH(tagArray,
(branches map labels dropRight 1).copyToArray(branchArray, 0),
labels(branches.last),
MIN_SWITCH_DENSITY);
case JUMP(where) =>
if (nextBlock != where)
jcode.emitGOTO_maybe_W(labels(where), false); // default to short jumps
case CJUMP(success, failure, cond, kind) =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
if (nextBlock == success) {
jcode.emitIF_ICMP(conds(negate(cond)), labels(failure));
// .. and fall through to success label
} else {
jcode.emitIF_ICMP(conds(cond), labels(success));
if (nextBlock != failure)
jcode.emitGOTO_maybe_W(labels(failure), false);
}
case REFERENCE(_) | ARRAY(_) =>
if (nextBlock == success) {
jcode.emitIF_ACMP(conds(negate(cond)), labels(failure));
// .. and fall through to success label
} else {
jcode.emitIF_ACMP(conds(cond), labels(success));
if (nextBlock != failure)
jcode.emitGOTO_maybe_W(labels(failure), false);
}
case _ =>
kind match {
case LONG => jcode.emitLCMP();
case FLOAT => jcode.emitFCMPG();
case DOUBLE => jcode.emitDCMPG();
}
if (nextBlock == success) {
jcode.emitIF(conds(negate(cond)), labels(failure));
// .. and fall through to success label
} else {
jcode.emitIF(conds(cond), labels(success));
if (nextBlock != failure)
jcode.emitGOTO_maybe_W(labels(failure), false);
}
}
case CZJUMP(success, failure, cond, kind) =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
if (nextBlock == success) {
jcode.emitIF(conds(negate(cond)), labels(failure));
} else {
jcode.emitIF(conds(cond), labels(success));
if (nextBlock != failure)
jcode.emitGOTO_maybe_W(labels(failure), false);
}
case REFERENCE(_) | ARRAY(_) =>
if (nextBlock == success) {
jcode.emitIFNONNULL(labels(failure));
} else {
jcode.emitIFNULL(labels(success));
if (nextBlock != failure)
jcode.emitGOTO_maybe_W(labels(failure), false);
}
case _ =>
kind match {
case LONG => jcode.emitLCONST_0(); jcode.emitLCMP();
case FLOAT => jcode.emitFCONST_0(); jcode.emitFCMPL();
case DOUBLE => jcode.emitDCONST_0(); jcode.emitDCMPL();
}
if (nextBlock == success) {
jcode.emitIF(conds(negate(cond)), labels(failure));
} else {
jcode.emitIF(conds(cond), labels(success));
if (nextBlock != failure)
jcode.emitGOTO_maybe_W(labels(failure), false);
}
}
case RETURN(kind) =>
jcode.emitRETURN(javaType(kind));
case THROW() =>
jcode.emitATHROW();
case DROP(kind) =>
kind match {
case LONG | DOUBLE => jcode.emitPOP2();
case _ => jcode.emitPOP();
}
case DUP(kind) =>
kind match {
case LONG | DOUBLE => jcode.emitDUP2();
case _ => jcode.emitDUP();
}
case MONITOR_ENTER() =>
jcode.emitMONITORENTER();
case MONITOR_EXIT() =>
jcode.emitMONITOREXIT();
}
crtPC = jcode.getPC();
val crtLine = try { clasz.cunit.position(instr.pos).line; } catch {
case _: Error => lastLineNr;
}
//System.err.println("CRTLINE: " + instr.pos + " " +
// /* (if (instr.pos < clasz.cunit.source.content.length) clasz.cunit.source.content(instr.pos) else '*') + */ " " + crtLine);
if (crtPC > lastMappedPC) {
jcode.completeLineNumber(lastMappedPC, crtPC, crtLine);
lastMappedPC = crtPC;
lastLineNr = crtLine;
}
});
}
def genPrimitive(primitive: Primitive, pos: Int): Unit = {
primitive match {
case Negation(kind) =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
jcode.emitINEG();
case LONG => jcode.emitLNEG();
case FLOAT => jcode.emitFNEG();
case DOUBLE => jcode.emitDNEG();
case _ => abort("Impossible to negate a " + kind);
}
case Arithmetic(op, kind) =>
op match {
case ADD => jcode.emitADD(javaType(kind));
case SUB =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
jcode.emitISUB();
case LONG => jcode.emitLSUB();
case FLOAT => jcode.emitFSUB();
case DOUBLE => jcode.emitDSUB();
}
case MUL =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
jcode.emitIMUL();
case LONG => jcode.emitLMUL();
case FLOAT => jcode.emitFMUL();
case DOUBLE => jcode.emitDMUL();
}
case DIV =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
jcode.emitIDIV();
case LONG => jcode.emitLDIV();
case FLOAT => jcode.emitFDIV();
case DOUBLE => jcode.emitDDIV();
}
case REM =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
jcode.emitIREM();
case LONG => jcode.emitLREM();
case FLOAT => jcode.emitFREM();
case DOUBLE => jcode.emitDREM();
}
case NOT =>
kind match {
case BOOL | BYTE | CHAR | SHORT | INT =>
jcode.emitPUSH(-1);
jcode.emitIXOR();;
case LONG =>
jcode.emitPUSH(-1l);
jcode.emitLXOR();;
case _ => abort("Impossible to negate an " + kind);
}
case _ => abort("Unknown arithmetic primitive " + primitive );
}
case Logical(op, kind) => Pair(op, kind) match {
case Pair(AND, LONG) =>
jcode.emitLAND();
case Pair(AND, INT) =>
jcode.emitIAND();
case Pair(AND, _) =>
jcode.emitIAND();
if (kind != BOOL)
jcode.emitT2T(javaType(INT), javaType(kind));
case Pair(OR, LONG) =>
jcode.emitLOR();
case Pair(OR, INT) =>
jcode.emitIOR();
case Pair(OR, _) =>
jcode.emitIOR();
if (kind != BOOL)
jcode.emitT2T(javaType(INT), javaType(kind));
case Pair(XOR, LONG) =>
jcode.emitLXOR();
case Pair(XOR, INT) =>
jcode.emitIXOR();
case Pair(XOR, _) =>
jcode.emitIXOR();
if (kind != BOOL)
jcode.emitT2T(javaType(INT), javaType(kind));
}
case Shift(op, kind) => Pair(op, kind) match {
case Pair(LSL, LONG) =>
jcode.emitLSHL();
case Pair(LSL, INT) =>
jcode.emitISHL();
case Pair(LSL, _) =>
jcode.emitISHL();
jcode.emitT2T(javaType(INT), javaType(kind));
case Pair(ASR, LONG) =>
jcode.emitLSHR();
case Pair(ASR, INT) =>
jcode.emitISHR();
case Pair(ASR, _) =>
jcode.emitISHR();
jcode.emitT2T(javaType(INT), javaType(kind));
case Pair(LSR, LONG) =>
jcode.emitLUSHR();
case Pair(LSR, INT) =>
jcode.emitIUSHR();
case Pair(LSR, _) =>
jcode.emitIUSHR();
jcode.emitT2T(javaType(INT), javaType(kind));
}
case Conversion(src, dst) =>
if (settings.debug.value)
log("Converting from: " + src + " to: " + dst);
if (dst == BOOL) {
Console.println("Illegal conversion at: " + clasz +
" at: " + method.sourceFile + ":" + Position.line(clasz.cunit.source, pos));
} else
jcode.emitT2T(javaType(src), javaType(dst));
case ArrayLength(_) =>
jcode.emitARRAYLENGTH();
case StartConcat =>
jcode.emitNEW(JAVA_LANG_STRINGBUFFER);
jcode.emitDUP();
jcode.emitINVOKESPECIAL(JAVA_LANG_STRINGBUFFER,
JMethod.INSTANCE_CONSTRUCTOR_NAME,
JMethodType.ARGLESS_VOID_FUNCTION);
case StringConcat(el) =>
val jtype = el match {
case REFERENCE(_) | ARRAY(_)=> JObjectType.JAVA_LANG_OBJECT;
case _ => javaType(el);
}
jcode.emitINVOKEVIRTUAL(JAVA_LANG_STRINGBUFFER,
"append",
new JMethodType(stringBufferType,
Predef.Array(jtype)));
case EndConcat =>
jcode.emitINVOKEVIRTUAL(JAVA_LANG_STRINGBUFFER,
"toString",
toStringType);
case _ => abort("Unimplemented primitive " + primitive);
}
}
val endPC: HashMap[BasicBlock, Int] = new HashMap();
val labels: HashMap[BasicBlock, JCode$Label] = new HashMap();
val conds: HashMap[TestOp, Int] = new HashMap();
conds += EQ -> JExtendedCode.COND_EQ;
conds += NE -> JExtendedCode.COND_NE;
conds += LT -> JExtendedCode.COND_LT;
conds += GT -> JExtendedCode.COND_GT;
conds += LE -> JExtendedCode.COND_LE;
conds += GE -> JExtendedCode.COND_GE;
val negate: HashMap[TestOp, TestOp] = new HashMap();
negate += EQ -> NE;
negate += NE -> EQ;
negate += LT -> GE;
negate += GT -> LE;
negate += LE -> GT;
negate += GE -> LT;
/** Map from type kinds to the Java reference types. It is used for
* loading class constants. @see Predef.classOf. */
val classLiteral: Map[TypeKind, JObjectType] = new HashMap();
classLiteral += UNIT -> new JObjectType("java.lang.Void");
classLiteral += BOOL -> new JObjectType("java.lang.Boolean");
classLiteral += BYTE -> new JObjectType("java.lang.Byte");
classLiteral += SHORT -> new JObjectType("java.lang.Short");
classLiteral += CHAR -> new JObjectType("java.lang.Character");
classLiteral += INT -> new JObjectType("java.lang.Integer");
classLiteral += LONG -> new JObjectType("java.lang.Long");
classLiteral += FLOAT -> new JObjectType("java.lang.Float");
classLiteral += DOUBLE -> new JObjectType("java.lang.Double");
def makeLabels(bs: List[BasicBlock]) = {
//labels.clear;
if (settings.debug.value)
log("Making labels for: " + method);
bs foreach (bb => labels += bb -> jcode.newLabel() );
}
////////////////////// local vars ///////////////////////
def sizeOf(sym: Symbol): Int = sizeOf(toTypeKind(sym.tpe));
def sizeOf(k: TypeKind): Int = k match {
case DOUBLE | LONG => 2;
case _ => 1;
}
def indexOf(m: IMethod, sym: Symbol): Int = {
val Some(local) = m.lookupLocal(sym);
assert (local.index >= 0,
"Invalid index for: " + local);
local.index
}
def indexOf(local: Local): Int = {
assert (local.index >= 0,
"Invalid index for: " + local);
local.index
}
/**
* Compute the indexes of each local variable of the given
* method.
*/
def computeLocalVarsIndex(m: IMethod): Unit = {
var idx = 1;
if (isStaticSymbol(m.symbol))
idx = 0;
for (val l <- m.locals) {
if (settings.debug.value)
log("Index value for " + l + ": " + idx);
l.index = idx;
idx = idx + sizeOf(l.kind);
}
}
////////////////////// Utilities ////////////////////////
/** Return the a name of this symbol that can be used on the Java
* platform. It removes spaces from names.
*
* Special handling: scala.All and scala.AllRef are 'erased' to
* scala.All$ and scala.AllRef$. This is needed because they are
* not real classes, and they mean 'abrupt termination upon evaluation
* of that expression' or 'null' respectively. This handling is
* done already in GenICode, but here we need to remove references
* from method signatures to these types, because such classes can
* not exist in the classpath: the type checker will be very confused.
*/
def javaName(sym: Symbol): String = {
val suffix = if (sym.hasFlag(Flags.MODULE) && !sym.isMethod &&
!sym.isImplClass &&
!sym.hasFlag(Flags.JAVA)) "$" else "";
if (sym == definitions.AllClass)
return "scala.All$"
else if (sym == definitions.AllRefClass)
return "scala.AllRef$";
(if (sym.isClass || (sym.isModule && !sym.isMethod))
sym.fullNameString('/')
else
sym.simpleName.toString().trim()) + suffix
}
def javaNames(syms: List[Symbol]): Array[String] = {
val res = new Array[String](syms.length);
var i = 0;
syms foreach ( s => { res(i) = javaName(s); i = i + 1; } );
res
}
/**
* Return the Java modifiers for the given symbol.
* Java modifiers for classes:
* - public, abstract, final, strictfp (not used)
* for interfaces:
* - the same as for classes, without 'final'
* for fields:
* - public, protected, private
* - static, final
* for methods:
* - the same as for fields, plus:
* - abstract, synchronized (not used), strictfp (not used), native (not used)
*/
def javaFlags(sym: Symbol): Int = {
import JAccessFlags._;
var jf: Int = 0;
val f = sym.flags;
jf = jf | (if (sym hasFlag Flags.PRIVATE) ACC_PRIVATE else ACC_PUBLIC);
jf = jf | (if ((sym hasFlag Flags.ABSTRACT) ||
(sym hasFlag Flags.DEFERRED)) ACC_ABSTRACT else 0);
jf = jf | (if (sym hasFlag Flags.INTERFACE) ACC_INTERFACE else 0);
jf = jf | (if ((sym hasFlag Flags.FINAL) && !sym.enclClass.hasFlag(Flags.INTERFACE)) ACC_FINAL else 0);
jf = jf | (if (isStaticSymbol(sym)) ACC_STATIC else 0);
jf
}
def isStaticSymbol(s: Symbol): Boolean =
s.hasFlag(Flags.STATIC) || s.hasFlag(Flags.STATICMEMBER) || s.owner.isImplClass;
def javaType(t: TypeKind): JType = t match {
case UNIT => JType.VOID;
case BOOL => JType.BOOLEAN;
case BYTE => JType.BYTE;
case SHORT => JType.SHORT;
case CHAR => JType.CHAR;
case INT => JType.INT;
case LONG => JType.LONG;
case FLOAT => JType.FLOAT;
case DOUBLE => JType.DOUBLE;
case REFERENCE(cls) => new JObjectType(javaName(cls));
case ARRAY(elem) => new JArrayType(javaType(elem));
}
def javaType(t: Type): JType = javaType(toTypeKind(t))
def javaType(s: Symbol): JType =
if (s.isMethod)
new JMethodType(
if (s.isClassConstructor) JType.VOID else javaType(s.tpe.resultType),
s.tpe.paramTypes.map(javaType).toArray)
else
javaType(s.tpe);
def javaTypes(ts: List[TypeKind]): Array[JType] = {
val res = new Array[JType](ts.length);
var i = 0;
ts foreach ( t => { res(i) = javaType(t); i = i + 1; } );
res
}
def getFile(cls: JClass, suffix: String): String = {
val path = cls.getName().replace('.', File.separatorChar);
settings.outdir.value + File.separatorChar + path + suffix
}
private def genLocalVariableTable: Unit = {
val vars: Array[JLocalVariable] = jmethod.getLocalVariables();
if (!settings.debuginfo.value || vars.length == 0)
return;
val pool = jclass.getConstantPool();
val pc = jcode.getPC();
var anonCounter = 0;
val lvTab = ByteBuffer.allocate(2 + 10 * vars.length);
lvTab.putShort(vars.length.asInstanceOf[Short]);
for (val lv <- vars) {
val name = if (lv.getName() == null) {
anonCounter = anonCounter + 1;
"<anon" + anonCounter + ">"
} else lv.getName();
lvTab.putShort(0.asInstanceOf[Short]);
lvTab.putShort(pc.asInstanceOf[Short]);
lvTab.putShort(pool.addUtf8(name).asInstanceOf[Short]);
lvTab.putShort(pool.addUtf8(lv.getType().getSignature()).asInstanceOf[Short]);
lvTab.putShort(lv.getIndex().asInstanceOf[Short]);
}
val attr =
fjbgContext.JOtherAttribute(jclass,
jmethod,
"LocalVariableTable",
lvTab.array());
jcode.addAttribute(attr);
}
}
}
|