frankpfenning / C0

C0 Language
4 stars 0 forks source link

C0VM doesn't give right number of locals to a function #59

Open robsimmons opened 10 years ago

robsimmons commented 10 years ago

If we compile this function

int mid (int lower, int upper) {
  int mid = lower + (upper - lower)/2;
  return mid;
}

int main () {
  return mid(3,6);
}

Then the main function has 3 local variables: I think we're giving each function in the program the same number of local variables, the upper bound of all the local variables in all the functions.

C0 C0 FF EE       # magic number
00 09             # version 4, arch = 1 (64 bits)

00 00             # int pool count
# int pool

00 00             # string pool total size
# string pool

00 02             # function count
# function_pool

#<main>
00 00             # number of arguments = 0
00 03             # number of local variables = 3
00 08             # code length = 8 bytes
10 03    # bipush 3        # 3
10 06    # bipush 6        # 6
B8 00 01 # invokestatic 1  # mid(3, 6)
B0       # return          #

#<mid>
00 02             # number of arguments = 2
00 03             # number of local variables = 3
00 10             # code length = 16 bytes
15 00    # vload 0         # lower
15 01    # vload 1         # upper
15 00    # vload 0         # lower
64       # isub            # (upper - lower)
10 02    # bipush 2        # 2
6C       # idiv            # ((upper - lower) / 2)
60       # iadd            # (lower + ((upper - lower) / 2))
36 02    # vstore 2        # mid = (lower + ((upper - lower) / 2));
15 02    # vload 2         # mid
B0       # return          #

00 00             # native count
# native pool
ishantheperson commented 3 years ago

Adding the highlighted line seems to fix the problem but I wonder if it has any side effects (num_vars is global for some reason). reset_num_vars sets it back to 0. Currently c0vm-trans.sml computes the number of variables by maintaining a list of variables in scope as it crawls the function. Then every time a new scope is created, it checks if the current number of variables in scope is greater than num_vars. If so it updates num_vars. image