Skip to content

Commit

Permalink
Initialize unspecified elements
Browse files Browse the repository at this point in the history
  • Loading branch information
leewei05 authored and Lai-YT committed Apr 28, 2024
1 parent 99c942e commit 35f9bff
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/qbe_ir_generator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -153,26 +153,33 @@ void QbeIrGenerator::Visit(const DeclVarNode& decl) {

void QbeIrGenerator::Visit(const DeclArrNode& arr_decl) {
int base_addr_num = NextLocalNum();
WriteInstr_("{} =l alloc{} {}", FuncScopeTemp{base_addr_num},
arr_decl.type->element_type().size(), arr_decl.type->size());
auto element_size = arr_decl.type->element_type().size();
WriteInstr_("{} =l alloc{} {}", FuncScopeTemp{base_addr_num}, element_size,
arr_decl.type->size());
id_to_num[arr_decl.id] = base_addr_num;

for (auto i = std::size_t{0}, e = arr_decl.init_list.size(); i < e; ++i) {
auto& arr_init = arr_decl.init_list.at(i);
arr_init->Accept(*this);
for (auto i = std::size_t{0}, e = arr_decl.type->len(); i < e; ++i) {
if (i < arr_decl.init_list.size()) {
auto& arr_init = arr_decl.init_list.at(i);
arr_init->Accept(*this);
}

const int offset = NextLocalNum();
WriteInstr_("{} =l extsw {}", FuncScopeTemp{offset},
i * arr_init->type->size());
WriteInstr_("{} =l extsw {}", FuncScopeTemp{offset}, i * element_size);

// res_addr = base_addr + offset
const int res_addr_num = NextLocalNum();
WriteInstr_("{} =l add {}, {}", FuncScopeTemp{res_addr_num},
FuncScopeTemp{base_addr_num}, FuncScopeTemp{offset});

// store initial value to res_addr
int init_val_num = num_recorder.NumOfPrevExpr();
WriteInstr_("storew {}, {}", FuncScopeTemp{init_val_num},
FuncScopeTemp{res_addr_num});
if (i < arr_decl.init_list.size()) {
int init_val_num = num_recorder.NumOfPrevExpr();
WriteInstr_("storew {}, {}", FuncScopeTemp{init_val_num},
FuncScopeTemp{res_addr_num});
} else {
// set remaining elements as 0
WriteInstr_("storew 0, {}", FuncScopeTemp{res_addr_num});
}
}
}

Expand Down
5 changes: 5 additions & 0 deletions test/codegen/array.c
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,10 @@ int main() {
__builtin_print(d[2]);
__builtin_print(d[3]);

int e[3] = {1};
__builtin_print(e[0]);
__builtin_print(e[1]);
__builtin_print(e[2]);

return 0;
}
3 changes: 3 additions & 0 deletions test/codegen/array.exp
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@
2
3
4
1
0
0

0 comments on commit 35f9bff

Please sign in to comment.