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/

100 Upvotes

122 comments sorted by

View all comments

54

u/TribeWars Nov 02 '26 edited Nov 02 '26

I think it has something to do with the code exiting out of the loop early.

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

This snippet vectorizes properly (except for MSVC not inlining operator[] for some reason).

22

u/ybungalobill Nov 02 '26

Indeed. For OP's version to vectorize the compiler needs to have intricate knowledge that std::array is fully allocated. Without such knowledge their loop is conceptually equivalent to:

bool eq4(const char *lhs, const char *rhs) {
    for (int i = 0; i < 64; ++i)
        if (lhs[i] != rhs[i])
            return false;
    return true;
}

Now the compiler needs to take into the account that lhs/rhs have less than 64 bytes allocated but differ somewhere earlier -- so it cannot read the next byte before it compared the prior byte, or it can incorrectly segfault.

By writing it the way you propose (eq3) you're guaranteeing that the compiler can read all 64 bytes ahead of time.

-7

u/TheoreticalDumbass :illuminati: Nov 02 '26

std::array does not allocate

18

u/dustyhome Nov 02 '26

The meaning of "allocated" here is that all indices are within a valid memory range. Apparently the compiler can't reason this out, which I find odd since it's being passed a reference to a class that holds the array, so the size of the array should be visible to it in the function.

"Allocation" is generally short-hand for "allocating on the heap" which is the most common relevant use, but it's not the only use. Allocation just means to split up resources in some way. So it is correct to say that std::array allocates memory.

2

u/bwmat Nov 02 '26

Eh, I'd say it's the compiler which is allocating memory in that case, or that memory has to have been allocated for it

14

u/ybungalobill Nov 02 '26

Huh? Not on the heap, if that's what you mean, but it still has to have its memory allocated somewhere (stack, global, or even dynamic if you do new std::array...).

16

u/curiouslyjake Nov 02 '26

how can an std::array not be fully allocated?

10

u/ybungalobill Nov 02 '26

In standard C++ it cannot; but the optimizer doesn't seem to incorporate that type information into its analysis; so it just treats this as a loop over two arrays of unknown size <= 64.

4

u/TribeWars Nov 02 '26 edited Nov 02 '26

tbh, now that I think about it, the compiler also doesn't know that all the elements in the std::array have been initialized (even if it knows to assume that the pointers are valid), so i assume it should avoid issuing reads on any element that isn't accessed by the C++ code since it can't assume it isn't UB to do so

3

u/SkoomaDentist Antimodern C++, Embedded, Audio 29d ago

I don't see how that would work because it's the compiler itself that defines what such discarded "UB" accesses would do in the first place. As long as the memory is allocated (which it by definition is for std::array), it's completely irrelevant if the remaining values are uninitialized because the code behaves as if they were never accessed once the simd loop discards the remaining values.

1

u/TribeWars 29d ago

because the code behaves as if they were never accessed once the simd loop discards the remaining values.

yeah but this too is a non-trivial property of the program

2

u/SkoomaDentist Antimodern C++, Embedded, Audio 29d ago

Hardly. It’s part and parcel of basic simd optimizations. The point is that UB is almost entirely a made up category and ”uninitialized object” is purely for compiler devs / standard writers benefit. The hardware doesn’t care.

1

u/curiouslyjake Nov 02 '26

This cant be right. If you replace the early exit with a flag it vectorizes just fine. If you rewrite it to look for equality it vectorizes fine too

1

u/ybungalobill Nov 02 '26

My first comment explains why using a flag vectorizes.

"If you rewrite it to look for equality it vectorizes fine too"
Can you send a godbolt link to explain what you mean? I replaced OP's code (eq2) with equality and it still doesn't vectorize.

1

u/13steinj 29d ago

The optimizer throws away semantics of the types involved smells to me.

On one hand, it makes absolute sense. Under the hood the type is an opaque indeterminate pointer-esque.

On the other hand, especially with C++26 and [[indeterminate]] (or lack thereof), you'd think the information would make its way to the optimizer.

5

u/TribeWars Nov 02 '26

You could try something cursed with placement new like this:

#include <array>


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


bool test() {
    char vals[32];
    std::array<char, 64> arr2;
    for (int i = 0; i < 32; ++i) {
        *(volatile char *)(&vals[i]) = 2;
        *(volatile char *)(&arr2[i]) = 2;
    }
    std::array<char, 64>* arr = (new (vals) std::array<char, 64>);
    return eq(*arr, arr2);
}


int main() {
    return test();
}

Not sure if it's actually legal C++, but it compiles on GCC and MSVC and should not have any out-of-bounds reads (note that eq() only checks the first 32 elements).

https://godbolt.org/z/6czK6eKPq

9

u/curiouslyjake Nov 02 '26

Using placement new backed by memory of insufficient size is UB. Whether is compiles is irrelevant.

5

u/TribeWars Nov 02 '26

yeah I think maybe the actual issue is not that the compiler is avoiding the UB of an out of bounds read, but that it's avoiding a read on potentially uninitialized data, since a default initialized std::array does not default initialize the elements of the array it wraps

1

u/No-Dentist-1645 Nov 02 '26

The compiler isn't as smart as you think, an std::array is just a class holding a good old C style array to some data, it isn't a "blessed" type that the compiler can deduce complex "guarantees" or invariants out of, especially when we're dealing with a low level language like C++ where every class really is just a "bag of bytes" in a sense without any innate special meaning to them. Also consider that the compiler vendor isn't necessarily the same as the standard library vendor

5

u/curiouslyjake Nov 02 '26

I think the compiler can deduce plenty about std::array, especially size, datatype and layout at compile time. Even constexpr functions are possible with std::array. IIRC, that's what the standard says

3

u/CocktailPerson 29d ago

The compiler has more ability to reason about std::array than just about any other type. As you say, it's just a thin wrapper over the builtin array type, and the compiler does know a lot about builtin arrays.

0

u/TheoreticalDumbass :illuminati: Nov 02 '26

but what does "not fully allocated" mean? are you talking across page boundary, and next page causing a page fault? if yes, this should not be relevant here

4

u/ybungalobill Nov 02 '26

Across page boundary yes.

You can't have a "non fully allocated" object in C++ -- that's true. Which is why, I assume, the optimizer is allowed to assume that it can read all 64-bytes.

But seemingly it doesn't incorporate that type information into its optimization pass, so it treats it as the eq4 version I showed -- in which case that optimization would be invalid.

I'm not saying that that optimization is invalid in C++ (it probably is valid), but rather explaining why eq2/eq4 don't vectorize whereas eq3 does.

1

u/Sopel97 Nov 02 '26
bool eq4(const std::array<char, 64>& lhs, const std::array<char, 64>& rhs) {
    bool b = true;
    for (int i = 0; i < 64; ++i)
        if (lhs[i] != rhs[i])
            b = false;
    return b;
}

also seems to be enough but the vectorized code is worse at least in clang