Ambiguous C?

Doug Gwyn gwyn at smoke.BRL.MIL
Thu Apr 27 14:01:39 AEST 1989


In article <17133 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
>If your compiler does not understand `volatile', and has no way to
>disable optimisation, you are out of luck.  (You can resort to assembly
>language subroutines.)

Back, back!  (Making the sign of the cross.)  No need to resort to
assembly language for something so simple.

What is the real problem here?  It's that the compiler knows that
we only need to inspect one byte in order to determine the state of
the bit.  So how do we outwit the compiler?  We have to make it unsure
of whether or not the other bytes are also needed.  One simple way to
do that is to resolve the bit test into two phases, the first of which
performs the proper access, after which the second determines what the
state of the bit is.  To force a longword access, it suffices to copy
the addressed object into an external longword, because the compiler
cannot know what other use might be made of its contents (by other
independently-compiled modules) and must therefore pick up the whole
object.  Having gotten the object into an ordinary storage cell, it
can then be inspected to our heart's content.

The one thing you can't really accomplish via such a trick is an
atomic read-modify-write operation, such as ORing a bit into a memory-
mapped device register.  I can't recall ever needing to ensure that,
but it is theoretically possible that one might.  In such a case we
might be inspired by the trick and code the operation something like:
	if ( (*(long *)DEVADDR |= BIT) == BIT )
		something_innocuous();
which will also force the compiler to examine the whole longword.
Odds are good that it will generate the desired code for the OR
operation.  (If not, additional effort along these general lines
should eventually outwit the compiler's optimization.)



More information about the Comp.lang.c mailing list