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
|
/*
* Code formatter project
* CS 4481
*/
package submit.ast;
import submit.MIPSResult;
import submit.RegisterAllocator;
import submit.SymbolTable;
/**
*
* @author edwajohn
*/
public class BinaryOperator extends AbstractNode implements Expression {
private final Expression lhs, rhs;
private final BinaryOperatorType type;
public BinaryOperator(Expression lhs, BinaryOperatorType type,
Expression rhs) {
this.lhs = lhs;
this.type = type;
this.rhs = rhs;
}
public BinaryOperator(Expression lhs, String type, Expression rhs) {
this.lhs = lhs;
this.type = BinaryOperatorType.fromString(type);
this.rhs = rhs;
}
@Override
public void toCminus(StringBuilder builder, String prefix) {
lhs.toCminus(builder, prefix);
builder.append(" ").append(type).append(" ");
rhs.toCminus(builder, prefix);
}
@Override
public MIPSResult toMIPS(StringBuilder code, StringBuilder data,
SymbolTable symbolTable,
RegisterAllocator registerAllocator) {
switch (type) {
case PLUS:
case MINUS:
case TIMES:
case DIVIDE:
MIPSResult left = lhs.toMIPS(code, data, symbolTable, registerAllocator);
String leftRegister =
registerAllocator.getRegisterOrLoadIntoRegister(left, code);
MIPSResult right = rhs.toMIPS(code, data, symbolTable, registerAllocator);
String rightRegister =
registerAllocator.getRegisterOrLoadIntoRegister(right, code);
String resultRegister = registerAllocator.getAny();
switch (type) {
case PLUS:
code.append(String.format("add %s %s %s\n", resultRegister,
leftRegister, rightRegister));
break;
case MINUS:
code.append(String.format("sub %s %s %s\n", resultRegister,
leftRegister, rightRegister));
break;
case TIMES:
code.append(String.format("mult %s %s\n", leftRegister, rightRegister));
code.append(String.format("mflo %s\n", resultRegister));
break;
case DIVIDE:
code.append(String.format("div %s %s\n", leftRegister, rightRegister));
code.append(String.format("mflo %s\n", resultRegister));
break;
default:
break;
}
registerAllocator.clear(leftRegister);
registerAllocator.clear(rightRegister);
return MIPSResult.createRegisterResult(resultRegister, VarType.INT);
default:
break;
}
return MIPSResult.createVoidResult();
}
}
|