[comp.lang.c] hack to fake volatile

robison@uiucdcsm.cs.uiuc.edu (03/31/88)

I came in late on the ``volatile'' argument, but the following hack 
would seem to work without adding anything to the language.
The hack may be expressed as:

	``Chain the optimizer's paws by encapsulating the volatile variable''

We declare the variable and two functions for accessing it:

	int _X;		/* local to WriteX and ReadX */

	#define WriteX(a) (_X = a)
	#define ReadX     (Munge(&_X), _X)

The function ``Munge'' would be in a library and be implemented as a no-op,
but not known to the optimizer!  Therefore the optimizer must invalidate
any copies of X in registers, as Munge could potentially (on Friday the
13's with a full moons) alter X.  

Arch D. Robison
University of Illinois at Urbana-Champaign
	
CSNET: robison@UIUC.CSNET
UUCP: {ihnp4,pur-ee,convex}!uiucdcs!robison
ARPA: robison@B.CS.UIUC.EDU (robison@UIUC.ARPA)

robison@uiucdcsb.cs.uiuc.edu (04/04/88)

Scott Daniels (daniels@teklds.UUCP) pointed out a bug in my original hack
to fake "volatile".  There are situations involving writes-only which an 
"optimizer" may incorrectly transform.  

One needs a call to "Munge" in both the read and write routines to
"flush the caches", so to speak.

	int _X;		/* local to WriteX and ReadX */

	#define WriteX(a) (_X=a, Munge(&_X))	/* Munge is a secret no-op */
	#define ReadX     (Munge(&_X), _X)

I'm not sure how to formally verify this hack.  I suppose one could argue
that any asynchronous writes and reads could be simulated by the Munge calls,
and therefore the optimizer must keep its paws off.  But this is far from 
a convincing argument.

Arch D. Robison
University of Illinois at Urbana-Champaign
	
CSNET: robison@UIUC.CSNET
UUCP: {ihnp4,pur-ee,convex}!uiucdcs!robison
ARPA: robison@B.CS.UIUC.EDU (robison@UIUC.ARPA)