Post

AMD64 Calling Convention for Linux and macOS

The AMD64 calling convention defines how functions receive parameters from their caller and how they return a result. Adhering to this calling convention ensures proper data handling and register usage in function calls.

Here is a comprehensive list of the registers used in the AMD64 calling convention for Linux and macOS:

  • %rax: Used for returning a value from a function by the caller.
  • %rbx: Optionally used as a base pointer.
  • %rcx: Used to pass the 4th argument to a function by the caller.
  • %rdx: Used to pass the 3rd argument to a function and optionally to return a second value by the caller.
  • %rsp: Stack pointer.
  • %rbp: Frame pointer.
  • %rsi: Used to pass the 2nd argument to a function by the caller.
  • %rdi: Used to pass the 1st argument to a function by the caller.
  • %r8: Used to pass the 5th argument to a function by the caller.
  • %r9: Used to pass the 6th argument to a function by the caller.
  • %r10, %r11, %r12, %r13, %r14, %r15: Temporary registers.

The responsibility for saving the contents of certain registers depends on whether they are used by the caller or the callee. The following table summarizes the register usage and saving responsibility:

RegisterUseSaved By
%raxReturn valueCaller
%rbxBase pointerCallee (Optional)
%rcx4th argumentCaller
%rdx3rd argumentCaller
%rspStack pointer-
%rbpFrame pointerCallee
%rsi2nd argumentCaller
%rdi1st argumentCaller
%r85th argumentCaller
%r96th argumentCaller
%r10Temporary registerCaller
%r11Temporary registerCaller
%r12Temporary registerCallee
%r13Temporary registerCallee
%r14Temporary registerCallee
%r15Temporary registerCallee

Registers saved by the callee are typically spilled to the current function’s stack frame, while the caller is responsible for setting up the arguments for the callee in the appropriate registers.

Understanding and following the AMD64 calling convention is essential for proper function call handling and interoperability between different code modules in Linux and macOS environments. By adhering to this convention, developers can ensure efficient and reliable program execution.

This Assembly Instruction Reference is also a valuable resource.

Reference

This post is licensed under CC BY 4.0 by the author.