Search code examples
ccompiler-constructioncompilationcompiler-optimizationstorage-class-specifier

who decide actual storage of register storage class?


Recently I have been asked following Q in a interview : Who actually decide that where register variable will be store(in RAM or register).

I have searched on google, the ans I got that compiler decide. but how can compiler decide ? It should be decided at run time as per my understanding.

what if we compile and run program in different machine , then how can compiler decide where to store register storage class value.


Solution

  • The register storage class specifier is a hint to the compiler that accesses to a variable ought to be “as fast as possible”, implying (on register architectures) that its storage should be allocated to a register. This prohibits a few things, like taking the address of the variable—registers don’t have addresses. However, the compiler is free to ignore this hint (§6.7.1¶5):

    A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

    When compiling your code, the compiler must choose how to map local variables and arithmetic operations into operations on CPU registers and stack memory. This is called register allocation; these decisions are made at compile time, and baked into the compiled code of a function.

    Suppose we have a very naïve compiler that does precisely what we say, and doesn’t optimise anything. If we give it this code:

    int x;
    x = 2;
    x += 5;
    

    Then we might expect to see this output, on an x86 machine:

    sub esp, 4          ; allocate stack space for an integer
    mov dword [esp], 2
    add dword [esp], 5
    

    But if we write:

    register int x;
    x = 2;
    x += 5;
    

    Then we might expect to see:

    mov eax, 2
    add eax, 5
    

    The latter is more efficient because it prefers register accesses over memory accesses. In practice, contemporary compilers have intelligent register allocation algorithms that make this storage class specifier unnecessary.