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 middle-end/78809] Inline strcmp with small constant strings


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78809

--- Comment #17 from Qing Zhao <qing.zhao at oracle dot com> ---
(In reply to Wilco from comment #16)

>> const char s[8] = “abcd\0abc”;  // null byte in the middle of the string
>> int f2(void) { return __builtin_strcmp(s, "abc") != 0; }
>> int f3(void) { return __builtin_strcmp(s, “abc”); }
>> 
>> can either of the above f2 or f3 been optimized to memcmp? seems not.
> 
> You never get that to the null byte as the memcmp only compares strlen("abc"+1)
> characters.

Yes, this is correct for memcmp, but not for strcmp.  strcmp will get to the
null byte. 
as a result,  

const char s[8] = “abcd\0abc”;
strcmp (s, “abc”) != 0.       // s = “abcd", which is != “abc"
strncmp (s, “abc”, 3) == 0
memcmp(s, “abc”, 3) == 0

So, strcmp cannot optimized to memcmp 

> However do you mean an input string which is shorter than the
> constant string? That's fine as this will compare not-equal in the memcmp.

for the input string is shorter than the constant string, for example: 

const char s[8] = “ab\0\0abcd”;
strcmp (s, “abc”) != 0
strncmp (s, “abc”, 3) != 0
memcmp (s, “abc”,3) != 0

In a summary, since it’s NOT easy for the compiler to know where is the
“Null_terminator” 
in the string, strcmp is NOT reasonable to be optimized to memcmp whenever its
result is 
used to compare with zero or not.

But for strncmp, if the result is to compare with zero, it might be reasonable
to optimized it
to the corresponding memcmp, i.e

strncmp (s, “abc”, 3) != 0

could be optimized to

memcmp (s, “abc”, 3) != 0

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