1

I'm new to the concept of writing functions that contains inline assembly in C/C++ and I want to know if it's safe to use all of the available general purpose registers. (from rax to r15)

In my knowledge, all of the variables/objects/data are actually stored in the main memory, and it is only loaded in the registers when we are performing operations with it, because of this I assume that it is actually safe to use any of the GP registers with inline assembly inside a function but I'm not sure about it.

I'm worried if it's possible that there might be a case where some registers are still used outside of the function and when that function is invoked those register's value might be overwritten and might case some errors possibly in the program?

Is there any registers that I should avoid when writing inline assembly?

4
  • 1
    You must inform the compiler about any and all registers that you modify, using a clobber list. There are none that it is safe to modify otherwise. Are you familiar in general with how GCC extended assembly works (operands, constraints, clobbers, etc)? It is not a trivial thing, very easy to get subtly wrong, and the compiler will not catch it if you do. See stackoverflow.com/tags/inline-assembly/info for references. Feb 27, 2022 at 6:21
  • 1
    all of the variables/objects/data are actually stored in the main memory - maybe you've been looking at debug builds where compilers don't keep anything in registers between C statements. That's only true for debug builds. Feb 27, 2022 at 6:30
  • 1
    I found 2 duplicates, one about why you need to tell the compiler about which regs you're using. Another about which regs to use, ultimately suggesting that you leave the choice to the compiler via constraints. So if you were asking either or both of those things, then that covers it. You can use any except RSP. Feb 27, 2022 at 6:34
  • 1
    Possibly also related: GCC inline assembly with stack operation re: mis-conceptions about inline asm. Feb 27, 2022 at 6:38

1 Answer 1

4

No, it is not correct that "data are actually stored in the main memory, and it is only loaded in the registers when we are performing operations with it". Compilers work very hard to keep data in the registers and only spill to memory if required.

You have to tell the compiler about all the registers you use in the inline assembly, so it can ensure that they are available for you. None of the registers are available to use freely.

To indicate to the compiler that you are modifying the contents of registers, you list them as outputs or in the clobber list.

Not the answer you're looking for? Browse other questions tagged or ask your own question.