2

I know that the inline keyword makes the compiler more likely to inline a function, although the decision is up to the compiler, and the GNU extension __attribute__((always_inline)) forces the compiler to inline it.
Correspondingly, is there...

__attribute__((always_register)) register int foo = 678;

...or something like that?

Sapphire_Brick
  • 1,560
  • 12
  • 26
  • 1
    What would happen if you `always_register` more variables than there are registers? – Raymond Chen May 18 '20 at 17:01
  • 1
    @RaymondChen The same thing that would happen if it's not possible to inline a function marked `always_inline`. – Sapphire_Brick May 18 '20 at 17:03
  • *force* hopefully no, the compiler knows better than you what to do, you are not sure to have enough registers for the rest of the code, and when you call a function/method the called cannot know a register is 'reserved' so the value must be saved elsewhere – bruno May 18 '20 at 17:03
  • 1
    If you need this level of control, write it in assembler yourself. If this is for perf reasons, trust the compiler or write it in assembly yourself. – Michael Dorgan May 18 '20 at 17:03
  • 2
    There was a keyword (there still is, but it's now deprecated) called `register` that gave the compiler a _hint_ that it would be a good idea to store something in a register. Nowadays people mostly rely on the compilers optimization to figure out what's best. – Ted Lyngmo May 18 '20 at 17:04
  • @MichaelDorgan I'm asking out of curiosity – Sapphire_Brick May 18 '20 at 17:04

1 Answers1

4

GCC has a way to specify register for a local variable through usage of keywords asm and register:

register int *foo asm ("r12");

Note the quote:

The only supported use for this feature is to specify registers for input and output operands when calling Extended asm.

This feature is used in Linux kernel on some architectures to gain access to a thread-local storage that is stored in one of general purpose registers. This is how current macro is implemented on ARC architecture:

register struct task_struct *curr_arc asm("r25");
#define current (curr_arc)

Such usage is interesting as it uses register keyword at a global scope, while in standard C it can only be used locally.

Sapphire_Brick
  • 1,560
  • 12
  • 26