clinuxgcccompiler-optimization

Is there any way to explicitly tell compiler to stop optimization


Linux, C, GCC, ARM (Allwinner H3). Is it possible to get the following equivalent functionality (pseudocode):

#pragma optimizations-stop
#pragma registers-flush

a=10;
while(*b != 0) c++;
if(a == 0) { do something; }

#pragma optimizations-start

with result of location of a being explicitly written with value 10, then every loop cycle value of b is read from the memory and then read value from location b is compared to 0, and then if not zero c is rmw'ed with +1, and when loop breaks location of a is being explicitly read from the memory and compared to 0?

And, what's important, instructions are executed in the specific order programmer laid them out in the program, not as compiler or CPU thinks the best.

Please withhold with discussion of what is impossible, let's discuss how to achieve the required result.

If it is not possible at the C/GCC level, I will be glad for suggestions to implement that as inline assembly.


Solution

  • The "big hammer" is a GCC extension, asm __volatile__("": : :"memory"). This is the full memory barrier used by the Linux kernel.

    Note that this does not do what you ask for in the title. It doesn't stop optimizations at all. It does however achieve the ordering that you describe.

    Also note that c++ is a read-modify-write. It's not atomic, and there are no memory barriers between the parts. The compiler can reasonably keep c in a register, and do a read-modify-write on the register. You'd need something like volatile int* pc = &c; to avoid that.

    Finally, to take your other post into account, the memory barrier on one thread won't magically make another thread cooperate. You'd need barriers on both threads. And that's why they're rare - you can usually use proper synchronization instead.