-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJasminBackender.java
722 lines (566 loc) · 29.9 KB
/
JasminBackender.java
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
package pt.up.fe.comp.jmm.jasmin;
import org.specs.comp.ollir.*;
import pt.up.fe.comp.jmm.ollir.OllirResult;
import pt.up.fe.comp.jmm.report.Report;
import pt.up.fe.comp.jmm.report.Stage;
import java.util.*;
import static org.specs.comp.ollir.InstructionType.BINARYOPER;
import static org.specs.comp.ollir.InstructionType.RETURN;
public class JasminBackender implements JasminBackend {
ClassUnit classUnit = null;
int conditionalNumber = 0;
int methodStackLimit = 0;
int currentStack = 0;
String superClass;
@Override
public JasminResult toJasmin(OllirResult ollirResult) {
try {
this.classUnit = ollirResult.getOllirClass();
// SETUP classUnit
this.classUnit.checkMethodLabels();
this.classUnit.buildCFGs();
this.classUnit.buildVarTables();
System.out.println("Generating Jasmin code ...");
String jasminCode = buildJasminCode();
List<Report> reports = new ArrayList<>();
if (ollirResult.getConfig().get("debug") != null && ollirResult.getConfig().get("debug").equals("true")) {
System.out.println("JASMIN CODE : \n" + jasminCode);
}
return new JasminResult(ollirResult, jasminCode, reports);
} catch (OllirErrorException e) {
return new JasminResult(classUnit.getClassName(), null,
Collections.singletonList(Report.newError(Stage.GENERATION, -1, -1,
"Jasmin generation exception.", e)));
}
}
private String buildJasminCode() {
StringBuilder stringBuilder = new StringBuilder();
// .class <access-spec> <class-name>
stringBuilder.append(".class ").append(this.classUnit.getClassName()).append("\n");
this.superClass = this.classUnit.getSuperClass();
if (this.superClass == null) {
this.superClass = "java/lang/Object";
}
// .super <class-name>
stringBuilder.append(".super ").append(getClassFullName(this.superClass)).append("\n");
// Fields
for (Field field : this.classUnit.getFields()) {
// .field <access-spec> <field-name> <descriptor>
StringBuilder accessSpec = new StringBuilder();
if (field.getFieldAccessModifier() != AccessModifiers.DEFAULT) {
accessSpec.append(field.getFieldAccessModifier().name().toLowerCase()).append(" ");
}
if (field.isStaticField()) {
accessSpec.append("static ");
}
if (field.isInitialized()) {
accessSpec.append("final ");
}
stringBuilder.append(".field ").append(accessSpec).append(field.getFieldName())
.append(" ").append(this.getFieldDescriptor(field.getFieldType())).append("\n");
}
// Methods
for (Method method : this.classUnit.getMethods()) {
// .method <access-spec> <method-spec>
// <statements>
// .end method
stringBuilder.append(this.getMethodHeader(method));
stringBuilder.append(this.getMethodStatements(method));
stringBuilder.append(".end method\n");
}
return stringBuilder.toString();
}
private String getMethodHeader(Method method) {
StringBuilder stringBuilder = new StringBuilder("\n.method ");
// <access-spec>
if (method.getMethodAccessModifier() != AccessModifiers.DEFAULT) {
stringBuilder.append(method.getMethodAccessModifier().name().toLowerCase()).append(" ");
}
if (method.isStaticMethod()) stringBuilder.append("static ");
if (method.isFinalMethod()) stringBuilder.append("final ");
// <method-spec>
if (method.isConstructMethod()) stringBuilder.append("<init>");
else stringBuilder.append(method.getMethodName());
stringBuilder.append("(");
for (Element param : method.getParams()) {
stringBuilder.append(this.getFieldDescriptor(param.getType()));
}
stringBuilder.append(")");
stringBuilder.append(this.getFieldDescriptor(method.getReturnType())).append("\n");
return stringBuilder.toString();
}
private String getMethodStatements(Method method) {
int limitLocals = calculateLimitLocals(method);
this.currentStack = 0;
this.methodStackLimit = 0;
String methodInstructions = this.getMethodInstructions(method);
return "\t.limit stack " + this.methodStackLimit + "\n" +
"\t.limit locals " + limitLocals + "\n" +
methodInstructions;
}
private String getMethodInstructions(Method method) {
StringBuilder stringBuilder = new StringBuilder();
List<Instruction> methodInstructions = method.getInstructions();
for (Instruction instruction : methodInstructions) {
// LABEL:
for (Map.Entry<String, Instruction> label : method.getLabels().entrySet()) {
if (label.getValue().equals(instruction)) {
stringBuilder.append(label.getKey()).append(":\n");
}
}
stringBuilder.append(this.getInstruction(instruction, method.getVarTable()));
if (instruction.getInstType() == InstructionType.CALL
&& ((CallInstruction) instruction).getReturnType().getTypeOfElement() != ElementType.VOID) {
stringBuilder.append("\tpop\n");
this.changeStackLimits(-1);
}
}
boolean hasReturnInstruction = methodInstructions.size() > 0
&& methodInstructions.get(methodInstructions.size() - 1).getInstType() == RETURN;
if (!hasReturnInstruction && method.getReturnType().getTypeOfElement() == ElementType.VOID) {
stringBuilder.append("\treturn\n");
}
return stringBuilder.toString();
}
private String getInstruction(Instruction instruction, HashMap<String, Descriptor> varTable) {
return switch (instruction.getInstType()) {
case ASSIGN -> this.getAssignInstruction((AssignInstruction) instruction, varTable);
case CALL -> this.getCallInstruction((CallInstruction) instruction, varTable);
case GOTO -> this.getGotoInstruction((GotoInstruction) instruction);
case BRANCH -> this.getBranchInstruction((CondBranchInstruction) instruction, varTable);
case RETURN -> this.getReturnInstruction((ReturnInstruction) instruction, varTable);
case PUTFIELD -> this.getPutFieldInstruction((PutFieldInstruction) instruction, varTable);
case GETFIELD -> this.getGetFieldInstruction((GetFieldInstruction) instruction, varTable);
case UNARYOPER -> this.getUnaryOperationInstruction((UnaryOpInstruction) instruction, varTable);
case BINARYOPER -> this.getBinaryOperationInstruction((BinaryOpInstruction) instruction, varTable);
case NOPER -> this.getLoadToStack(((SingleOpInstruction) instruction).getSingleOperand(), varTable);
};
}
private String getUnaryOperationInstruction(UnaryOpInstruction instruction, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(this.getLoadToStack(instruction.getOperand(), varTable))
.append("\t").append(this.getOperation(instruction.getOperation()));
boolean isBooleanOperation = instruction.getOperation().getOpType() == OperationType.NOTB;
if (isBooleanOperation) {
stringBuilder.append(this.getBooleanOperationResultToStack());
} else {
stringBuilder.append("; Invalid UNARYOPER\n");
}
stringBuilder.append("\n");
return stringBuilder.toString();
}
private String getBinaryOperationInstruction(BinaryOpInstruction instruction, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
Element leftElement = instruction.getLeftOperand();
Element rightElement = instruction.getRightOperand();
stringBuilder.append(this.getLoadToStack(leftElement, varTable))
.append(this.getLoadToStack(rightElement, varTable))
.append("\t").append(this.getOperation(instruction.getOperation()));
OperationType opType = instruction.getOperation().getOpType();
boolean isBooleanOperation =
opType == OperationType.EQ
|| opType == OperationType.GTH
|| opType == OperationType.GTE
|| opType == OperationType.LTH
|| opType == OperationType.LTE
|| opType == OperationType.NEQ;
if (isBooleanOperation) {
stringBuilder.append(this.getBooleanOperationResultToStack());
}
stringBuilder.append("\n");
this.changeStackLimits(-1);
return stringBuilder.toString();
}
private String getBranchInstruction(CondBranchInstruction instruction, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
Instruction condition;
if (instruction instanceof SingleOpCondInstruction) {
SingleOpCondInstruction singleOpCondInstruction = (SingleOpCondInstruction) instruction;
condition = singleOpCondInstruction.getCondition();
} else if (instruction instanceof OpCondInstruction) {
OpCondInstruction opCondInstruction = (OpCondInstruction) instruction;
condition = opCondInstruction.getCondition();
} else {
return "; ERROR: invalid CondBranchInstruction instance\n";
}
String operation;
switch (condition.getInstType()) {
case BINARYOPER -> {
BinaryOpInstruction binaryOpInstruction = (BinaryOpInstruction) condition;
switch (binaryOpInstruction.getOperation().getOpType()) {
case LTH -> {
Element leftElement = binaryOpInstruction.getLeftOperand();
Element rightElement = binaryOpInstruction.getRightOperand();
Integer parsedInt = null;
Element otherElement = null;
operation = "if_icmplt";
// instruction selection for 0 < x
if (leftElement instanceof LiteralElement) {
String literal = ((LiteralElement) leftElement).getLiteral();
parsedInt = Integer.parseInt(literal);
otherElement = rightElement;
operation = "ifgt";
// instruction selection for x < 0
} else if (rightElement instanceof LiteralElement) {
String literal = ((LiteralElement) rightElement).getLiteral();
parsedInt = Integer.parseInt(literal);
otherElement = leftElement;
operation = "iflt";
}
if (parsedInt != null && parsedInt == 0) {
stringBuilder.append(this.getLoadToStack(otherElement, varTable));
} else {
stringBuilder.append(this.getLoadToStack(leftElement, varTable))
.append(this.getLoadToStack(rightElement, varTable));
operation = "if_icmplt";
}
}
case ANDB -> {
stringBuilder.append(this.getInstruction(condition, varTable));
operation = "ifne";
}
default -> {
// not supposed to happen
stringBuilder.append("; Invalid BINARYOPER\n");
stringBuilder.append(this.getInstruction(condition, varTable));
operation = "ifne";
}
}
}
case UNARYOPER -> {
UnaryOpInstruction unaryOpInstruction = (UnaryOpInstruction) condition;
if (unaryOpInstruction.getOperation().getOpType() == OperationType.NOTB) {
stringBuilder.append(this.getLoadToStack(unaryOpInstruction.getOperand(), varTable));
operation = "ifeq";
} else {
// not supposed to happen
stringBuilder.append("; Invalid UNARYOPER\n");
stringBuilder.append(this.getInstruction(condition, varTable));
operation = "ifne";
}
}
default -> {
stringBuilder.append(this.getInstruction(condition, varTable));
operation = "ifne";
}
}
stringBuilder.append("\t").append(operation).append(" ").append(instruction.getLabel()).append("\n");
if (operation.equals("if_icmplt")) {
this.changeStackLimits(-2);
} else {
this.changeStackLimits(-1);
}
return stringBuilder.toString();
}
private String getOperation(Operation operation) {
return switch (operation.getOpType()) {
case LTH -> "if_icmplt";
case ANDB -> "iand";
case NOTB -> "ifeq";
case ADD -> "iadd";
case SUB -> "isub";
case MUL -> "imul";
case DIV -> "idiv";
default -> "; ERROR: operation not implemented: " + operation.getOpType() + "\n";
};
}
private String getPutFieldInstruction(PutFieldInstruction instruction, HashMap<String, Descriptor> varTable) {
String res = this.getLoadToStack(instruction.getFirstOperand(), varTable) +
this.getLoadToStack(instruction.getThirdOperand(), varTable) +
"\tputfield " + this.getClassFullName(((Operand) instruction.getFirstOperand()).getName()) +
"/" + ((Operand) instruction.getSecondOperand()).getName() +
" " + this.getFieldDescriptor(instruction.getSecondOperand().getType()) + "\n";
this.changeStackLimits(-2);
return res;
}
private String getGetFieldInstruction(GetFieldInstruction instruction, HashMap<String, Descriptor> varTable) {
return this.getLoadToStack(instruction.getFirstOperand(), varTable) +
"\tgetfield " + this.getClassFullName(((Operand) instruction.getFirstOperand()).getName()) +
"/" + ((Operand) instruction.getSecondOperand()).getName() +
" " + this.getFieldDescriptor(instruction.getSecondOperand().getType()) + "\n";
}
private String getReturnInstruction(ReturnInstruction instruction, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
if (instruction.hasReturnValue()) {
stringBuilder.append(this.getLoadToStack(instruction.getOperand(), varTable));
}
stringBuilder.append("\t");
if (instruction.getOperand() != null) {
ElementType elementType = instruction.getOperand().getType().getTypeOfElement();
if (elementType == ElementType.INT32 || elementType == ElementType.BOOLEAN) {
stringBuilder.append("i");
} else {
stringBuilder.append("a");
}
}
stringBuilder.append("return\n");
return stringBuilder.toString();
}
private String getGotoInstruction(GotoInstruction instruction) {
return "\tgoto " + instruction.getLabel() + "\n";
}
private String getLoadToStack(Element element, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
if (element instanceof LiteralElement) {
String literal = ((LiteralElement) element).getLiteral();
if (element.getType().getTypeOfElement() == ElementType.INT32
|| element.getType().getTypeOfElement() == ElementType.BOOLEAN) {
int parsedInt = Integer.parseInt(literal);
if (parsedInt >= -1 && parsedInt <= 5) { // [-1,5]
stringBuilder.append("\ticonst_");
} else if (parsedInt >= -128 && parsedInt <= 127) { // byte
stringBuilder.append("\tbipush ");
} else if (parsedInt >= -32768 && parsedInt <= 32767) { // short
stringBuilder.append("\tsipush ");
} else {
stringBuilder.append("\tldc "); // int
}
if (parsedInt == -1) {
stringBuilder.append("m1");
} else {
stringBuilder.append(parsedInt);
}
} else {
stringBuilder.append("\tldc ").append(literal);
}
this.changeStackLimits(+1);
} else if (element instanceof ArrayOperand) {
ArrayOperand operand = (ArrayOperand) element;
stringBuilder.append("\taload").append(this.getVariableNumber(operand.getName(), varTable)).append("\n"); // load array (ref)
this.changeStackLimits(+1);
stringBuilder.append(getLoadToStack(operand.getIndexOperands().get(0), varTable)); // load index
stringBuilder.append("\tiaload"); // load array[index]
this.changeStackLimits(-1);
} else if (element instanceof Operand) {
Operand operand = (Operand) element;
switch (operand.getType().getTypeOfElement()) {
case INT32, BOOLEAN -> stringBuilder.append("\tiload").append(this.getVariableNumber(operand.getName(), varTable));
case OBJECTREF, STRING, ARRAYREF -> stringBuilder.append("\taload").append(this.getVariableNumber(operand.getName(), varTable));
case THIS -> stringBuilder.append("\taload_0");
default -> stringBuilder.append("; ERROR: getLoadToStack() operand ").append(operand.getType().getTypeOfElement()).append("\n");
}
this.changeStackLimits(+1);
} else {
stringBuilder.append("; ERROR: getLoadToStack() invalid element instance\n");
}
stringBuilder.append("\n");
return stringBuilder.toString();
}
private String getCallInstruction(CallInstruction instruction, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
int numToPop = 0;
switch (instruction.getInvocationType()) {
case invokevirtual -> {
stringBuilder.append(this.getLoadToStack(instruction.getFirstArg(), varTable));
numToPop = 1;
for (Element element : instruction.getListOfOperands()) {
stringBuilder.append(this.getLoadToStack(element, varTable));
numToPop++;
}
stringBuilder.append("\tinvokevirtual ")
.append(this.getClassFullName(((ClassType) instruction.getFirstArg().getType()).getName()))
.append("/").append(((LiteralElement) instruction.getSecondArg()).getLiteral().replace("\"", ""))
.append("(");
for (Element element : instruction.getListOfOperands()) {
stringBuilder.append(this.getFieldDescriptor(element.getType()));
}
stringBuilder.append(")").append(this.getFieldDescriptor(instruction.getReturnType())).append("\n");
if (instruction.getReturnType().getTypeOfElement() != ElementType.VOID) {
numToPop--;
}
}
case invokespecial -> {
stringBuilder.append(this.getLoadToStack(instruction.getFirstArg(), varTable));
numToPop = 1;
stringBuilder.append("\tinvokespecial ");
if (instruction.getFirstArg().getType().getTypeOfElement() == ElementType.THIS) {
stringBuilder.append(this.superClass);
} else {
String className = this.getClassFullName(((ClassType) instruction.getFirstArg().getType()).getName());
stringBuilder.append(className);
}
stringBuilder.append("/").append("<init>(");
for (Element element : instruction.getListOfOperands()) {
stringBuilder.append(this.getFieldDescriptor(element.getType()));
}
stringBuilder.append(")").append(this.getFieldDescriptor(instruction.getReturnType())).append("\n");
if (instruction.getReturnType().getTypeOfElement() != ElementType.VOID) {
numToPop--;
}
}
case invokestatic -> {
numToPop = 0;
for (Element element : instruction.getListOfOperands()) {
stringBuilder.append(this.getLoadToStack(element, varTable));
numToPop++;
}
stringBuilder.append("\tinvokestatic ")
.append(this.getClassFullName(((Operand) instruction.getFirstArg()).getName()))
.append("/").append(((LiteralElement) instruction.getSecondArg()).getLiteral().replace("\"", ""))
.append("(");
for (Element element : instruction.getListOfOperands()) {
stringBuilder.append(this.getFieldDescriptor(element.getType()));
}
stringBuilder.append(")").append(this.getFieldDescriptor(instruction.getReturnType())).append("\n");
if (instruction.getReturnType().getTypeOfElement() != ElementType.VOID) {
numToPop--;
}
}
case NEW -> {
numToPop = -1; // -1 already counting with the return of the new
ElementType elementType = instruction.getReturnType().getTypeOfElement();
if (elementType == ElementType.OBJECTREF) {
for (Element element : instruction.getListOfOperands()) {
stringBuilder.append(this.getLoadToStack(element, varTable));
numToPop++;
}
stringBuilder.append("\tnew ").append(this.getClassFullName(((Operand) instruction.getFirstArg()).getName())).append("\n");
} else if (elementType == ElementType.ARRAYREF) {
for (Element element : instruction.getListOfOperands()) {
stringBuilder.append(this.getLoadToStack(element, varTable));
numToPop++;
}
stringBuilder.append("\tnewarray ");
if (instruction.getListOfOperands().get(0).getType().getTypeOfElement() == ElementType.INT32) {
stringBuilder.append("int\n");
} else {
stringBuilder.append("; only int arrays are implemented\n");
}
} else {
stringBuilder.append("; ERROR: NEW invocation type not implemented\n");
}
}
case arraylength -> {
stringBuilder.append(this.getLoadToStack(instruction.getFirstArg(), varTable));
stringBuilder.append("\tarraylength\n");
}
case ldc -> stringBuilder.append(this.getLoadToStack(instruction.getFirstArg(), varTable));
default -> stringBuilder.append("; ERROR: call instruction not implemented\n");
}
this.changeStackLimits(-numToPop);
return stringBuilder.toString();
}
private String getAssignInstruction(AssignInstruction instruction, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
Operand dest = (Operand) instruction.getDest();
if (dest instanceof ArrayOperand) {
ArrayOperand arrayOperand = (ArrayOperand) dest;
this.changeStackLimits(+1);
stringBuilder.append("\taload").append(this.getVariableNumber(arrayOperand.getName(), varTable)).append("\n"); // load array (ref)
stringBuilder.append(this.getLoadToStack(arrayOperand.getIndexOperands().get(0), varTable)); // load index
} else {
// "iinc" instruction selection
if (instruction.getRhs().getInstType() == BINARYOPER) {
BinaryOpInstruction binaryOpInstruction = (BinaryOpInstruction) instruction.getRhs();
if (binaryOpInstruction.getOperation().getOpType() == OperationType.ADD) {
boolean leftIsLiteral = binaryOpInstruction.getLeftOperand().isLiteral();
boolean rightIsLiteral = binaryOpInstruction.getRightOperand().isLiteral();
LiteralElement literal = null;
Operand operand = null;
if (leftIsLiteral && !rightIsLiteral) {
literal = (LiteralElement) binaryOpInstruction.getLeftOperand();
operand = (Operand) binaryOpInstruction.getRightOperand();
} else if (!leftIsLiteral && rightIsLiteral) {
literal = (LiteralElement) binaryOpInstruction.getRightOperand();
operand = (Operand) binaryOpInstruction.getLeftOperand();
}
if (literal != null && operand != null) {
if (operand.getName().equals(dest.getName())) {
int literalValue = Integer.parseInt((literal).getLiteral());
if (literalValue >= -128 && literalValue <= 127) {
return "\tiinc " + varTable.get(operand.getName()).getVirtualReg() + " " + literalValue + "\n";
}
}
}
}
}
}
stringBuilder.append(this.getInstruction(instruction.getRhs(), varTable));
stringBuilder.append(this.getStore(dest, varTable)); // store in array[index] if (dest instanceof ArrayOperand)
return stringBuilder.toString();
}
private String getStore(Operand dest, HashMap<String, Descriptor> varTable) {
StringBuilder stringBuilder = new StringBuilder();
switch (dest.getType().getTypeOfElement()) {
// BOOLEAN is represented as int in JVM
case INT32, BOOLEAN -> {
if (varTable.get(dest.getName()).getVarType().getTypeOfElement() == ElementType.ARRAYREF) {
stringBuilder.append("\tiastore").append("\n");
this.changeStackLimits(-3);
} else {
stringBuilder.append("\tistore").append(this.getVariableNumber(dest.getName(), varTable)).append("\n");
this.changeStackLimits(-1);
}
}
case OBJECTREF, THIS, STRING, ARRAYREF -> {
stringBuilder.append("\tastore").append(this.getVariableNumber(dest.getName(), varTable)).append("\n");
this.changeStackLimits(-1);
}
default -> stringBuilder.append("; ERROR: getStore()\n");
}
return stringBuilder.toString();
}
private String getVariableNumber(String name, HashMap<String, Descriptor> varTable) {
if (name.equals("this")) {
return "_0";
}
int virtualReg = varTable.get(name).getVirtualReg();
StringBuilder stringBuilder = new StringBuilder();
// virtual reg 0, 1, 2, 3 have specific operation
if (virtualReg < 4) stringBuilder.append("_");
else stringBuilder.append(" ");
stringBuilder.append(virtualReg);
return stringBuilder.toString();
}
private String getFieldDescriptor(Type type) {
StringBuilder stringBuilder = new StringBuilder();
ElementType elementType = type.getTypeOfElement();
if (elementType == ElementType.ARRAYREF) {
stringBuilder.append("[");
elementType = ((ArrayType) type).getArrayType();
}
switch (elementType) {
case INT32 -> stringBuilder.append("I");
case BOOLEAN -> stringBuilder.append("Z");
case OBJECTREF -> {
String name = ((ClassType) type).getName();
stringBuilder.append("L").append(this.getClassFullName(name)).append(";");
}
case STRING -> stringBuilder.append("Ljava/lang/String;");
case VOID -> stringBuilder.append("V");
default -> stringBuilder.append("; ERROR: descriptor type not implemented\n");
}
return stringBuilder.toString();
}
private String getClassFullName(String classNameWithoutImports) {
if (classNameWithoutImports.equals("this")) {
return this.classUnit.getClassName();
}
for (String importName : this.classUnit.getImports()) {
if (importName.endsWith(classNameWithoutImports)) {
return importName.replaceAll("\\.", "/");
}
}
return classNameWithoutImports;
}
private String getBooleanOperationResultToStack() {
return " TRUE" + this.conditionalNumber + "\n"
+ "\ticonst_0\n"
+ "\tgoto NEXT" + this.conditionalNumber + "\n"
+ "TRUE" + this.conditionalNumber + ":\n"
+ "\ticonst_1\n"
+ "NEXT" + this.conditionalNumber++ + ":";
}
private void changeStackLimits(int variation) {
this.currentStack += variation;
this.methodStackLimit = Math.max(this.methodStackLimit, this.currentStack);
}
public static int calculateLimitLocals(Method method) {
Set<Integer> virtualRegs = new TreeSet<>();
virtualRegs.add(0);
for (Descriptor descriptor : method.getVarTable().values()) {
virtualRegs.add(descriptor.getVirtualReg());
}
return virtualRegs.size();
}
}