Is there any way to tell the compiler (here gcc) that it should not optimize variables that it thinks are constants to constant expressions? In general by a compiler flag or even better by using an attribute for a specific variable?
I want the (local) variable to really exist, every read on this variable to be actually executed and also every write, even if I write the same value again.
It would always load/store the variable from/to RAM if I don't optimize. Same if I declare it volatile. However, I do want it to be able to be kept in a register, just like a normal variable that's neither constant nor volatile. Disabling optimization completely is also not an option.
Code example (r(a) and r(b) are any register):
int a, b;
a = 2;
a = 2;
b = a;
Result (provided b is needed later, a no more):
Ignored line
Ignored line
Moves 2 in r(b)
a is replaced by constant expression 2
volatile int a;
int b;
a = 2;
a = 2;
b = a;
Result (b is needed later, a doesn't matter):
Moves 2 in r2, puts address of a in r3, writes r2 to RAM(r3)
Writes r2 again to RAM(r3)
Reads RAM(r3) into r4
Puts address of b in r5, writes r4 to RAM(r5)
As you can see this is very inefficient. What I want:
Move 2 in r(a)
Move 2 in r(a) again
Write r(a) into r(b)
If registers are needed for something else, store a and b in RAM
This is exactly what would happen, if a was a real variable and not just 2.
For such a demand you could not use C for this. It is not possible to dictate a variables physical location (RAM vs registry). The whole point of GCC is to take care of that for you.
You'd have to write your own assembly code to work with using load operations.