You shall not pass! - Gandalf


Warning: This post probably appeals to a certain kind of person (who might not even enjoy the content due to its possible flaws), so continue with caution.



Hello again, esteemed reader! I hope you’ve had a pleasant, what, 2 months since my last blog entry?

Well, fear not! I’m here to make sure your appetite for knowledge is, somewhat, satisfied.

In actuality, I’ve been in a sort of writer’s block. For the past few months (summer included) I’ve been staring into the void of internship-searching, and it stared back at me. Glad to say that’s finally over including a rejection after 5 rounds of interviewing; damned stack ranking.

However, I’m here to talk about the dark times - more exactly about an accidental discovery while knee-deep in the dark times.

Context

This past summer, driven in part by ambition, in part by personal spite, I was targeting HFT internships. While I had a sudden realization by the middle of the summer, I had already gone down the rabbit hole of vibecoding some projects.

I’m talking now about these because, while preparing for an interview, I decided to actually do a deep-dive into my projects. And there I found the following piece of code:

const auto half{static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};
const std::uint64_t delimMask{half << 32 | half};
for (; start + 8 <= string.size(); start += 8)
{
    std::uint64_t stringData{};
    std::memcpy(&stringData, string.data() + start, sizeof(stringData));

    std::uint64_t cmp{stringData ^ delimMask};
    std::uint64_t mask{(cmp - 0x0101010101010101ULL) & ~cmp & 0x8080808080808080ULL};
    if (mask != 0ULL)
    {
        size_t pos{static_cast<size_t>(__builtin_ctzll(mask) / 8)};
        return start + pos;
    }
}

for (; start < string.size(); ++start)
{
    if (string[start] == delimiter)
    {
        return start;
    }
}
return -1;

Yes, I know exactly what you’re gonna say next: WTF? That’s what I said, at least.

I do not remember if it was an LLM who wrote that, or if I got inspired by Stack Overflow, but I did not have a clue what the fuck I was doing. That made me do the bare minimum and educate myself on the code I would, possibly, have to explain to another human.


Editor note:

While reviewing this draft, I’ve become aware of a flaw:

const auto half{static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};

Since char can be treated as a signed char (implementation defined), left shifting it is UB (before C++20, apparently). More exactly, if the char were to be negative, sign extension could take place; therefore, the mask would be corrupted.

A correct implementation would be:

const auto byte = static_cast<std::uint8_t>(delimiter);
const std::uint64_t delimMask = byte * 0x0101010101010101ULL;
This works because 0x0101010101010101 = 1 << 56 | ... | 1
==> delimiter * 0x0101010101010101 = delimiter * (1 << 56 | ... | 1) = delimiter << 56 | ... | delimiter (pseudo code)


The article will continue to use the bugged version, to stay faithful to my code.


SWAR - SIMD Within A Register

I’m not going to assume that you are familiar with either abbreviation.

Simply put, SIMD allows a processor to execute a single instruction over multiple independent data elements simultaneously. Modern CPUs provide dedicated vector registers and instructions to facilitate this.

I am still learning about it, so perhaps it will be a later topic. Today I am more focused on his lesser-known, uglier brother:

SWAR applies a similar principle without dedicated vector instructions. Instead, we pack multiple smaller data elements into a regular integer and exploit arithmetic and bitwise operations to process them in parallel.

Let’s start by dissecting my black magic, line by line. Sounds good? Great!

const auto half {static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};

Delimiter is supposed to be a char. For our example, we will be using ‘=’ (0x3D). What the line is trying to do is to have a whole 32-bit half filled by our delimiter character.

Show the `half` calculation
half = 0x00 | 0x00 | 0x00 | 0x00 | 0x3D | 0x3D | 0x3D | 0x3D
     = 0    | 0    | 0    | 0    | =    | =    | =    | =   

With this judgement, delimMask is simply going to be full of equals!

const std::uint64_t delimMask {half << 32 | half};
Show the `delimMask` representation
delimMask   = 0x3D | 0x3D | 0x3D | 0x3D | 0x3D | 0x3D | 0x3D | 0x3D
            = =    | =    | =    | =    | =    | =    | =    | =   


I’m going to skip the loop declaration. The next two lines are just copying the current 8-byte (64-bit) window into a uint64_t. We are trying to not invoke any UB (Undefined Behavior) regarding memory alignment, and the like, so instead of doing fun and hacky pointer casts (jk, do NOT do this), we’re doing a plain memcpy:

std::uint64_t stringData {};
std::memcpy(&stringData, string.data() + start, sizeof(stringData));

We are going to use the example string 10=heyyy. I am going to wait a tiny bit to see what you think this is going to look like in memory.

3.

2.

1.

Show the string's byte representation
stringData  = y    | y    | y    | e    | h    | =    | 0    | 1
            = 0x79 | 0x79 | 0x79 | 0x65 | 0x68 | 0x3D | 0x30 | 0x31


Now, you may wonder: WHY IS IT IN REVERSE? That is a very good question, for which the short answer is Little Endianness - the quality that memory is represented starting with the least significant byte. We are basically saying to the code, in a safe way:

Hey! See this region of memory that is “10=heyyy”? Interpret it as if it were an integer!

Therefore, the integer will represent it in reverse. Makes no sense? Thank Intel. But there are some advantages, check this Stack Exchange discussion for further enlightenment.

The black magic

We have now reached the bread and butter of this blog!

std::uint64_t cmp {stringData ^ delimMask};

That little arrow (^) is the XOR operator. What it does is that it sets bits that are equal in both numbers to 0, and to 1 otherwise.

We’re going to introduce the binary representation as well now:

Show the XOR calculation
delimMask   = 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D
            = 00111101  | 00111101  | 00111101  | 00111101  | 00111101  | 00111101  | 00111101  | 00111101

^

stringData  = y         | y         | y         | e         | h         | =         | 0         | 1
            = 0x79      | 0x79      | 0x79      | 0x65      | 0x68      | 0x3D      | 0x30      | 0x31
            = 01111001  | 01111001  | 01111001  | 01100101  | 01101000  | 00111101  | 00110000  | 00110001

=

cmp         = 01000100  | 01000100  | 01000100  | 01011000  | 01010101  | 00000000  | 00001101  | 00001100
            = 0x44      | 0x44      | 0x44      | 0x58      | 0x55      | 0x00      | 0x0D      | 0x0C


Easy enough? Time for la crème de la crème

std::uint64_t mask {(cmp - 0x0101010101010101ULL) & ~cmp & 0x8080808080808080ULL};
if (mask != 0ULL) {
        size_t pos {static_cast<size_t>(__builtin_ctzll(mask) / 8)};
        return start + pos;
}

Basically, this mind-numbing level of bit-hacks does some simple things in order:

There’s no need to believe me, we’re doing the math in order.

Show the zero-byte detection calculation
cmp         = 01000100  | 01000100  | 01000100  | 01011000  | 01010101  | 00000000  | 00001101  | 00001100

-
              00000001  | 00000001  | 00000001  | 00000001  | 00000001  | 00000001  | 00000001  | 00000001

result      = 01000011  | 01000011  | 01000011  | 01010111  | 01010011  | 11111111  | 00001100  | 00001011

&

~cmp        = 10111011  | 10111011  | 10111011  | 10100111  | 10101010  | 11111111  | 11110010  | 11110011

=

            = 00000011  | 00000011  | 00000011  | 00000111  | 00000010  | 11111111  | 00000000  | 00000011
            = 0x03      | 0x03      | 0x03      | 0x07      | 0x02      | 0xFF      | 0x00      | 0x03

&

              10000000  | 10000000  | 10000000  | 10000000  | 10000000  | 10000000  | 10000000  | 10000000
              0x80      | 0x80      | 0x80      | 0x80      | 0x80      | 0x80      | 0x80      | 0x80

=

mask        = 00000000  | 00000000  | 00000000  | 00000000  | 00000000  | 10000000  | 00000000  | 00000000
            = 0x00      | 0x00      | 0x00      | 0x00      | 0x00      | 0x80      | 0x00      | 0x00


__builtin_ctzll is just computer-ese for "give me how many trailing zeros this 64-bit number has". And we divide by 8 to find the byte where our bit is set. Of course, this works because my computer (like the vast majority of them) is a little-endian system.

Voila! We have a super complicated character search.

Now, you may wonder 2 things:

  1. What’s up with the end trailing loop?
  2. Is this even more efficient than a single loop, or std::string::find?

What’s up with the end trailing loop?

Remember this sentence:

We are trying to not invoke any UB (Undefined Behavior) regarding memory alignment, and the like, so instead of doing fun and hacky pointer casts, we’re doing a plain memcpy

You might think "But isn't memcpy, like, slow?" and you’d be right in 99% of the cases! However, let’s look at the code, and at what the compiler generates:

C++ Code
    std::uint64_t stringData {};
    std::memcpy(&stringData, string.data() + start, sizeof(stringData));
    


ASM Code (x86-64 gcc (trunk) -std=c++20 -O0)
    mov     QWORD PTR [rbp-64], 0
    mov     rax, QWORD PTR [rbp-72]
    mov     rdi, rax
    call    "std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::data()"
    mov     edx, DWORD PTR [rbp-76]
    movsxd  rdx, edx
    add     rax, rdx
    mov     rax, QWORD PTR [rax]
    mov     QWORD PTR [rbp-64], rax     % very nice, a simple MOV call!
    


As you can observe, there is no call to memcpy! In fact, this is such a widely used pattern in systems programming that the compiler can automatically generate the proper code! However, this only works if the memcpy size is constant. If we were to have the following code:

C++ Code
    std::uint64_t stringData {};
    std::memcpy(&stringData, string.data() + start, min(sizeof(stringData), string.size() - start));
    


The compiler would emit the following assembly:

ASM Code (x86-64 gcc (trunk) -std=c++20 -O0)
    [...]

    lea     rcx, [rax+rdx]
    lea     rax, [rbp-80]
    mov     rdx, rbx
    mov     rsi, rcx
    mov     rdi, rax
    call    "memcpy"    % you see the memcpy call?

    


Because the memcpy optimization requires a fixed 8-byte window, we need a trailing for loop to process the remaining (at most 7) bytes.

Is this even more efficient than a single loop, or std::string::find?

There’s only one way to find out - and that’s the next chapter!

However, let’s make some predictions.

Running at -O0, I believe that the SWAR version is going to be much faster than the loop version, and much slower than std::string::find, since that should be vectorized. However, running at -O3 should vectorize the loop version, so possibly SWAR will be the slowest variant.

Why do I think it will be faster than a simple loop? For that we still have to check the emitted assembly (-O0):

SWAR ASM Code (inner loop, excluding final 7-byte trail) (x86-64 gcc (trunk) -std=c++20 -O0)
    .L5:
        mov     QWORD PTR [rbp-64], 0
        mov     rax, QWORD PTR [rbp-72]
        mov     rdi, rax
        call    "std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::data()"
        mov     edx, DWORD PTR [rbp-76]
        movsxd  rdx, edx
        add     rax, rdx
        mov     rax, QWORD PTR [rax]
        mov     QWORD PTR [rbp-64], rax
        mov     rax, QWORD PTR [rbp-64]
        xor     rax, QWORD PTR [rbp-32]
        mov     QWORD PTR [rbp-40], rax
        movabs  rdx, -72340172838076673
        mov     rax, QWORD PTR [rbp-40]
        add     rdx, rax
        mov     rax, QWORD PTR [rbp-40]
        not     rax
        and     rdx, rax
        movabs  rax, -9187201950435737472
        and     rax, rdx
        mov     QWORD PTR [rbp-48], rax

    


We can see that for each loop iteration the SWAR variant uses ~21 instructions per 8 bytes, meaning 2.625 instructions per byte, whereas:

Scalar Loop Code (inner loop) (x86-64 gcc (trunk) -std=c++20 -O0)
    .L5:
        mov     eax, DWORD PTR [rbp-28]
        movsxd  rdx, eax
        mov     rax, QWORD PTR [rbp-24]
        mov     rsi, rdx
        mov     rdi, rax
        call    "std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::operator[](unsigned long)"
        movzx   eax, BYTE PTR [rax]
        cmp     BYTE PTR [rbp-29], al
        sete    al
        test    al, al

        % these are not executed at each iteration
        je      .L3
        mov     eax, DWORD PTR [rbp-28]
        jmp     .L4
        % ---
    


in the Scalar Loop version we are using ~10 instructions for a single byte!

TLDR: std::string::find > SWAR >> loop (-O0) | std::string::find >= loop >> SWAR (-O3) (spoiler: this didn’t happen)

Benchmarking: when memchr surprised me

The benchmark has been done on the following environment:

Processor: AMD Ryzen 9 5900HX with Radeon Graphics 3.30 GHz Edition: Windows 11 Pro Version: 23H2 g++ Version: g++.exe (Rev8, Built by MSYS2 project) 15.2.0

The benchmark itself is going to be simple: 1000 runs on strings where the character is found at the beginning, middle, and end of the string.

Click to see the benchmark code
    #include <algorithm>
    #include <chrono>
    #include <cstdint>
    #include <cstring>
    #include <iomanip>
    #include <iostream>
    #include <string>
    #include <utility>
    #include <vector>

    using Clock = std::chrono::steady_clock;

    int searchCharacter1(const std::string &string, int start, char delimiter)
    {
        const auto half{static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};
        const std::uint64_t delimMask{half << 32 | half};
        for (; start + 8 <= static_cast<int>(string.size()); start += 8)
        {
            std::uint64_t stringData{};
            std::memcpy(&stringData, string.data() + start, sizeof(stringData));

            std::uint64_t cmp{stringData ^ delimMask};
            std::uint64_t mask{(cmp - 0x0101010101010101ULL) & ~cmp & 0x8080808080808080ULL};
            if (mask != 0ULL)
            {
                size_t pos{static_cast<size_t>(__builtin_ctzll(mask) / 8)};
                return start + static_cast<int>(pos);
            }
        }

        for (; start < static_cast<int>(string.size()); ++start)
        {
            if (string[start] == delimiter)
            {
                return start;
            }
        }
        return -1;
    }

    int searchCharacter2(const std::string &string, int start, char delimiter)
    {
        for (; start < static_cast<int>(string.size()); start++)
        {
            if (string[start] == delimiter)
                return start;
        }
        return -1;
    }

    int searchCharacterFind(const std::string &string, int start, char delimiter)
    {
        size_t pos = string.find(delimiter, static_cast<size_t>(start));
        return (pos == std::string::npos) ? -1 : static_cast<int>(pos);
    }

    template <typename Fn>
    std::pair<int, double> bench(Fn &&bench_function, const std::string &search_string, char search_char)
    {
        auto t0 = Clock::now();
        int result = bench_function(search_string, 0, search_char);
        auto t1 = Clock::now();

        return {
            result,
            std::chrono::duration<double, std::nano>(t1 - t0).count()
        };
    }

    void run_case(size_t n, const char *pos_label, const std::string &data, int runs, volatile int &sink)
    {
        double total1_ns = 0.0;
        double total2_ns = 0.0;
        double total3_ns = 0.0;
        bool match = true;

        for (int r = 0; r < runs; ++r)
        {
            auto [r1, t1] = bench(searchCharacter1, data, ';');
            auto [r2, t2] = bench(searchCharacter2, data, ';');
            auto [r3, t3] = bench(searchCharacterFind, data, ';');

            sink += r1 + r2 + r3;
            if (r1 != r2 || r1 != r3)
                match = false;

            total1_ns += t1;
            total2_ns += t2;
            total3_ns += t3;
        }

        double avg1 = total1_ns / runs;
        double avg2 = total2_ns / runs;
        double avg3 = total3_ns / runs;

        std::cout << std::left << std::setw(8) << n
                << std::setw(8) << pos_label
                << std::right << std::fixed << std::setprecision(1)
                << std::setw(12) << avg1
                << std::setw(14) << avg2
                << std::setw(16) << avg3
                << std::setw(12) << std::setprecision(2) << (avg2 / avg1) << "x"
                << std::setw(10) << (avg3 / avg1) << "x"
                << std::setw(8) << (match ? "True" : "False") << "\n";
    }

    int main()
    {
        const std::vector<size_t> sizes = {8, 100, 1000, 10000};
        constexpr int runs = 1000;
        volatile int sink = 0;

        std::cout << std::left << std::setw(8) << "Size"
                << std::setw(8) << "Pos"
                << std::right << std::setw(12) << "SWAR (ns)"
                << std::setw(14) << "Scalar (ns)"
                << std::setw(16) << "str::find (ns)"
                << std::setw(13) << "Scalar/SWAR"
                << std::setw(11) << "find/SWAR"
                << std::setw(8) << "Match\n";
        std::cout << std::string(90, '-') << "\n";

        for (size_t n : sizes)
        {
            std::string data_first(n, 'a');
            std::string data_middle(n, 'a');
            std::string data_end(n, 'a');

            data_first[0] = ';';
            data_middle[n / 2] = ';';
            data_end[n - 1] = ';';

            run_case(n, "first", data_first, runs, sink);
            run_case(n, "middle", data_middle, runs, sink);
            run_case(n, "end", data_end, runs, sink);
        }

        if (sink == -1)
            std::cout << sink << "\n";
        return 0;
    }

    

Windows results

The tables below include the columns: Scalar/SWAR and find/SWAR. Those are the Scalar time / SWAR time and find time / SWAR time ratios. Therefore a lower number means that Scalar/find did better than SWAR. Conversely, a larger number means the opposite.

Running the benchmark with g++ -O0:

Size    Pos        SWAR (ns)   Scalar (ns)  str::find (ns)  Scalar/SWAR  find/SWAR  Match
------------------------------------------------------------------------------------------
8       first           51.2          50.2            48.9        0.98x      0.96x    True
8       middle          51.4         126.1            48.9        2.45x      0.95x    True
8       end             57.5         180.0            51.7        3.13x      0.90x    True
100     first           48.9          51.6            46.8        1.06x      0.96x    True
100     middle         201.5         783.8            58.9        3.89x      0.29x    True
100     end            415.3        1458.9            81.1        3.51x      0.20x    True
1000    first           48.4          51.6            47.1        1.07x      0.97x    True
1000    middle        1088.2        7080.7           184.8        6.51x      0.17x    True
1000    end           1547.1       13740.4           305.2        8.88x      0.20x    True
10000   first           49.2          45.2            47.2        0.92x      0.96x    True
10000   middle        7050.8       73804.5          1389.4       10.47x      0.20x    True
10000   end          15720.7      159144.6          3036.3       10.12x      0.19x    True


Running with g++ -O3:

Size    Pos        SWAR (ns)   Scalar (ns)  str::find (ns)  Scalar/SWAR  find/SWAR  Match
------------------------------------------------------------------------------------------
8       first           31.3          31.6            33.4        1.01x      1.07x    True
8       middle          32.7          32.0            33.5        0.98x      1.02x    True
8       end             32.0          32.7            32.6        1.02x      1.02x    True
100     first           31.5          32.1            32.2        1.02x      1.02x    True
100     middle          33.6          49.0            44.4        1.46x      1.32x    True
100     end             37.1          64.1            69.6        1.73x      1.88x    True
1000    first           31.4          32.4            32.0        1.03x      1.02x    True
1000    middle          74.5         167.7           191.8        2.25x      2.57x    True
1000    end             98.5         289.8           442.7        2.94x      4.49x    True
10000   first           31.7          31.7            32.0        1.00x      1.01x    True
10000   middle         349.6        1776.2          1388.7        5.08x      3.97x    True
10000   end            669.2        2582.3          2758.4        3.86x      4.12x    True


Hmm, very interesting. While running with -O0 we can see that std::string::find >> SWAR, when running with -O3 we get the exact opposite effect. I was expecting std::string::find and loop to use SIMD.

The following makes it all make sense: std::string::find is using pre-compiled library code, while the SWAR variant is compiled with -O3. This means that the optimization touches only our part of the code, not the linked library. However, this means 1 of 2 things:

  1. SWAR is faster than SIMD vectorization (very highly unlikely)
  2. the library code is not vectorized on my machine


Using GDB to breakpoint memchr (aka what std::string::find calls), we get the following disassembly:

ASM Code
    Dump of assembler code for function ucrtbase!memchr:
    => 0x00007ff8132110d0 <+0>:     test   %r8,%r8
    0x00007ff8132110d3 <+3>:     je     0x7ff8132110e2 <ucrtbase!memchr+18>
    0x00007ff8132110d5 <+5>:     cmp    %dl,(%rcx)
    0x00007ff8132110d7 <+7>:     je     0x7ff8132110e2 <ucrtbase!memchr+18>
    0x00007ff8132110d9 <+9>:     inc    %rcx
    0x00007ff8132110dc <+12>:    sub    $0x1,%r8
    0x00007ff8132110e0 <+16>:    jne    0x7ff8132110d5 <ucrtbase!memchr+5>
    0x00007ff8132110e2 <+18>:    neg    %r8
    0x00007ff8132110e5 <+21>:    sbb    %rax,%rax
    0x00007ff8132110e8 <+24>:    and    %rcx,%rax
    0x00007ff8132110eb <+27>:    ret
    0x00007ff8132110ec <+28>:    int3
    0x00007ff8132110ed <+29>:    int3
    0x00007ff8132110ee <+30>:    int3
    0x00007ff8132110ef <+31>:    int3
    0x00007ff8132110f0 <+32>:    int3
    0x00007ff8132110f1 <+33>:    int3
    0x00007ff8132110f2 <+34>:    int3
    0x00007ff8132110f3 <+35>:    int3
    0x00007ff8132110f4 <+36>:    int3
    0x00007ff8132110f5 <+37>:    int3
    0x00007ff8132110f6 <+38>:    data16 nopw 0x0(%rax,%rax,1)
    


There’s no sign of vectorization! So I am guessing that on my machine memchr is not 100% optimized.

Even with this part of the explanation, there’s still the Scalar loop enigma.

Compiling with the -fopt-info-vec-all flag yields the following:

.\bench.cpp:43:18: missed: couldn’t vectorize loop .\bench.cpp:43:18: missed: not vectorized: could not determine main exit from loop with multiple exits.

This confirms that our loop couldn’t be vectorized!

We should still check this benchmark on a Linux machine. For this experiment, I’m going to use WSL2.

Debugging further on WSL2

We are running on the following environment:

WSL version: 3.0.5.0 Kernel version: 6.18.58.1-1 g++ version: g++ (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0

Note: there is a compiler version discrepancy, which means the benchmark is most possibly flawed in one manner or another. Take the results with a grain of salt.

Running the same tests on WSL2:

$ g++ bench.cpp -O0 -o ./bench

Size    Pos        SWAR (ns)   Scalar (ns)  str::find (ns)  Scalar/SWAR  find/SWAR  Match
------------------------------------------------------------------------------------------
8       first           31.2          26.3            28.4        0.84x      0.91x    True
8       middle          31.6          37.2            30.0        1.18x      0.95x    True
8       end             31.1          53.1            30.2        1.71x      0.97x    True
100     first           25.8          22.5            23.2        0.87x      0.90x    True
100     middle          45.7         228.8            24.9        5.01x      0.55x    True
100     end             89.4         461.3            25.0        5.16x      0.28x    True
1000    first           26.5          23.7            23.5        0.89x      0.89x    True
1000    middle         348.9        2271.5            27.6        6.51x      0.08x    True
1000    end            637.7        4329.3            28.5        6.79x      0.04x    True
10000   first           26.9          24.4            22.8        0.91x      0.85x    True
10000   middle        3098.5       22363.4            49.4        7.22x      0.02x    True
10000   end           6086.7       43719.8            68.1        7.18x      0.01x    True


$ g++ bench.cpp -O3 -o ./bench

Size    Pos        SWAR (ns)   Scalar (ns)  str::find (ns)  Scalar/SWAR  find/SWAR  Match
------------------------------------------------------------------------------------------
8       first           21.7          21.1            23.7        0.97x      1.09x    True
8       middle          21.7          22.2            22.9        1.02x      1.06x    True
8       end             21.6          22.3            22.9        1.03x      1.06x    True
100     first           21.6          21.1            22.9        0.98x      1.06x    True
100     middle          23.6          30.4            23.0        1.29x      0.97x    True
100     end             25.6          50.8            23.9        1.98x      0.93x    True
1000    first           23.0          22.3            24.6        0.97x      1.07x    True
1000    middle          56.0         193.2            27.0        3.45x      0.48x    True
1000    end             85.3         363.4            26.9        4.26x      0.32x    True
10000   first           21.5          21.1            22.9        0.98x      1.07x    True
10000   middle         312.7        1733.7            42.8        5.54x      0.14x    True
10000   end            650.2        3545.9            65.8        5.45x      0.10x    True


These results are promising. We can see that std::string::find is now up to 10x faster than our SWAR version.

Using gdb again:

ASM Code
    Dump of assembler code for function memchr_ifunc:
    => 0x00007ffff78a9310 <+0>:     endbr64
        0x00007ffff78a9314 <+4>:     mov    0x170bad(%rip),%rcx        # 0x7ffff7a19ec8
        0x00007ffff78a931b <+11>:    lea    0xb47e(%rip),%rax        # 0x7ffff78b47a0 <__memchr_sse2>
        0x00007ffff78a9322 <+18>:    mov    0xb8(%rcx),%edx
        0x00007ffff78a9328 <+24>:    mov    %edx,%esi
        0x00007ffff78a932a <+26>:    and    $0x120,%esi
        0x00007ffff78a9330 <+32>:    cmp    $0x120,%esi
        0x00007ffff78a9336 <+38>:    je     0x7ffff78a9340 <memchr_ifunc+48>
        0x00007ffff78a9338 <+40>:    ret
        0x00007ffff78a9339 <+41>:    nopl   0x0(%rax)
        0x00007ffff78a9340 <+48>:    mov    0x1a4(%rcx),%ecx
        0x00007ffff78a9346 <+54>:    test   $0x2,%ch
        0x00007ffff78a9349 <+57>:    je     0x7ffff78a9338 <memchr_ifunc+40>
        0x00007ffff78a934b <+59>:    mov    %edx,%esi
        0x00007ffff78a934d <+61>:    and    $0x800,%esi
        0x00007ffff78a9353 <+67>:    test   %edx,%edx
        0x00007ffff78a9355 <+69>:    js     0x7ffff78a9380 <memchr_ifunc+112>
        0x00007ffff78a9357 <+71>:    lea    0xfdee2(%rip),%rax        # 0x7ffff79a7240 <__memchr_avx2_rtm>
        0x00007ffff78a935e <+78>:    test   %esi,%esi
        0x00007ffff78a9360 <+80>:    jne    0x7ffff78a9338 <memchr_ifunc+40>
        0x00007ffff78a9362 <+82>:    and    $0x4,%ch
        0x00007ffff78a9365 <+85>:    lea    0xeffd4(%rip),%rdx        # 0x7ffff7999340 <__memchr_avx2>
        0x00007ffff78a936c <+92>:    lea    0xb42d(%rip),%rax        # 0x7ffff78b47a0 <__memchr_sse2>
        0x00007ffff78a9373 <+99>:    cmove  %rdx,%rax
        0x00007ffff78a9377 <+103>:   ret
        0x00007ffff78a9378 <+104>:   nopl   0x0(%rax,%rax,1)
        0x00007ffff78a9380 <+112>:   and    $0x40000000,%edx
        0x00007ffff78a9386 <+118>:   je     0x7ffff78a9357 <memchr_ifunc+71>
        0x00007ffff78a9388 <+120>:   test   %esi,%esi
        0x00007ffff78a938a <+122>:   lea    0x1051ef(%rip),%rdx        # 0x7ffff79ae580 <__memchr_evex>
        0x00007ffff78a9391 <+129>:   lea    0x10c8a8(%rip),%rax        # 0x7ffff79b5c40 <__memchr_evex_rtm>
        0x00007ffff78a9398 <+136>:   cmove  %rdx,%rax
        0x00007ffff78a939c <+140>:   ret
    End of assembler dump.
    


After running breakpoints on all possible variants, my C runtime seems to pick __memchr_avx2:

Snippet of the dump of __memchr_avx2
    Dump of assembler code for function __memchr_avx2:
    => 0x00007ffff7999340 <+0>:     endbr64
        [...]

        % The important part ---
        vpbroadcastb %xmm0, %ymm0
        vpcmpeqb     (%rdi), %ymm0, %ymm1
        vpmovmskb    %ymm1, %eax
        tzcnt        %eax, %eax
        % ---

        [...]

    End of assembler dump.
    

Running the same -fopt-info-vec-all flag while compiling yields the following:

bench.cpp:43:18: note: *** Analysis failed with vector mode V2DI bench.cpp:43:18: note: *** Skipping vector mode V16QI, which would repeat the analysis for V2DI

While the error message differs from the Windows version, we can notice that the Scalar loop still failed vectorization.

I can’t stress this enough, but in a proper benchmark you’d use the same compiler version! I’m going to keep the flaws, however, for this post.

Conclusions

Okay, I think we’ve played enough with objdump and gdb. You, my dear reader, are probably very tired from looking at all of this archaic “nonsense” that I’ve provided here. However, here are a few observations to keep in mind for the future:


Moreover, even though the benchmark is somewhat flawed, it is still very informative about the optimizations, or lack thereof, that come prebuilt with your compiler’s C runtime - and about the ever-growing list of differences between Windows’s runtimes and Unix-based runtimes.

Actually, after doing a quick investigation, I’ve found the following page:

In Visual Studio 2015, the CRT was refactored into new binaries. The Universal CRT (UCRT) contains the functions and globals exported by the standard C99 CRT library. The UCRT is now a Windows component, and ships as part of Windows 10 and later versions. The static library, DLL import library, and header files for the UCRT are now found in the Windows SDK.

The vcruntime library contains Visual C++ CRT implementation-specific code: exception handling and debugging support, runtime checks and type information, implementation details, and certain extended library functions. The vcruntime library version needs to match the version of the compiler you’re using.

Inspecting the tables, the SDK is found in the ucrtbase.dll file (remember, in the benchmarks we used ucrtbase!memchr!), and the MSVC runtime is found in vcruntime<version>.dll.

Doing a quick objdump for vcruntime140.dll (my version of the file):

Snippet of vcruntime140!memchr
    Disassembly of section .text:

        0000000180011e90 <.text+0x10e90>:
        180011e90:   0f b6 d2                movzx  edx,dl
        180011e93:   69 d2 01 01 01 01       imul   edx,edx,0x1010101   % editor note: I am validated by Microsoft devs!
        180011e99:   66 0f 6e c2             movd   xmm0,edx
        180011e9d:   66 0f 70 c0 00          pshufd xmm0,xmm0,0x0
        
        % skipping code

        180011eca:   49 83 f8 20             cmp    r8,0x20
        180011ece:   72 39                   jb     0x180011f09
        180011ed0:   66 0f 6f 09             movdqa xmm1,XMMWORD PTR [rcx]
        180011ed4:   66 0f 74 c8             pcmpeqb xmm1,xmm0      % notice the weird names!
        180011ed8:   66 48 0f d7 c1          pmovmskb rax,xmm1
        180011edd:   48 0f bc c0             bsf    rax,rax
        180011ee1:   75 39                   jne    0x180011f1c
        180011ee3:   66 0f 6f 49 10          movdqa xmm1,XMMWORD PTR [rcx+0x10]
        180011ee8:   48 83 c1 10             add    rcx,0x10
        180011eec:   66 0f 74 c8             pcmpeqb xmm1,xmm0
        180011ef0:   66 48 0f d7 c1          pmovmskb rax,xmm1
        180011ef5:   48 0f bc c0             bsf    rax,rax
        180011ef9:   75 21                   jne    0x180011f1c
        180011efb:   48 83 c1 10             add    rcx,0x10
        
        % some unrolled verification ...

    


We can see that MSVC’s version of memchr is vectorized - compared to the SDK version that we’ve been using so far! While I could do another version of the benchmark now, with this insight in mind, it would probably be very similar to the WSL version, and I am too lazy.

All in all, I can say that it’s been a fun journey to write this entry. It’s been one of my first times really understanding what my (not Godbolt’s) compilers produced - and I’ve really enjoyed it!

I hope that in my ramblings you’ve also been able to find something interesting, or even useful!

There’s probably going to be some sort of gap again before I post something new, so I wish you a very Merry Christmas close to your loved ones, a Happy New Year, and, for my Romanian readers:

LA MULTI ANI ROMANIA! (in avans)