Skip to content

Commit 734f163

Browse files
committed
Tacky code generation for Chapter 12
1 parent 4d2f600 commit 734f163

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

src/com/plasstech/lang/c/codegen/tacky/TackyCodeGen.java

+10-6
Original file line numberDiff line numberDiff line change
@@ -375,17 +375,21 @@ public TackyVal visit(FunctionCall n) {
375375
public TackyVal visit(Cast n) {
376376
// p 260
377377
TackyVal result = n.exp().accept(this);
378+
Type innerType = n.exp().type();
378379
Type targetType = n.targetType();
379-
if (targetType.equals(n.exp().type())) {
380+
if (targetType.equals(innerType)) {
380381
return result;
381382
}
382-
TackyVar dst = makeTackyVariable("cast_to_" + n.targetType().name(), n.type());
383-
if (targetType.equals(Type.LONG)) {
384-
emit(new TackySignExtend(result, dst));
385-
} else if (targetType.equals(Type.INT)) {
383+
// page 282
384+
TackyVar dst = makeTackyVariable("cast_to_" + targetType.name(), targetType);
385+
if (targetType.size() == innerType.size()) {
386+
emit(new TackyCopy(result, dst));
387+
} else if (targetType.size() < innerType.size()) {
386388
emit(new TackyTruncate(result, dst));
389+
} else if (innerType.signed()) {
390+
emit(new TackySignExtend(result, dst));
387391
} else {
388-
throw new UnsupportedOperationException("Cannot generate cast");
392+
emit(new TackyZeroExtend(result, dst));
389393
}
390394
return dst;
391395
}

src/com/plasstech/lang/c/codegen/tacky/TackyInstruction.java

+2
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ interface Visitor<R> {
2626
R visit(TackySignExtend op);
2727

2828
R visit(TackyTruncate op);
29+
30+
R visit(TackyZeroExtend op);
2931
}
3032

3133
<R> R accept(Visitor<R> visitor);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.plasstech.lang.c.codegen.tacky;
2+
3+
public record TackyZeroExtend(TackyVal src, TackyVal dst) implements TackyInstruction {
4+
@Override
5+
public <R> R accept(Visitor<R> visitor) {
6+
return visitor.visit(this);
7+
}
8+
}

0 commit comments

Comments
 (0)