Problem with reordering of memory accesses

Michael Schwingen michaels@stochastik.rwth-aachen.de
Tue Oct 17 05:02:00 GMT 2000


Hello,

I have an optimization problem with gcc 2.95.2 (snapshot 20000417 behaves
the same). Consider this test program:

typedef struct
{
  int x0;
  int x1;
  int x2;
  int x3;
  int x4;
}foo;

void test(foo *p)
{
  p->x4 = 0x12345678;
  p->x2 = 0x87654321;
}

When compiling this with 
  powerpc-eabi-gcc -O3 -mcpu=860 -S test1.c
I get the following result:

test:
	lis 0,0x1234
	lis 9,0x8765
	ori 0,0,22136
	ori 9,9,17185
	stw 9,8(3)
	stw 0,16(3)
	blr

ie. the compiler had swapped the writes to element x2 and x4. I guess this
is legal behaviour, however, this creates a problem in my case since element
x2 is used as a semaphore which must be written last to avoid race
conditions (removing -mcpu=860 makes the compikler work as expected,
although I could not find any hint in the gcc source why, and this is no
option since I have to specify the 860 CPU, because otherwise gcc generates
floating point instructions).

How do I ensure that the writes occur in the specified order?  

Declaring x2 and x4 "volatile" helps in this test case, but not in my real
(more complex) code. Declaring the pointer volatile seems to work, but I
would like to use some construct that is *guaranteed* to work even with
newer compiler versions. Is the solution with the volatile pointer safe? If
not, what alternatives can I use?	

cu
Michael
-- 
"Intelligent life is very rare in the universe.
 On earth, it has not been discovered yet"     (Stephen Hawking)


More information about the Gcc mailing list