Skip to content

<algorithm>: Silent bad codegen for vectorized meow_element() above 4 GB #3617

@StephanTLavavej

Description

@StephanTLavavej

Reported by Johan Lundberg and Felix Ungman. This is a regression in VS 2022 17.4 after the PR series #2447 #2821 #2825.

This repro is specific to x64 because it requires a range over 4 gigabytes. The size in bytes, not the size in elements, is the threshold, so we can repro it with slightly over 1 billion ints.

D:\GitHub\STL\out\x64>type meow.cpp
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    for (const auto n : {0x3FFF'FFFFull, 0x4000'0010ull}) {
        vector<int> v(n, 25);
        v[n - 2] = 24;
        v[n - 1] = 26;

        cout << "n: " << n << "\n";
        cout << "min_element: " << *min_element(v.begin(), v.end()) << "\n";
        cout << "max_element: " << *max_element(v.begin(), v.end()) << "\n";
        const auto p = minmax_element(v.begin(), v.end());
        cout << "minmax_element: " << *p.first << ", " << *p.second << "\n";
        cout << "\n";
    }
}
D:\GitHub\STL\out\x64>cl /EHsc /nologo /W4 /std:c++latest /MT /O2 meow.cpp && meow
meow.cpp
n: 1073741823
min_element: 24
max_element: 26
minmax_element: 24, 26

n: 1073741840
min_element: 25
max_element: 25
minmax_element: 25, 25

The escape hatch restores correctness:

D:\GitHub\STL\out\x64>cl /EHsc /nologo /W4 /std:c++latest /MT /O2 /D_USE_STD_VECTOR_ALGORITHMS=0 meow.cpp && meow
meow.cpp
n: 1073741823
min_element: 24
max_element: 26
minmax_element: 24, 26

n: 1073741840
min_element: 24
max_element: 26
minmax_element: 24, 26

I found the root cause and am working on a fix. The code isn't ignoring data beyond 4 GB - it actually finds the right answers, but then has a 32-bit truncation mistake immediately before returning the result.

I verified that no other vectorized algorithms are affected, as they don't perform these advanced index computations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixedSomething works now, yay!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions