Reordering of function calls - compiler bug or allowed by standard?

Jens Kilian jens.kilian@verigy.com
Wed Sep 24 06:27:00 GMT 2008


The following somewhat contrived example models what happens in our software
when accessing some memory-mapped IO registers.  There is an address register
into which the SW writes the address to be accessed, plus a data register
from which it can then read the contents of that address.  Both accesses
have been replaced by printf/scanf here.

---8<--------------------------------------------------------------------8<---
#include <stdio.h>

/* model internal state of address register */
int N;

/* write address register */
void
writeit(int i)
{
  printf("Writing %d\n", i);
  N = i;
}

/* read data register */
int
readit(void)
{
  int x;

  printf("Reading %d\n", N);
  scanf("%d", &x);

  return x;
}

/* convenience macro to read from address i */
#define RD(i) (writeit(i), readit())

int
main(void)
{
  if (RD(42) == RD(23))
    return 1;

  return 0;
}
---8<--------------------------------------------------------------------8<---

In the main() routine, the intended result is to read from addresses 42 and 23
and compare the results.  However, GCC reorders the calls to writeit/readit
so that both writes are performed first - in the real HW, this would cause
the program to read one of the addresses twice, the other not at all.

I tested two GCC versions, which both show similar but not identical results:

gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-54):

Writing 23
Writing 42
Reading 42
0
Reading 42
0

gcc version 4.1.2 20070626 (Red Hat 4.1.2-14):

Writing 42
Writing 23
Reading 23
1
Reading 23
1

Is there any way to force a consistent order of function calls - i.e.,
to keep GCC from moving calls across the '==' operator?
(Preferably one that doesn't involve rewriting the main() function - it is
easy for me to change the macro definition, but finding and fixing all
places where such a macro is used in this way would require enormous effort
- and it wouldn't keep people from reintroducing such problems later).

Thanks,
	Jens.
-- 
mailto:jjk@acm.org                 phone:+49-7031-4357-122
  http://www.bawue.de/~jjk/          fax:+49-7031-4357-483
  http://del.icio.us/jjk           As the air to a bird, or the sea to a fish,
                                   so is contempt to the contemptible. [Blake]



More information about the Gcc-help mailing list