Skip to content

Commit

Permalink
Merge pull request #94 from vacantron/dev
Browse files Browse the repository at this point in the history
Eliminate redundant branches
  • Loading branch information
jserv authored Dec 16, 2023
2 parents f8324c2 + aa336a2 commit 9408e2b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
22 changes: 16 additions & 6 deletions src/arm-codegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ void update_elf_offset(ph2_ir_t *ph2_ir)
elf_offset += 12;
return;
case OP_branch:
if (ph2_ir->is_branch_detached)
elf_offset += 12;
else
elf_offset += 8;
return;
case OP_return:
elf_offset += 24;
return;
Expand Down Expand Up @@ -156,6 +161,12 @@ void cfg_flatten()
/* restore sp */
flatten_ir->src1 = bb->belong_to->func->stack_size;

if (insn->op == OP_branch) {
/* In SSA, we index `else_bb` first, and then `then_bb` */
if (insn->else_bb != bb->rpo_next)
flatten_ir->is_branch_detached = 1;
}

update_elf_offset(flatten_ir);
}
}
Expand Down Expand Up @@ -264,13 +275,12 @@ void emit_ph2_ir(ph2_ir_t *ph2_ir)
abort();
return;
case OP_branch:
ofs = ph2_ir->else_bb->elf_offset;
emit(__movw(__AL, __r8, ofs + elf_code_start));
emit(__movt(__AL, __r8, ofs + elf_code_start));
emit(__teq(rn));
emit(__b(__NE, 8));
emit(__blx(__AL, __r8));
emit(__b(__AL, ph2_ir->then_bb->elf_offset - elf_code_idx));
if (ph2_ir->is_branch_detached) {
emit(__b(__NE, 8));
emit(__b(__AL, ph2_ir->else_bb->elf_offset - elf_code_idx));
} else
emit(__b(__NE, ph2_ir->then_bb->elf_offset - elf_code_idx));
return;
case OP_jump:
emit(__b(__AL, ph2_ir->next_bb->elf_offset - elf_code_idx));
Expand Down
1 change: 1 addition & 0 deletions src/defs.h
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ struct ph2_ir {
basic_block_t *then_bb;
basic_block_t *else_bb;
struct ph2_ir *next;
int is_branch_detached;
};

typedef struct ph2_ir ph2_ir_t;
Expand Down
6 changes: 5 additions & 1 deletion src/reg-alloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,8 @@ void reg_alloc()

fn_t *fn;
for (fn = FUNC_LIST.head; fn; fn = fn->next) {
fn->visited++;

if (!strcmp(fn->func->return_def.var_name, "main"))
MAIN_BB = fn->bbs;

Expand Down Expand Up @@ -319,6 +321,8 @@ void reg_alloc()
for (bb = fn->bbs; bb; bb = bb->rpo_next) {
int is_pushing_args = 0, args = 0;

bb->visited++;

insn_t *insn;
for (insn = bb->insn_list.head; insn; insn = insn->next) {
ph2_ir_t *ir;
Expand Down Expand Up @@ -560,7 +564,7 @@ void reg_alloc()

/* jump to the beginning of loop or over the else block */
if (bb->next->visited == fn->visited ||
bb->next->visited != bb->rpo + 1) {
bb->next->rpo != bb->rpo + 1) {
ph2_ir_t *ir = bb_add_ph2_ir(bb, OP_jump);
ir->next_bb = bb->next;
}
Expand Down

0 comments on commit 9408e2b

Please sign in to comment.