Null pointer check elimination
David Daney
ddaney@avtrex.com
Tue Nov 15 07:39:00 GMT 2005
Gabriel Dos Reis wrote:
> I'm saying that if you call foo with a null pointer, you get into
> undefined behaviour territory. And GCC is founded to make
> optimization based on that. And you -- as a user -- generally don't
> know how and when GCC can apply that assumption. And it is already
> doing so in known cases; it may do more in the future. I don't want
> to go and give a long list of the specific cases; there is no point in
> it. The transformation is general and will be applied where the
> opportunity arises. Just don't count on dereferencing a null pointer
> to result you or not result in a segfault in general.
Perhaps not in general, but one unstated premise of this whole thread is
that for some GCC targets (most Unix like operating systems) you *can*
count on a SIGSEGV when you dereference a null pointer. The java front
end takes advantage of this fact to eliminate explicit checks for
dereferencing of null pointers.
The Java Language Specification requires that NullPointerExceptions are
thrown when calling a method via a null 'this'. But since a method call
does not usually involve dereferencing 'this', an explicit check for
null must be made when it cannot be proven that 'this' is not null. The
original point of this thread was that some of these explicit checks may
be eliminated based on a priori knowledge about the behavior of certain
standard library methods.
Which leads me to the (unrelated) thought that inserting an instruction
that dereferences the pointer may be more efficient (from a code size
point of view) than an explicit check for null and then branching around
the code that creates and throws the exception.
David Daney
More information about the Java
mailing list