20040723 Friday July 23, 2004

Don't try to trick the compiler.


This is yet another not-a-compiler-bug-but-a-user-bug story.

Some Sun internal folks built an open source project hosted on sourceforge.net with our compiler, and the program produced different output when compiled with -xO4 or above. So they thankfully filed a bug (btw, we're happy to look at any bugs filed against us, even if it turns out to be a user error. So please don't hesitate to file a bug if you think it's compiler's fault).

A short analysis revealed the following:

In a file "r.h", there was a declaration like:
  typedef struct ... {
     ...
  } some_struct_t;

  extern const some_struct_t some_struct;
But in "r.c", it wasn't declared "const", and in that file, many functions modified this global variable some_struct.

The original programmer seemed to have thought that since this global variable is modified only in r.c and all other files should just read the variable, it's a good way to force that.

At -xO4 or above, our compiler starts doing aggressive inlining. And the inlining exposed some redudant loads from one field of this global variable "some_struct" in a file "a.c". Of course, the compiler happily eliminated the second redundant load - since "some_struct" is declared "const", there's nothing for the compiler to worry about. Well, the only problem was there was a call to a function defined in "r.c" which modifies the field that the eliminated redundant load was accessing. So the variable wasn't really "const" at all. Of course, this program works just fine when compiled without optimization or low level optimization, since only inlining and redundant code elimination can reveal the problem.

Another interesting tidbit is that there was some if-def that removed this "const"ness when compiled on certain platform. I bet somebody was already bitten by exactly the same problem, and worked around it by removing constness for that platform. Maybe s/he thought it was a platform specific problem. I don't know.

Anyway, I guess the morale of this story is: don't try to trick your compiler.

( Jul 23 2004, 01:18:09 PM PDT ) Permalink Comments [1]
Comments:

yeah, you're doing your job! I'm greatly relieved. :)

Posted by Rashper on July 24, 2004 at 10:58 AM PDT #

Post a Comment:

Comments are closed for this entry.