Function Call Code Generation
What you'll learn: You'll learn how compilers translate function calls into low-level instructions that manage arguments, preserve registers, and coordinate stack operations between caller and callee.
The Challenge of Function Calls
When generating code for a function call, the compiler must orchestrate a careful handoff between the calling code and the called function. Both sides need to agree on how arguments are passed, where return values go, and which registers can be safely modified—this agreement is called a calling convention.
Three Core Responsibilities
1. Argument Passing
The compiler must generate code to place arguments where the called function expects them. Common approaches include:
- Registers: First few arguments go in designated registers (fast access)
- Stack: Additional arguments pushed onto the stack in a specific order
2. Stack Management
Before the call, the compiler generates instructions to:
- Push arguments onto the stack (if needed)
- Save the return address (where to resume after the function completes)
- Allocate space for the callee's local variables (via stack frame setup)
After the call returns, the stack must be cleaned up, removing arguments and restoring the stack pointer.
3. Register Preservation
Registers are categorized as:
- Caller-saved: The calling function must save these before the call if it needs their values afterward
- Callee-saved: The called function must preserve these and restore them before returning
The compiler generates save/restore instructions based on which registers are live across the call.
The Assembly Pattern
A typical calling sequence looks like: save caller-saved registers → place arguments → execute call instruction → restore registers → retrieve return value.
Key Takeaway: Function call code generation requires the compiler to implement calling conventions through careful coordination of argument passing mechanisms, stack frame management, and strategic register saving/restoring to ensure both caller and callee can communicate correctly.