6.3 Calling mechanism

Procedures and Functions are called with their parameters on the stack. Contrary to Turbo Pascal, all parameters are pushed on the stack, and they are pushed right to left, instead of left to right for Turbo Pascal. This is especially important if you have some assembly subroutines in Turbo Pascal which you would like to translate to Free Pascal.

Function results are returned in the accumulator, if they fit in the register. Methods calls (from either objects or clases) have an additional invisible parameter which is self. This parameter is the leftmost parameter within a method call (it is therefore the last parameter passed to the method).

When the procedure or function exits, it clears the stack.

Other calling methods are available for linking with external object files and libraries, these are summarized in table (6.3). The first column lists the modifier you specify for a procedure declaration. The second one lists the order the paramaters are pushed on the stack. The third column specifies who is responsible for cleaning the stack: the caller or the called function. The alignment column indicates the alignment of the parameters sent to the stack area. Finally, the fifth column indicates if any registers are saved in the entry code of the subroutine.



Table 6.3: Calling mechanisms in Free Pascal





Modifier Pushing order Stack cleaned by alignment registers saved





¡none¿ Right-to-left Function default None
cdecl Right-to-left Caller GCC alignment GCC registers
interrupt Right-to-left Function default all registers
pascal Left-to-right Function default None
safecall Right-to-left Function default GCC registers
stdcall Right-to-left Function GCC alignment GCC registers
popstack Right-to-left Caller default None
register Left-to-right Caller default None






More about this can be found in chapter 7, page 273 on linking. Information on GCC registers saved, GCC stack alignment and general stack alignment on an operating system basis can be found in Appendix H. The register modifier is currently not supported, and maps to the default calling convention.

Furthermore, the saveregisters modifier can be used with any of the calling mechanism specifiers. When saveregisters is used, all registers will be saved on entry to the routine, and will be restored upon exit. Of course, if the routine is a function, and it normally returns its retun value in a register, that register will not be saved. Also, if the self register is used, it will also neither be saved nor restored.