Skip to content

Commit

Permalink
Fix unsafely CSE for global variable
Browse files Browse the repository at this point in the history
The global variable might be changed by the subroutine. Considering
the following code:

```
int e = arr[idx];
subroutine_changing_idx();
int d = arr[idx];
```

We cannot invoke the CSE and replace `d = arr[idx]` with `d = e` safely.

Fix #112
  • Loading branch information
vacantron committed Feb 29, 2024
1 parent 10153eb commit 12add87
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/ssa.c
Original file line number Diff line number Diff line change
Expand Up @@ -1067,6 +1067,11 @@ int cse(insn_t *insn, basic_block_t *bb)
return 0;

var_t *def = NULL, *base = prev->rs1, *idx = prev->rs2;
if (base->is_global)
return 0;
if (idx->is_global)
return 0;

basic_block_t *b;
insn_t *i = prev;
for (b = bb;; b = b->idom) {
Expand Down Expand Up @@ -1097,7 +1102,7 @@ int cse(insn_t *insn, basic_block_t *bb)

if (prev->prev) {
insn->prev = prev->prev;
prev->next = insn;
prev->prev->next = insn;
} else {
bb->insn_list.head = insn;
insn->prev = NULL;
Expand All @@ -1110,7 +1115,6 @@ int cse(insn_t *insn, basic_block_t *bb)

void optimize()
{
int changed = 0;
fn_t *fn;
for (fn = FUNC_LIST.head; fn; fn = fn->next) {
/* basic block level (control flow) optimizations */
Expand All @@ -1120,7 +1124,9 @@ void optimize()
/* instruction level optimizations */
insn_t *insn;
for (insn = bb->insn_list.head; insn; insn = insn->next) {
changed |= cse(insn, bb);
if (cse(insn, bb))
continue;

/* more optimizations */
}
}
Expand Down
19 changes: 19 additions & 0 deletions tests/driver.sh
Original file line number Diff line number Diff line change
Expand Up @@ -547,4 +547,23 @@ int main()
}
EOF

# optimizer
try_ 1 << EOF
int i = 0;
void func()
{
i = 1;
}
int main()
{
char arr[2], t;
arr[0] = 0;
arr[1] = 1;
t = arr[i];
func();
t = arr[i];
return t;
}
EOF

echo OK

0 comments on commit 12add87

Please sign in to comment.