R – control register allocation in g++

cpu-registersg++gccinlineoptimization

I have highly optimized piece of C++ and making even small changes in places far from hot spots can hit performance as much as 20%. After deeper investigation it turned out to be (probably) slightly different registers used in hot spots.
I can control inlineing with always_inline attribute, but can I control register allocation?

Best Solution

If you really want to mess with the register alloation then you can force GCC to allocate local and global variables in certain registers.

You do this with a special variable declaration like this:

 register int test_integer asm ("EBX");

Works for other architectures as well, just replace EBX with a target specific register name.

For more info on this I suggest you take a look at the gcc documentation:

http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Local-Reg-Vars.html

My suggestion however is not to mess with the register allocation unless you have very good reasons for it. If you allocate some registers yourself the allocator has less registers to work with and you may end up with a code that is worse than the code you started with.

If your function is that performance critical that you get 20% performance differences between compiles it may be a good idea to write that thing in inline-assembler.


EDIT: As strager pointed out the compiler is not forced to use the register for the variable. It's only forced to use the register if the variable is used at all. E.g. if the variable it does not survive an optimization pass it won't be used. Also the register can be used for other variables as well.

Related Question