英文:
Where exactly compilers store local variables
问题
我正在编写一个针对较旧的8位处理器(C的一个小子集)的编译器,该编译器应该生成汇编代码(或直接生成机器代码,不重要)。
本地变量应存储在哪里?在(正常调用的)堆栈上还是在某个单独的数据堆栈上?所以,在函数的开头是否应该保留(可能初始化)空间,并在返回时进行清理?注意,中断可能随时修改(调用)堆栈指针下方的区域。
英文:
I'm in the process of writing a compiler for an older 8 bit processor (a tiny subset of C), that should generate assembler code (or machine code directly, doesn't matter).
Where should local variables be stored? On the (normal call) stack or some separate data stack? So should at the beginning of a function the space be reserved (maybe initialized) and on the return cleaned up? Note, that interrupts could modify the area below the (call) stack pointer at any time.
答案1
得分: 1
常见做法是将本地变量存储在处理器寄存器中,如果可能的话。(在8位机器上,有时这不是一个选项。)其余的本地变量通常存储在正常的数据栈上。
通常为函数生成的入口代码执行以下操作:
- 通过调整堆栈指针在堆栈上保留一定数量的字节。
- 存储被调用者保存的寄存器,如果需要的话。(即,按照调用约定,不应该在函数调用过程中更改的寄存器。)
- 初始化本地变量。
退出代码通常执行以下操作:
- 恢复被调用者保存的寄存器。
- 通过在堆栈中的另一方向调整堆栈指针来取消保留的堆栈区域。
正如您自己注意到的,函数永远不能依赖于堆栈指针“错误”一侧的数据,因为这些数据可能会被中断函数修改。
英文:
Common practice is to store local variables in processor registers, if possible. (On an 8-bit machine this sometimes isn't an option.) The remaining local variables are typically stored on the normal data stack.
The entry code emitted for a function typically does the following:
- Reserve a number of bytes on the stack, by adjusting the stack pointer.
- Store callee-save registers, if needed. (I.e. registers that the calling-convention says should not be changes over the function call.)
- Initializes local variables.
The exit code typically does the following:
- Restore the callee-save registers.
- Unreserve the area on the stack by adjusting the stack pointer in the other direction.
As you noted yourself, a function can never rely on data on the "wrong" side of the stack pointer, as that can be modified by interrupt functions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论