This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Using may_alias


I've got some (perverse) code that uses reinterpret_cast to get new
'view' of a vector-like structure:
---------------------------------------------
template <int N>
struct vec
{
     int data[N];

};

vec<2> &as_vec2(vec<3> &v3)
{
     return *reinterpret_cast<vec<2>*>(&v3);

}

int main()
{
     vec<3> v3;
     vec<2> v2(as_vec2(v3));

     return v2.data[0];
}

---------------------------------------------
(this is a hastily hacked-up version designed to be clear, not pretty)

When I compile this in g++ (4.4.1) with -O2 and -Wall, I get the
following warning:

$ g++ vec-alias.cpp -O2 -Wall
vec-alias.cpp: In function âint main()â:
vec-alias.cpp:19: warning: dereferencing pointer â<anonymous>â does
break strict-aliasing rules
vec-alias.cpp:19: note: initialized from here

Not too surprising, since the result of as_vec2 clearly aliases the
argument and they have different types.

I've heard of the __may_alias__ attribute in gcc and I thought that I
could clue the compiler in by replacing the as_vec2 function with:

vec<2> &__attribute__((__may_alias__)) as_vec2(vec<3> &__attribute__
((__may_alias__))v3)
{
    typedef vec<2>*__attribute__((__may_alias__)) ret_t;
    return *reinterpret_cast<ret_t>(&v3);
}

However, I get the same aliasing warnings.  Granted, I haven't use attributes
too much and I may be specifying them incorrectly.

I'm also kind of curious what flag actually causes this warning to
appear, since -O1 -Wall with all of the additional options shown for
-O2 in the gcc info page doesn't trigger it. I suspect that my info
page doesn't reflect what -O2 really means to the compiler.

As a matter of fact, I seem to recall that there's a command to have
gcc tell you about what the various optimization levels to from the
command line, but I can't seem to figure out how to get it.

Any thoughts on how to tell the compiler that this function's return
value aliases its input? Any ideas what's going on with the compiler
args?

Thanks,
Jason


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]