Force GCC to pass arguments in registers

落花浮王杯 提交于 2020-02-06 03:46:38

问题


I'm starting to try to mess around with inlining ASM in C++, so I wrote up this little snippet:

#include <iostream>

int foo(int, int, int);


int main(void)
{
    return foo(1,2,3);
}

int foo(int a, int b, int c)
{
    asm volatile("add %1, %0\n\t"
                 "add %2, %0\n\t"
                 "add $0x01, %0":"+r"(a):"r"(b), "r"(c):"cc");
}

Which outputs the following assembly code:

main:
.LFB969:
    subq    $40, %rsp
    .seh_stackalloc 40
    .seh_endprologue
    call    __main
    movl    $3, %r8d
    movl    $2, %edx
    movl    $1, %ecx
    call    _Z3fooiii

... stuff not shown...

_Z3fooiii:
.LFB970:
    .seh_endprologue
    movl    %ecx, 8(%rsp)
    movl    %edx, 16(%rsp)
    movl    %r8d, 24(%rsp)
    movl    16(%rsp), %edx
    movl    24(%rsp), %ecx
    movl    8(%rsp), %eax
/APP
 # 15 "K:\inline_asm_practice_1.cpp" 1
    add %edx, %eax
    add %ecx, %eax
    add $0x01, %eax
 # 0 "" 2
/NO_APP
    movl    %eax, 8(%rsp)
    ret

So I can see where it inputs my code, but what's with the stack manipulations above it? Is there any way I can get rid of them; they seem unnecessary. I should just be able to have

(in main)

movl    $3, %r8d
movl    $2, %edx
movl    $1, %ecx
call    _Z3fooiii

(in foo)

add %edx, %ecx
add %r8d, %eax
add $0x01, %eax
ret

How do I make gcc understand that it doesn't need to shove things on the stack and bring them back in a different order? I've fried fastcall and regparam already, and I can't find anything aboout this.


回答1:


You probably need to enable optimizations via something like -O2 in order to get the compiler to try and write better/faster code, instead simpler/easier to debug/understand code.



来源:https://stackoverflow.com/questions/24471469/force-gcc-to-pass-arguments-in-registers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!