开发者

GCC not saving/restoring reserved registers on function calls

开发者 https://www.devze.com 2023-03-23 09:48 出处:网络
I have a scenario in GCC causing me problems. The behaviour I get is not the behaviour I expect. To summarise the situation, I am proposing several new instructions for x86-64 which are implemented in

I have a scenario in GCC causing me problems. The behaviour I get is not the behaviour I expect. To summarise the situation, I am proposing several new instructions for x86-64 which are implemented in a hardware simulator. In order to test these instructions I am taking existing C source code and handcoding the new instructions using hexidecimal. Because these instructions interact with the existing x86-64 registers, I use the input/output/clobber lists to declare dependencies for GCC.

What's happening is that if I call a function e.g. printf, the dependent registers aren't saved and restored.

For example

register unsigned long r9  asm ("r9")  = 101;
printf("foo %s\n", "bar");
asm volatile (".byte 0x00, 0x00, 0x00, 0x00" : /* no output */ : "q" (r9) );

101 was assigned to r9 and the inline assembly (fake in this example) is dependent on r9. This runs correctly in the absence of the printf, but when it is there GCC does not save and restore r9 and another value is there by the time my custom instruction is called.

I thought perhaps that GCC might have secretly changed the assignment to the variable r9, but when I do this

asm volatile (".byte %0" : /* no output */ : "q" (r9) );

and look at the assembly output, it is indeed using %r9.

I am using gcc 4.4.5. What do you think might be happening? I thought GCC开发者_运维问答 will always save and restore registers on function calls. Is there some way I can enforce it?

Thanks!

EDIT: By the way, I'm compiling the program like this

gcc -static -m64 -mmmx -msse -msse2 -O0 test.c -o test


The ABI, section 3.2.1 says:

Registers %rbp, %rbx and %r12 through %r15 “belong” to the calling function and the called function is required to preserve their values. In other words, a called function must preserve these registers’ values for its caller. Remaining registers “belong” to the called function. If a calling function wants to preserve such a register value across a function call, it must save the value in its local stack frame.

so you shouldn't expect registers other than %rbp, %rbx and %r12 through %r15 to be preserved by a function call.


gcc will not make explicit-register variables like this callee-saved. Basically this register notation you're using makes the variable a direct alias for the register, with the assumption you want to be able to read back the value a callee leaves in the register. If you used a callee-saved register instead of a call-clobbered (caller-saved) register, the problem would go away.

0

精彩评论

暂无评论...
验证码 换一张
取 消