Skip to content

Commit

Permalink
Implement four out of five suggested optimizations (#37)
Browse files Browse the repository at this point in the history
Fix #27

The remaining suggestion requires understanding where a label point to
so that it can be replaced by its literal equivalent. See #36.
  • Loading branch information
samueldr authored Jul 17, 2024
1 parent af02db1 commit 09f53d0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/chibi.h
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,7 @@ typedef enum {
EOR2 = EOR | flag_2,
SFT2 = SFT | flag_2,

ORAk = ORA | flag_k,
STA2k = STA2 | flag_k,
STH2kr = STH2 | flag_k | flag_r,
POP2r = POP2 | flag_r,
Expand Down
36 changes: 36 additions & 0 deletions src/optimize.c
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,42 @@ static bool optimize_pass(Instruction *prog, int stage) {
continue;
}

//
// https://github.com/lynn/chibicc/issues/27
//

// instances of #00 ORA, [can] be removed.
if (IsLit(prog, 0) && prog->next->opcode == ORA) {
memcpy(prog, prog->next->next, sizeof(Instruction));
changed = true;
continue;
}

// [SWP] static arithmetic operation e.g. #abcd SWP, could be #cdab.
if (prog->opcode == LIT2 && prog->next->opcode == SWP) {
unsigned short tmp = prog->literal;
prog->literal = ((tmp & 0xFF) << 8) | ((tmp & 0xFF00) >> 8 );
prog->next = prog->next->next;
changed = true;
continue;
}

// DUP2 #0000 EQU2, [can] be turned into ORAk #00 EQU
if (prog->opcode == DUP2 && IsLit2(prog->next, 0) && prog->next->next->opcode == EQU2) {
prog ->opcode = ORAk;
prog->next ->opcode = LIT;
prog->next->next->opcode = EQU;
changed = true;
continue;
}

// #0000 SWP, to #0000
if (IsLit2(prog, 0) && prog->next->opcode == SWP) {
memcpy(prog->next, prog->next->next, sizeof(Instruction));
changed = true;
continue;
}

prog = prog->next;
}
return changed;
Expand Down

0 comments on commit 09f53d0

Please sign in to comment.