Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline Assembler: What scratch registers can be used?

When inserting inline assembler into a function in a C-like language, what is the convention about what registers you're allowed to use for scratch? Is it the compiler's responsibility to save the values of all the registers it needs to save before entering the asm block? Is it the responsibility of the programmer to store the values in these registers somewhere and restore them before exiting the asm block? Is there a typical convention, or is this very implementation-specific?

like image 929
dsimcha Avatar asked Oct 24 '09 05:10

dsimcha


3 Answers

Inline assembly is, by definition, compiler-specific.

Most compilers that support inline assembly have a syntax that allows you to indicate which registers are modified by the assembly. The compiler can then save and restore those registers as needed.

like image 193
Stephen Canon Avatar answered Oct 31 '22 11:10

Stephen Canon


This is very compiler specific. However, for a realistic example let's take gcc on x86. The format is:

asm ( assembler template
    : output operands               (optional)
    : input operands                (optional)
    : list of clobbered registers       (optional)
    );  

Where the "list of clobbered registers" is you telling the compiler which registers your code is using.

Here's a simple memory copy code:

asm ("movl $count, %%ecx;
      up: lodsl;    
      stosl;
      loop up;"
    :           /* no output */
    :"S"(src), "D"(dst) /* input */
    :"%ecx", "%eax" );  /* clobbered list */    

Given these directions, gcc won't be using eax and ecx for other things in the block.

More info here.

like image 7
Eli Bendersky Avatar answered Oct 31 '22 12:10

Eli Bendersky


You can read on register usage in some calling conventions here.

like image 2
elder_george Avatar answered Oct 31 '22 11:10

elder_george