2013-03-04 124 views
8

在gcc中,可以使用以下語法聲明局部變量應放入寄存器中。如何使用gcc asm關鍵字在寄存器中傳遞函數參數

register int arg asm("eax"); 

在一些舊的代碼我這句法來聲明該參數的函數應該在寄存器傳遞在互聯網上找到:

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

但當我嘗試這個例子:

/* 
    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; 
} 

而且用gcc編譯我得到一個錯誤:

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

現在我的問題是:
是ASM的語法正確以上,在海灣合作委員會就是一個函數的形參?
這是否曾經被gcc支持?
如果這不是正確的語法,那麼如何實現呢?

感謝,
// JK

回答

2

我所知道的是使用快速調用屬性的唯一方法:

(GCC手冊第6.30)http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html#Function-Attributes

fastcall

On the Intel 386, the fastcall attribute causes the compiler to pass the first argument (if of integral type) in the register ECX and the second argument (if of integral type) in the register EDX. Subsequent and other typed arguments are passed on the stack. The called function will pop the arguments off the stack. If the number of arguments is variable all arguments are pushed on the stack.

在使用它的以下示例代碼:

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

int main() { 
    return add (1, 2); 
} 

將導致:

.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 

不要忘記提及在其他翻譯單元的任何聲明FASTCALL屬性,否則很奇怪的事情可能會發生。

+0

感謝您的建議。但是我認爲可能有或者已經有了gcc支持的更一般的語法。 – 2013-03-04 20:47:43

+0

哇,超過一半的生成函數是多麼醜陋無用的序幕/尾聲廢話......那是用'-O0'還是...? – 2013-03-04 22:52:07

+0

Nope - 與-O0相比,它變得更加有趣,因爲參數通過ecx和edx傳遞,無論出於何種原因將首先存儲在堆棧中。這是(不笑話)將做什麼用的gcc -O0:'補充: \t pushl \t%EBP \t MOVL \t%ESP,EBP% \t subl \t $ 8%ESP \t MOVL \t%ECX,-4( %EBP) \t \t MOVL%EDX,-8(%EBP) \t \t MOVL -8(%EBP),%eax中 \t \t MOVL -4(%EBP),%EDX \t \t萊亞爾(%EDX, %eax),%eax \t請假 \t ret' – mikyra 2013-03-04 23:28:05

相關問題