This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug middle-end/78809] Inline strcmp with small constant strings
- From: "qing.zhao at oracle dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Tue, 24 Oct 2017 21:07:31 +0000
- Subject: [Bug middle-end/78809] Inline strcmp with small constant strings
- Auto-submitted: auto-generated
- References: <bug-78809-4@http.gcc.gnu.org/bugzilla/>
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