How to pass function parameters to a register with the gcc asm keyword

In gcc, you can declare that a local variable should be put in a register using the following syntax.

register int arg asm("eax"); 

In some old code that I found on the Internet, this syntax was used to declare that function parameters should be passed to the register:

 void foo(register int arg asm("eax")) 

But when I try this example:

 /* Program to demonstrate usage of asm keyword to allocate register for a variable. */ #include <stdio.h> /* Function with argument passed in register */ void foo(register int arg asm("eax") ) { register int loc asm("ebx"); loc = arg; printf("foo() local var: %d\n", loc); } int main(void) { foo(42); return 0; } 

And compile with gcc I get an error:

 gcc main.c -o test-asm.exe main.c:7:27: error: expected ';', ',' or ')' before 'asm' 

Now my questions are:
Is the asm syntax above correct in gcc, i.e. for formal function parameters?
Has it ever been supported by gcc?
If this is not the correct syntax, how can this be done then?

Thanks,
// Yu.K.

+8
c assembly gcc parameter-passing calling-convention
source share
1 answer

The only method I know is to use the fastcall attribute:

(GCC Manual 6.30 section) http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html#Function-Attributes

bastard

In Intel 386, the fastcall attribute forces the compiler to pass the first argument (if the integral type) to the ECX register and the second argument (if the integral type) to the EDX register. Subsequent and other arguments entered are pushed onto the stack. the called function will pop the arguments out of the stack. If the number of arguments is variable, all arguments are pushed onto the stack.

Using it in the following code example:

 __attribute__((fastcall,noinline)) int add (int a, int b) { return a + b; } int main () { return add (1, 2); } 

will result in:

  .file "main.c" .text .globl add .type add, @function add: pushl %ebp movl %esp, %ebp leal (%edx,%ecx), %eax popl %ebp ret .size add, .-add .globl main .type main, @function main: pushl %ebp movl %esp, %ebp movl $2, %edx movl $1, %ecx call add popl %ebp ret .size main, .-main 

Do not forget to specify the fastcall attribute in any ad in other translation units, otherwise strange things may occur.

+2
source share

All Articles