This is the mail archive of the gcc-bugs@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]

[Bug c/32074] New: Optimizer does not exploit assertions


It would be nice if the optimizer took advantage of assertions. I realize that
assertions may not be enabled for production code, but even when disabled they
are still explicit statements of the programmer's assumptions; the compiler
should be able to exploit those assumptions if it yields better code (or avoids
annoying warnings). 

To me, ``assert(!bad_thing)'' indicates that ``bad_thing'' should not be
allowed to happen; compiling with assertions disabled means that ''bad_thing''
is assumed not to happen. Therefore, code that breaks when ``bad_thing ==
true'' is my bug, not the compiler's, and not necessarily worse than the bug(s)
caused by return values or side effects of ``correct'' code after an enabled
assertion would have terminated the program.

For example, -funroll_loops on the following code results in an 8x duff's
device, even though no acceptable input will run more than twice. In this
particular case, ``if(bad thing) exit(-1)'' does the same thing.


void short_loop(int* dest, int* src, int count) {
  // same happens for if(count > 2) exit(-1)
  assert(count <= 2);

  for(int i=0; i < count; i++)
    dest[i] = src[i];
}

As another example, compiling the following switch statement with -Wall causes
complaints about control reaching the end of a non-void function:

int limited_switch(int a, int b, int what) {
  switch(what) {
  case 0:
    return a+b;
  case 1:
    return a;
  case 2:
    return b;
  case 3:
    return a-b;
  default:
    // unreachable
    assert(false);
  }
}

The following variant of the previous switch statement, which also has an
undefined return value for (what < 0 || what >= 4), doesn't cause any warnings
at all, though it's arguably less correct -- at least with the first variant
the programmer indicated that she thought the matter through.


int limited_switch(int a, int b, int what) {
  int result;
  switch(what) {
  case 0:
    result = a+b;
    break;
  case 1:
    result = a;
    break;
  case 2:
    result = b;
    break;
  case 3:
    result = a-b;
    break;
  default:
    break;
  }
  return result;
}


-- 
           Summary: Optimizer does not exploit  assertions
           Product: gcc
           Version: 4.2.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: c
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: scovich at gmail dot com


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=32074


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