const table

This commit is contained in:
Yaossg 2024-11-29 16:00:22 +08:00
parent 967a203414
commit 66505c1389
2 changed files with 51 additions and 23 deletions

52
boot.c
View file

@ -381,17 +381,14 @@ void next_token() {
token_data = parse_string();
dedup_string();
} else if (ch == '.') {
int ch2 = getchar();
if (ch2 == '.') {
int ch3 = getchar();
if (ch3 == '.') {
token_type = 0;
if (getchar() == '.') {
if (getchar() == '.') {
token_type = TOKEN_ELLIPSIS;
} else {
eprintf("unexpected character: %c\n", ch3);
exit(1);
}
} else {
eprintf("unexpected character: %c\n", ch2);
}
if (token_type != TOKEN_ELLIPSIS) {
eprintf("expecting '...'\n");
exit(1);
}
} else if (is_digit(ch)) {
@ -467,6 +464,9 @@ int max_reg_id = 18;
int indirection[4096];
int overflow[4096];
int const_table[4096]; // id -> value
int is_const[4096];
const int REG_ZERO = 0;
const int REG_RA = 1;
const int REG_SP = 2;
@ -837,10 +837,19 @@ int lookup_from_slot(int slot) {
return materialize_address(reg, local_type[slot], local_marker[slot]);
}
int load_imm(int imm) {
if (imm == 0) return REG_ZERO;
int reg = next_reg(TYPE_INT);
_asm_i("li", reg, "", "", imm);
return reg;
}
int lookup(int id) {
int slot = local_table[id];
if (slot) {
return lookup_from_slot(slot);
if (local_table[id]) {
return lookup_from_slot(local_table[id]);
}
if (is_const[id]) {
return load_imm(const_table[id]);
}
const char* name = id_table + id_lut[id];
if (global_marker[id]) {
@ -1066,10 +1075,7 @@ int parse_primary_expr() {
if (token_type == TOKEN_EOF) {
exit(1);
} else if (token_type == TOKEN_NUMBER) {
if (token_data == 0) return REG_ZERO;
int reg = next_reg(TYPE_INT);
_asm_i("li", reg, "", "", token_data);
return reg;
return load_imm(token_data);
} else if (token_type == TOKEN_ID) {
next_token();
if (token_type == TOKEN_PAREN_LEFT) {
@ -1695,16 +1701,28 @@ void parse_global_variable(int id, const char* name, int type) {
}
void parse_global_declaration() {
int is_const_int = 1;
if (token_type != TOKEN_CONST) {
is_const_int = 0;
}
int type = parse_type();
if (type < 0) {
eprintf("expecting type for global declaration\n");
exit(1);
}
if (type != TYPE_INT) {
is_const_int = 0;
}
expect_token(TOKEN_ID);
int id = token_data;
char* name = id_table + id_lut[id];
next_token();
if (token_type == TOKEN_PAREN_LEFT) {
if (is_const_int && token_type == TOKEN_ASSIGN) {
expect_token(TOKEN_NUMBER);
const_table[id] = token_data;
is_const[id] = 1;
expect_token(TOKEN_SEMICOLON);
} else if (token_type == TOKEN_PAREN_LEFT) {
declare_global(id, MARKER_FUNCTION, type);
parse_function(name);
} else {