Bug 27336 - "this" pointer is not assumed to be not null
: "this" pointer is not assumed to be not null
Status: NEW
Product: gcc
Classification: Unclassified
Component: c++
: 4.1.0
: P3 enhancement
: ---
Assigned To: Not yet assigned to anyone
:
: missed-optimization
:
:
  Show dependency treegraph
 
Reported: 2006-04-27 11:29 UTC by Guillaume Melquiond
Modified: 2006-11-08 01:05 UTC (History)
4 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail: 4.2.0
Last reconfirmed: 2006-04-27 21:04:48


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Guillaume Melquiond 2006-04-27 11:29:13 UTC
I noticed that GCC tends to litter the assembly code with null checks and jumps
(especially for dynamic casts) even when the pointer cannot be null. This is
especially true for "this": unless I am mistaken, calling a nonstatic member
with "this" not pointing to an object of the correct type (or a derived type)
is undefined behavior. So GCC should assume it is not null. I tried the
following testcase with 3.4.6, 4.0.3, and 4.1.0; GCC was never able to optimize
the return value to "true" when compiling with -O3.

struct A { bool g(); };
bool A::g() { return this; }
Comment 1 Richard Guenther 2006-04-27 13:10:59 UTC
Confirmed.  The frontend needs to tell the middle-end that the argument is
non-NULL.  Like by making the methods __attribute__((nonnull(1))).
Comment 2 Guillaume Melquiond 2006-04-28 09:03:33 UTC
I tried setting the nonnull attribute, it indeed allowed the optimization. In
particular, codes containing dynamic casts are now straight lines. This is a
nice improvement. Unfortunately GCC was not able to go further and use this
information in the caller in order to optimize it:

struct A { bool g() __attribute__((nonnull)); }
bool f(A *a) {
  a->g();
  return a;
}

Am I expecting too much from the nonnull attribute? (The documentation does not
seem to cover this point.) Or would it be reasonnable for the middle-end to
implement such an optimization?
Comment 3 Richard Guenther 2006-04-28 09:33:58 UTC
VRP could extract this information just like it does for loads in

void bar(int);
int foo(int *i)
{
  bar(*i);
  return i == NULL;
}
Comment 4 Steven Bosscher 2006-05-01 19:17:11 UTC
Re. comment #2 and comment #3, yes you are expecting too much of the nonnull
attribute.  The attribute only applies to function arguments, not to function
results.
Comment 5 Steven Bosscher 2006-05-01 19:19:39 UTC
Ehm, right, ignore comment #4.

Yes it is possible.

No, it's not very practical.  Your code looks like,

bool f(A *a) {
  g(a);
  return a;
}

to the middle end.  It would take a significant amount of extra work to walk
through all formal and actual argument lists in a CALL_EXPR to find "attribute
nonnull"-arguments in the callee argument list.  I'm not sure that's worth the
cost.
Comment 6 Richard Guenther 2006-05-01 19:21:42 UTC
Though it's also not hard to teach VRP to do this.