cgcc

Is there a compiler memory barrier for a single variable?


Compiler memory barriers has the effect among other things to force the compiler to make sure all stack variables that are cached in registers are written to memory before the barrier.

For example, GCC has the following statement:

asm inline ("" : : : "memory");

Is there any way to tell a compiler (specifically GCC, but I'm interested in others as well) to do the same effect for only a specific variable? something like the following imagined construct:

int x;
...
asm inline ("" : : : "memory(x)");

With the expected behavior that the value of x and x only will be written to the corresponding memory location, if it happens to be cached in a register.

The reason for this is that I have a specific variable which I need to make sure is not cached in a register so that a hardware engine can read its value. However, a full compiler memory barrier will force the compiler to write to memory the value of all other variables that might be cached in register at that point in time as well which can amount to much more data then I need to write. I wondered if there something more specific.

Thanks in advance!


Solution

  • Try with { int y = x; *(volatile int*)&x = y; } and inspect the resulting assembly.