So, obviously, the C compiler, when compiling gotos, before inserting the jump instruction, needs to insert sub stack_pointer, number or add stack_pointer, number in order to match the fact that the stack pointer will now presumably point to a different local variable in a different scope. Without variable length arrays, this can, I suppose, be implemented by the C compiler, before compiling the function, calculating for each label in the function what is the difference in the stack pointer between that label and the beginning of a function. But how can it do that if there are variable length arrays and that difference isn't known at the compile time?
- $\begingroup$ If locals are addressed via offsets from a fixed frame pointer, instead of from the stack pointer, it may not be necessary to adjust the stack pointer. For keeping track of the addresses of VLAs, the compiler can simply invent a local variable to hold a pointer to it, which, like any other local, may be held in a register or spilled to a known offset from the frame / stack pointer. $\endgroup$Nate Eldredge– Nate Eldredge2025-09-23 00:35:26 +00:00Commented Sep 23 at 0:35
1 Answer
The stack pointer on scope entry can be saved into a register (or on the stack) and then restored on scope exit.
And you should have rules about any control flow that would skip the runtime stack allocation and how that interacts with the memory that would have been allocated. C for example doesn't allow jumping past the allocation of a VLA.
LLVM for example has IR intrinsics stacksave and stackrestore for this which specifically calls out the C99 variable length arrays as a usecase..
Moreover you can move all compile-time stack manipulation to the start of the function and make only a single adjustment to the stack pointer.