Bug 95821 - Failure to optimize strchr to use memchr for string constant
Summary: Failure to optimize strchr to use memchr for string constant
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 11.0
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: missed-optimization
Depends on:
Blocks:
 
Reported: 2020-06-22 17:07 UTC by Gabriel Ravier
Modified: 2023-08-24 21:31 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2021-12-22 00:00:00


Attachments
A patch (1.12 KB, patch)
2022-06-17 01:48 UTC, H.J. Lu
Details | Diff

Note You need to log in before you can comment on or make changes to this bug.
Description Gabriel Ravier 2020-06-22 17:07:10 UTC
auto f(char c)
{
    return strchr("123", c);
}

This can be optimized to `return memchr("123", c, 4)`. This transformation is done by LLVM, but not by GCC.
Comment 1 Jakub Jelinek 2020-06-22 17:20:06 UTC
For -Os that is an undesirable change because it makes the code larger.  But otherwise yes, seems useful.
Comment 2 Andrew Pinski 2021-12-22 07:35:11 UTC
Confirmed.
Though for small strings it might even make sense to inline it, eg.:
auto f(char c)
{
    return strchr("123", c);
}
to
auto f(char c)
{
  auto t = "123";
  int t1;
  switch (c)
    {
       case '1':
         t1 = 1;
       case '2':
         t1 = 2;
       case '3':
         t1 = 3;
       default:
         t = 0;
         return t;
    }
   return t+t1;
}
Comment 3 Andrew Pinski 2021-12-22 07:39:37 UTC
(In reply to Andrew Pinski from comment #2)
> Confirmed.
> auto f(char c)
> {
>   auto t = "123";
>   int t1;
>   switch (c)
>     {
>        case '1':
>          t1 = 1;
>        case '2':
>          t1 = 2;
>        case '3':
>          t1 = 3;
>        default:
>          t = 0;
>          return t;
>     }
>    return t+t1;
> }

I missed '\0' (and break's):

auto f(char c)
{
  auto t = "123";
  int t1;
  switch (c)
    {
       case '1':
         t1 = 1;
         break;
       case '2':
         t1 = 2;
         break;
       case '3':
         t1 = 3;
         break;
       case '\0':
         t1 = 4;
         break;
       default:
         t = 0;
         return t;
    }
   return t+t1;
}
Comment 4 H.J. Lu 2022-06-17 01:48:43 UTC
Created attachment 53157 [details]
A patch