Bug 83026

Summary: missing strlen optimization for strcmp of unequal strings
Product: gcc Reporter: Martin Sebor <msebor>
Component: tree-optimizationAssignee: Qing Zhao <qing.zhao>
Status: RESOLVED FIXED    
Severity: normal CC: dimhen
Priority: P3 Keywords: missed-optimization
Version: 8.0   
Target Milestone: ---   
See Also: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82950
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90625
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90876
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90879
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92408
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed: 2017-11-20 00:00:00
Bug Depends on:    
Bug Blocks: 83819    

Description Martin Sebor 2017-11-16 23:29:37 UTC
Here's another strcmp optimization opportunity.  When strlen() determines that two strings are of unequal length it's safe to assume they do not compare equal.  Therefore, in the function below, the conditional with the the strcmp() call can be folded into false.

$ cat c.c && gcc -O2 -S -Wall -fdump-tree-optimized=/dev/stdout c.c
void g (const char *a, const char *b)
{
  if (__builtin_strlen (a) == __builtin_strlen (b))
    return;

  if (!__builtin_strcmp (a, b))
    __builtin_abort ();
}

;; Function g (g, funcdef_no=0, decl_uid=1892, cgraph_uid=0, symbol_order=0)

g (const char * a, const char * b)
{
  long unsigned int _1;
  long unsigned int _2;
  int _3;

  <bb 2> [local count: 10000]:
  _1 = __builtin_strlen (a_5(D));
  _2 = __builtin_strlen (b_6(D));
  if (_1 == _2)
    goto <bb 5>; [20.97%]
  else
    goto <bb 3>; [79.03%]

  <bb 3> [local count: 7903]:
  _3 = __builtin_strcmp (a_5(D), b_6(D));
  if (_3 == 0)
    goto <bb 4>; [0.04%]
  else
    goto <bb 5>; [99.96%]

  <bb 4> [count: 0]:
  __builtin_abort ();

  <bb 5> [local count: 9997]:
  return;

}
Comment 1 Martin Sebor 2017-11-16 23:30:35 UTC
See also pr82950 for a related enhancement.
Comment 2 Qing Zhao 2017-11-20 16:18:53 UTC
This is reasonable. I will add the support for this into my implementation for PR78809.
Comment 3 Paolo Carlini 2017-11-20 18:41:03 UTC
Qing is on it.
Comment 4 Qing Zhao 2017-12-05 16:31:29 UTC
Note, this optimization is only valid when the result of the strcmp is used to compare with zero.
Comment 5 qinzhao 2018-05-31 20:42:35 UTC
the patch has been put back into trunk as revision 261039:

https://gcc.gnu.org/viewcvs/gcc?limit_changes=0&view=revision&revision=261039
Comment 6 qinzhao 2018-05-31 20:44:45 UTC
the change is in trunk, I am closing this bug.