M
M
MrBman2018-12-09 19:29:11
C++ / C#
MrBman, 2018-12-09 19:29:11

Why does clang (x86-64 7.0.0) generate worse code (in this example)?

Hello!
I'm learning C, reading books a little, and learning how standard library functions work. Then I try to implement them myself. I use the cppreference site and the libc-OpenBSD sources when I want to compare my code or see how it's done there, I use the godbolt Compiler Exlorer for comparison.
So, I wrote the following code for the standard strrchr function:

char *strrchr(char const *beg, int chr)
{
  char const *fnd;

  for (fnd = NULL; *beg != '\0'; ++beg)
    if (*beg == (char)chr)
      fnd = beg;
  return (char *)fnd;
}

Then I looked at how it is implemented in OpenBSD (not verbatim):
char *strrchr(char const *beg, int chr)
{
  char const *fnd;

  for (fnd = NULL;; ++beg) {
    if (*beg == (char)chr)
      fnd = beg;
    if (*beg == '\0')
      return (char *)fnd;
  }
}

Why does the compiler for my implementation generate worse code than for the OpenBSD implementation?
(in both cases I used: first without optimizations, then the optimization flag -O3)
What is the fundamental difference, I can’t understand?
What can I read to understand how to write such C code so that the compiler generates good code?
What does it depend on?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
code07734, 2019-01-17
@code07734

Look at the assembler that the compiler produces.
The compiler does not always guess to optimize.
It looks like they have fewer conditional jumps, and your code is written in such a way that the compiler will not come up with an optimization for it.
They have 2 if'a will become one conditional transition. You have - 1 if it will become.
In the loop, you have more checks, the compiler does not guess to take out the brackets - it does not learn like a neural network or a person.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question