LangProc / langproc-2021-cw

5 stars 4 forks source link

Max number of arguments for a function #20

Closed neagualexa closed 2 years ago

neagualexa commented 2 years ago

Hi I was using godbolt and realised that if a function has more than 4 arguments (total number of argument registers for MIPS, $4-$7), the MIPS code generated will ignore the rest of the parameters. This can be seen below: int f(int d, int e, int z, int a, int b, int c) { return 4; }

f: addiu $sp,$sp,-8 sw $fp,4($sp) move $fp,$sp .. sw $4,8($fp) sw $5,12($fp) sw $6,16($fp) sw $7,20($fp) ... li $2,4 # 0x4 move $sp,$fp lw $fp,4($sp) addiu $sp,$sp,8 jr $31 nop

So the stack pointer only stores the first 4 arguments of the function (up to address $fp+20). However, in the compilers_tests/functions folder, we have a test where the called g() has 5 arguments. Are we expected to ignore the 5th argument or do we assume that that parameter is stored in register $8?

Am I understanding the situation right?

ymherklotz commented 2 years ago

The main problem is that you are not using the arguments, so you are not seeing where they are stored. Maybe the following will show it a bit better:

int f(int d, int e, int z, int a, int b, int c) { 
    return a+b+c+d+e+z; 
}

But as a quick explanation, up to four integers can be passed through registers, however, any other arguments are passed on the stack of the calling function, as you should be able to see by compiling the function above.

The MIPS ABI (page 3-15 to 3-20) has a more detailed description of how arguments are passed, so that might help clear things up.

neagualexa commented 2 years ago

So the extra arguments (5th onwards) can be found directly in the following addresses (addr 24, 28...) in the stack? Will there not be a possibility there a variable could be stored at the same location in stack as one of the arguments? Or can we enforce that anything that requires to be stored in the stack will be stored after those used addresses?

ymherklotz commented 2 years ago

That is part of the calling convention. To call your function, the calling function must ensure that it puts the arguments on the correct location on it's stack, so as to get the Figure 3-21 in the ABI. So it will leave space for the 4 arguments passed by registers, and then location 16($sp) in the original function stack frame will have the 5th argument, and 20($sp) will have the 6th argument.

This is also what you'll have to implement if you want to call functions that take more than 4 arguments.