I'm writing a compiler for a subset of C. I'm trying to implement arrays but I'm stuck on how to know when to allocate space on the stack for my array when the size of the array is not known at compile time.
An array for which I know the size at compile time can be declared using the .space
directive. Otherwise, I could allocate the space on my stack as well by decrementing %esp
and using that as an address.
However, suppose following code:
int f(int param)
{
int x;
x = 2;
if(param < x)
{
// Array declareren van compile time onbekende grootte
int new_array[g(param)];
}
}
There is no way to declare the array at compile time.
The intermediate representation I am using is three address code. So my initial thought would be to create a three adress code statement like ARRAYALLOC _var1
wher _var1
would be the result of the expression that determines the size of the array. This would then allow me, while emitting x86 code, to insert statements that free up space in the stack.
However, I feel that this might not be the idiomatic way of approaching things. Google has left me stranded on this issue.
Could anybody elaborate?
Note: this compiler is a toy compiler. I have learned most things to do it on my own. I.e., it is by far a professional approach and allocating arrays on the stack is not an issue.