Darryl Gove's blog
An aliasing example
The compiler flag -xalias_level allows a user to assert the degree of aliasing that exists within the source code of an application. If the assertion is not true, then the behaviour of the application is undefined. It is definitely worth looking at the examples given in the user's guide, although they can be a bit "dry" to read. So here's an example which illustrates what can happen:
struct stuff{
int value1;
int value2;
};
void fill(struct stuff *x)
{
x->value1=0; // Clear value1
int * r=(int*)x; // Take the address of the structure
int var = *r; // Take the value from value1
x->value1=var; // And store it back into value1
}
The above code will clear value1 and then load and store this value back. So for correctly working code value1 should exit the function containing zero. However, if -xalias_level=basic is used to build the application, then this tells the compiler that no two pointers to variables of different types will alias. So pointer to an int will never alias with an int. So the read from *r does not alias with x.value1.
So with this knowledge the compiler is free to remove the original store to x.value1, because it has been told that nothing will alias with it, and there is a later store to the same address. The later store will overwrite the initial store.
Fortunately it the lint utility can pick up these issues:
$ lint -Xalias_level=basic alias.c (9) warning: cast of nonscalar pointer to scalar pointer is valid only at -xalias_level=any
For the example above the compiler does the correct thing and eliminates all the instructions but the store to value1. For more complex examples there is no guarantee that the code will be correct if it violates the -xalias_level setting.
Posted at 08:00AM Oct 12, 2009 by Darryl Gove in Sun | Comments[1]


