views:

171

answers:

3

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?

+8  A: 

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.

Stephen Canon
+2  A: 

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

elder_george
+6  A: 

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.

Eli Bendersky