Incomputer science, acalling convention is animplementation-level (low-level) scheme for howsubroutines or functions receiveparameters from their caller and how theyreturn a result.[1] When some code calls a function, design choices have been taken for where and how parameters are passed to that function, and where and how results are returned from that function, with these transfers typically done via certain registers or within astack frame on thecall stack. There are design choices for how the tasks of preparing for a function call and restoring the environment after the function has completed are divided between the caller and the callee. Some calling convention specifies the way every function should get called. The correct calling convention should be used for every function call, to allow the correct and reliable execution of the whole program using these functions.
Calling conventions are usually considered part of theapplication binary interface (ABI). They may be considered acontract between the caller and the called function.[1]
The names or meanings of the parameters and return values are defined in theapplication programming interface (API, as opposed to ABI), which is a separate though related concept to ABI and calling convention. The names of members within passed structures and objects would also be considered part of the API, and not ABI. Sometimes APIs do include keywords to specify the calling convention for functions.
Calling conventions do not typically include information on handling lifespan of dynamically allocated structures and objects. Other supplementary documentation may state where the responsibility for freeing up allocated memory lies.
Calling conventions are unlikely to specify the layout of items within structures and objects, such as byte ordering or structure packing.
For some languages, the calling convention includes details of error or exception handling, (e.g.Go,Java) and for others, it does not (e.g.C++).
ForRemote procedure calls, there is an analogous concept calledMarshalling.
Calling conventions may be related to a particular programming language'sevaluation strategy, but most often are not considered part of it (or vice versa), as the evaluation strategy is usually defined on a higher abstraction level and seen as a part of the language rather than as a low-level implementation detail of a particular language'scompiler.
Calling conventions may differ in:
Sometimes multiple calling conventions appear on a single platform; a given platform and language implementation may offer a choice of calling conventions. Reasons for this include performance, adaptation of conventions of other popular languages, and restrictions or conventions imposed by various "computing platforms".
Many architectures only have one widely used calling convention, often suggested by the architect. ForRISCs including SPARC, MIPS, andRISC-V, registers names based on this calling convention are often used. For example, MIPS registers$4 through$7 have "ABI names"$a0 through$a3, reflecting their use for parameter passing in the standard calling convention. (RISC CPUs have many equivalent general-purpose registers so there's typically no hardware reason for giving them names other than numbers.)
The calling convention of a given program's language may differ from the calling convention of the underlying platform, OS, or of some library being linked to. For example, on32-bit Windows, operating system calls have thestdcall calling convention, whereas manyC programs that run there use thecdecl calling convention. To accommodate these differences in calling convention, compilers often permit keywords that specify the calling convention for a given function. Thefunction declarations will include additional platform-specific keywords that indicate the calling convention to be used. When handled correctly, the compiler will generate code to call functions in the appropriate manner.
Some languages allow the calling convention for a function to be explicitly specified with that function; other languages will have some calling convention but it will be hidden from the users of that language, and therefore will not typically be a consideration for the programmer.
The 32-bit version of thex86 architecture is used with many different calling conventions. Due to the small number of architectural registers, and historical focus on simplicity and small code-size, many x86 calling conventions pass arguments on the stack. The return value (or a pointer to it) is returned in a register. Some conventions use registers for the first few parameters which may improve performance, especially for short and simpleleaf routines very frequently invoked (i.e. routines that do not call other routines).
Example call:
pushEAX; pass some register resultpushdword[EBP+20]; pass some memory variable (FASM/TASM syntax)push3; pass some constantcallcalc; the returned result is now in EAX
Typical callee structure: (some or all (except ret) of the instructions below may be optimized away in simple procedures). Some conventions leave the parameter space allocated, using plainret instead ofret imm16. In that case, the caller couldadd esp,12 in this example, or otherwise deal with the change to ESP.
calc:pushEBP; save old frame pointermovEBP,ESP; get new frame pointersubESP,localsize; reserve stack space for locals..; perform calculations, leave result in EAX.movESP,EBP; free space for localspopEBP; restore old frame pointerretparamsize; free parameter space and return.
The 64-bit version of the x86 architecture, known asx86-64, AMD64, and Intel 64, has two calling sequences in common use. One calling sequence, defined by Microsoft, is used on Windows; the other calling sequence, specified in the AMD64 System V ABI, is used byUnix-like systems and, with some changes, byOpenVMS. As x86-64 has more general-purpose registers than does 32-bit x86, both conventions pass some arguments in registers.
The standard 32-bitARM calling convention allocates the 16 general-purpose registers as:
If the type of value returned is too large to fit in r0 to r3, or whose size cannot be determined statically at compile time, then the caller must allocate space for that value at run time, and pass a pointer to that space in r0.
Subroutines must preserve the contents of r4 to r11 and the stack pointer (perhaps by saving them to the stack in thefunction prologue, then using them as scratch space, then restoring them from the stack in thefunction epilogue). In particular, subroutines that call other subroutinesmust save the return address in the link register r14 to the stack before calling those other subroutines. However, such subroutines do not need to return that value to r14—they merely need to load that value into r15, the program counter, to return.
The ARM calling convention mandates using a full-descending stack. In addition, the stack pointer must always be 4-byte aligned, and must always be 8-byte aligned at a function call with a public interface.[3]
This calling convention causes a "typical" ARM subroutine to:
The 64-bit ARM (AArch64) calling convention allocates the 31 general-purpose registers as:[4]
All registers starting withx have a corresponding 32-bit register prefixed withw. Thus, a 32-bit x0 is called w0.
Similarly, the 32 floating-point registers are allocated as:[5]
RISC-V has a defined calling convention with two flavors, with or without floating point.[6] It passes arguments in registers whenever possible.
ThePOWER,PowerPC, andPower ISA architectures have a large number of registers so most functions can pass all arguments in registers forsingle level calls. Additional arguments are passed on the stack, and space for register-based arguments is also always allocated on the stack as a convenience to the called function in case multi-level calls are used (recursive or otherwise) and the registers must be saved. This is also of use invariadic functions, such asprintf(), where the function's arguments need to be accessed as an array. A single calling convention is used for all procedural languages.
Branch-and-link instructions store the return address in a speciallink register separate from the general-purpose registers; a routine returns to its caller with a branch instruction that uses the link register as the destination address.Leaf routines do not need to save or restore the link register; non-leaf routines must save the return address before making a call to another routine and restore it before it returns, saving it by using the Move From Special Purpose Register instruction to move the link register to a general-purpose register and, if necessary, then saving it to the stack, and restoring it by, if it was saved to the stack, loading the saved link register value to a general-purpose register, and then using the Move To Special Purpose Register instruction to move the register containing the saved link-register value to the link register.
The O32[7]ABI isthe most commonly used ABI, owing to its status as the originalSystem V ABI for MIPS.[8] It is strictly stack-based, with only four registers$a0-$a3 available to pass arguments. This perceived slowness, along with an antique floating-point model with 16 registers only, has encouraged the proliferation of many other calling conventions. The ABI took shape in 1990 and was never updated since 1994. It is only defined for 32-bit MIPS, butGCC has created a 64-bit variation called O64.[9]
For 64-bit, the N64 ABI (not related toNintendo 64) by Silicon Graphics is most commonly used. The most important improvement is that eight registers are now available for argument passing; It also increases the number of floating-point registers to 32. There is also an ILP32 version called N32, which uses 32-bit pointers for smaller code, analogous to thex32 ABI. Both run under the 64-bit mode of the CPU.[9]
A few attempts have been made to replace O32 with a 32-bit ABI that resembles N32 more. A 1995 conference came up with MIPS EABI, for which the 32-bit version was quite similar.[10] EABI inspiredMIPS Technologies to propose a more radical "NUBI" ABI that additionally reuses argument registers for the return value.[11] MIPS EABI is supported by GCC but notLLVM; neither supports NUBI.
For all of O32 and N32/N64, the return address is stored in a$ra register. This is automatically set with the use of theJAL (jump and link) orJALR (jump and link register) instructions. The stack grows downwards.
TheSPARC architecture, unlike mostRISC architectures, is built onregister windows. There are 24 accessible registers in each register window: 8 are the "in" registers (%i0-%i7), 8 are the "local" registers (%l0-%l7), and 8 are the "out" registers (%o0-%o7). The "in" registers are used to pass arguments to the function being called, and any additional arguments need to be pushed onto thestack. However, space is always allocated by the called function to handle a potential register window overflow, local variables, and (on 32-bit SPARC) returning a struct by value. To call a function, one places the arguments for the function to be called in the "out" registers; when the function is called, the "out" registers become the "in" registers and the called function accesses the arguments in its "in" registers. When the called function completes, it places the return value in the first "in" register, which becomes the first "out" register when the called function returns.
TheSystem VABI,[12] which most modernUnix-like systems follow, passes the first six arguments in "in" registers %i0 through %i5, reserving %i6 for the frame pointer and %i7 for the return address.
TheIBM System/360 is another architecture without a hardware stack. The examples below illustrate the original calling convention used byOS/360 and successors prior to the introduction ofEnterprise Systems Architecture (ESA), XPLINK and 64-bitz/Architecture; other operating systems for System/360 and later might have different calling conventions.
Calling program:
LA 1,ARGS Load argument list address L 15,=V(SUB) Load subroutine address1 BALR 14,15 Branch to called routine2 ...ARGS DC A(FIRST) Address of 1st argument DC A(SECOND) ... DC A(THIRD)+X'80000000' Last argument3
Called program:
SUB EQU * This is the entry point of the subprogram4
Standard entry sequence:
USING *,155 STM 14,12,12(13) Save registers6 ST 13,SAVE+4 Save caller's savearea addr LA 12,SAVE Chain saveareas ST 12,8(13) LR 13,12 ...
Standard return sequence:
L 13,SAVE+47 LM 14,12,12(13) L 15,RETVAL8 BR 14 Return to callerSAVE DS 18F Savearea9
Notes:
L 15,=A(SUB) orLA 15,SUB for internal subroutine; useL 15,=V(SUB) for external subroutines.BALR instruction stores the address of the next instruction (return address) in the register specified by the first argument—register 14—and branches to the second argument address in register 15. BASR is preferred on models that support it. BASSM may be used if switching between 24 and 31 bit modes is required.SUB ENTRY , afterSUB EQU * or replace it withSUB CSECT ,.DROP andUSING informing the assembler that register 15 is no longer to be used as a base register.STM instruction saves registers 14, 15, and 0 through 12 in a 72-byte[a] area provided by the caller called asave area pointed to by register 13. The called routine provides its own save area for use by subroutines it calls; the address of this area is normally kept in register 13 throughout the routine. The instructions followingSTM update forward and backward chains linking this save area to the caller's save area.savearea statically in the called routine makes itnon-reentrant andnon-recursive; a reentrant program uses a dynamicsavearea, acquired either from the operating system and freed upon returning, or in storage passed by the calling program.In theSystem/390 ABI[13] and thez/Architecture ABI,[14] used in Linux:
Additional arguments are passed on the stack.
| Register | Windows CE 5.0[15] | gcc[16] | Renesas[17] |
|---|---|---|---|
| R0 | Return values. Temporary for expanding assembly pseudo-instructions. Implicit source/destination for 8/16-bit operations. Not preserved. | Return value, caller saves | Variables/temporary. Not guaranteed |
| R1..R3 | Serves as temporary registers. Not preserved. | Caller saved scratch. Structure address (caller save, by default) | Variables/temporary. Not guaranteed |
| R4..R7 | First four words of integer arguments. The argument build area provides space into which R4 through R7 holding arguments may spill. Not preserved. | Parameter passing, caller saves | Arguments. Not guaranteed. |
| R8..R13 | Serves as permanent registers. Preserved. | Callee Saves | Variables/temporary. Guaranteed. |
| R14 | Default frame pointer. (R8-R13 may also serve as frame pointer andleaf routines may use R1–R3 as frame pointer.) Preserved. | Frame Pointer, FP, callee saves | Variables/temporary. Guaranteed. |
| R15 | Serves as stack pointer or as a permanent register. Preserved. | Stack Pointer, SP, callee saves | Stack pointer. Guaranteed. |
Note: "preserved" reserves to callee saving; same goes for "guaranteed".
The most common calling convention for theMotorola 68000 series is:[18][19][20][21]
TheIBM 1130 was a small 16-bit word-addressable machine. It had only six registers plus condition indicators, and no stack. The registers areInstruction Address Register (IAR),Accumulator (ACC),Accumulator Extension (EXT), and three index registers X1–X3. The calling program is responsible for saving ACC, EXT, X1, and X2.[22] There are twopseudo-operations for calling subroutines,CALL to code non-relocatable subroutines directly linked with the main program, andLIBF to call relocatable library subroutines through atransfer vector.[23] Both pseudo-ops resolve to aBranch and Store IAR (BSI) machine instruction that stores the address of the next instruction at its effective address (EA) and branches to EA+1.
Arguments follow theBSI—usually these are one-word addresses of arguments—the called routine must know how many arguments to expect so that it can skip over them on return. Alternatively, arguments can be passed in registers. Function routines returned the result in ACC for real arguments, or in a memory location referred to as the Real Number Pseudo-Accumulator (FAC). Arguments and the return address were addressed using an offset to the IAR value stored in the first location of the subroutine.
* 1130 subroutine example ENT SUB Declare "SUB" an external entry point SUB DC 0 Reserved word at entry point, conventionally coded "DC *-*" * Subroutine code begins here * If there were arguments the addresses can be loaded indirectly from the return address LDX I 1 SUB Load X1 with the address of the first argument (for example) ... * Return sequence LD RES Load integer result into ACC * If no arguments were provided, indirect branch to the stored return address B I SUB If no arguments were provided END SUB
Subroutines in IBM 1130,CDC 6600 andPDP-8 (all three computers were introduced in 1965) store the return address in the first location of a subroutine.[24]
Threaded code places all the responsibility for setting up for and cleaning up after a function call on the called code. The calling code does nothing but list the subroutines to be called. This puts all the function setup and clean-up code in one place—the prologue and epilogue of the function—rather than in the many places that function is called. This makes threaded code the most compact calling convention.
Threaded code passes all arguments on the stack. All return values are returned on the stack. This makes naive implementations slower than calling conventions that keep more values in registers. However, threaded code implementations that cache several of the top stack values in registers—in particular, the return address—are usually faster than subroutine calling conventions that always push and pop the return address to the stack.[25][26][27]
The default calling convention for programs written in thePL/I language passes all argumentsby reference, although other conventions may optionally be specified.[28] The arguments are handled differently for different compilers and platforms, but typically the argument addresses are passed via an argument list in memory. A final, hidden, address may be passed pointing to an area to contain the return value. Because of the wide variety of data types supported by PL/I adata descriptor may also be passed to define, for example, the lengths of character or bit strings, the dimension and bounds of arrays (dope vectors), or the layout and contents of adata structure.Dummy arguments are created for arguments which are constants or which do not agree with the type of argument the called procedure expects.[29]
all registers except d0, d1, a0, a1 and a7 should be preserved across a call.
On the 6809 or Zilog Super8, DTC is faster than STC.
Although direct-threaded interpreters are known to have poor branch prediction properties... the latency of a call and return may be greater than an indirect jump.