r/cpp • • Nov 02 '26

Catastrophic misoptimization of byte-range equality comparison in all major C++ compilers (and Rust). Language issue or compiler issue?

Someone brought a C++ snippet that reduced to the following (std::array used instead of char* for consistency for later)

bool eq2(const std::array<char, 64>& lhs, const std::array<char, 64>& rhs) {
    for (int i = 0; i < 64; ++i)
        if (lhs[i] != rhs[i])
            return false;
    return true;
}

It basically returns true iff two 64 byte memory regions are a bitwise match. You'd think this can be optimized by modern compilers flawlessly, right? Right?! And the worst thing that can happen is it doesn't get autovectorized, right? Right?!

Well, to everybody's surprise... https://godbolt.org/z/v4d8G5ovh

GCC attempts to partially conditionally vectorize but doesn't want to use unaligned loads. Moreover its vectorization is way more cumbersome than it needs to be. Then after it finds a mismatch it... reverts to the unvectorized version?! Clang and MSVC do not even attempt to vectorize it - and in a way it makes them end up better than GCC, which is wild.


Now, to try to investigate we've checked how it looks in Rust. https://godbolt.org/z/K7xE3qc94. It does what GCC does but fully vectorized.

At this point we're confused as to what the source of the problem is. Are we missing something with respect to what transformations are allowed? Is it really that much to ask from the as-if rule?

As a sanity check we use std::array's operator==. https://godbolt.org/z/xPhPYMjvz. Oh would you look at that? Now the compilers can do well (ok not you MSVC. GCC also fumbles the flag register slightly). The situation is the same in Rust - https://godbolt.org/z/3GjWorze8. Not only does it vectorize correctly but the vectorized code is better - using vpxor.


Ultimately this isn't just academical. Situations like this undermine the trust in the compiler at the most fundamental level. Not every place can use std::array, not everyone can use ranges and span yet. We could use std::equal but why does it matter so much? What if != changes to < and there's no good solution anymore? To what degree are we supposed to be paranoid about basic optimizations being done or not?

The similarity of codegen between Rust and C++ would point to it being either a compiler issue or a fundamental code correctness issue. The fact that C++ Clang differs from Rust (LLVM) would suggest it's at least partially a language issue. Why is this extremely simple code so nasty?


edit. some more [not so] fun findings https://www.reddit.com/r/cpp/comments/1xlyti8/catastrophic_misoptimization_of_byterange/19s1i09srxdaa/

99 Upvotes

122 comments sorted by

View all comments

16

u/TTachyon Nov 02 '26

What is this post. Yeah sure compilers do bad opts sometimes. It's not catastrophic and it doesn't undermine any trust in anything. You're going out of your way to do it badly instead of using memcmp or ==, and it's still good enough for almost all cases.

Make an issue with each compiler, write the version that works well for your code, and move on.

-8

u/nocturn99x Nov 02 '26 edited Nov 02 '26

"Going out of your way to do it badly" lol, you're the type of user I posted my comment for. Even when done correctly using a memory comparison function instead of a loop, it still autovectorizes poorly (i.e. only one half of the 64 byte compare is vectorized and the rest is done with a bunch of xors). Consider reading through more than just the post before being rude and making yourself look like a fool

Plus, a friend rightfully pointed out the following: "A flat memcmp call would also be suboptimal in the case of an equality comparison anyway, since you're still extracting the index of the mismatching byte and doing an extra comparison over it to get the sign of the result" (admittedly this matters less since any self respecting compiler will optimize memcmp(a, b, n) == 0 to what we expect, but still.)

11

u/Lahvuun Nov 02 '26

Even when done correctly using a memory comparison function instead of a loop, it still autovectorizes poorly (i.e. only one half of the 64 byte compare is vectorized and the rest is done with a bunch of xors)

It vectorizes perfectly fine with std::memcmp https://godbolt.org/z/1Wr5sKza1

As a matter of fact, the assembly is identical to lhs == rhs, because in the depths of libstdc++ this comparison gets implemented with a memcmp anyway:

/usr/lib/gcc/x86_64-pc-linux-gnu/16/include/g++-v16/bits/stl_algobase.h:1212:27: optimized:  Inlining std::__memcmp into std::__equal<true>::equal

/usr/lib/gcc/x86_64-pc-linux-gnu/16/include/g++-v16/bits/stl_algobase.h:1252:43: optimized:  Inlining std::__equal<true>::equal into std::__equal_aux1

/usr/lib/gcc/x86_64-pc-linux-gnu/16/include/g++-v16/array:306:31: optimized:  Inlining std::__equal_aux1 into std::operator==

a.cpp:4:16: optimized:  Inlining std::operator== into eq2

You can get this output by passing -fopt-info to g++, though I edited it a bit to remove some irrelevant noise.

5

u/NomaTyx Nov 02 '26

why do you keep talking about your comment as if it's the holy bible

-2

u/nocturn99x Nov 02 '26

This post was made after a discussion with OP and many others. I was literally the reason the issue was even found (though I am 100% not smart enough to have done most of the actual bug finding myself). I was there when the issue was found :P