Arm64 Calling convention
The Arm64 calling convention is a set of rules that dictate how functions receive parameters and return values, how the stack is managed, and how registers are used. This ensures that code generated by different compilers can interoperate.
Key Points of the Arm64 Calling Convention
Registers:
General-purpose registers: x0 to x30.
Stack pointer: sp.
Link register: x30 (also known as lr).
Frame pointer: x29 (also known as fp).
Parameter Passing:
The first eight integer or pointer arguments are passed in registers x0 to x7.
Additional arguments are passed on the stack.
Floating-point arguments are passed in registers v0 to v7.
Return Values:
The primary return value is placed in x0.
If a function returns a structure or a union, the address of the return value is passed in x8.
Stack Management:
The stack must be 16-byte aligned at the point of a function call.
The caller is responsible for allocating space for the return address and any arguments that do not fit in registers.
Callee-saved Registers:
Registers x19 to x28, x29 (fp), and x30 (lr) must be preserved by the callee.
The callee must save and restore these registers if it uses them.
Example
Here is an example of a simple function in Arm64 assembly that adds two integers:
Explanation (1)
The function
addtakes two integer arguments in registersx0andx1.It adds the values in
x0andx1, storing the result inx0.The
retinstruction returns to the caller, with the result inx0.
Example with Stack Usage
Here is an example of a function that uses the stack to store local variables:
Explanation (2)
The function
sum_arraytakes two arguments: a pointer to an array inx0and the array length inx1.It saves the frame pointer (
x29) and link register (x30) on the stack.It sets up the frame pointer and allocates space for local variables.
It initializes the sum (
x2) and index (x3) to 0.It enters a loop to iterate over the array, loading each element, adding it to the sum, and incrementing the index.
After the loop, it deallocates the local variables and restores the frame pointer and link register.
It moves the sum to the return register (
x0) and returns.
These examples illustrate the basic principles of the Arm64 calling convention, including register usage, parameter passing, and stack management.