Issue 157704
Summary clang-20 regression: Incorrect code generated for a custom iterator (leading to wrong results and crashes)
Labels new issue
Assignees
Reporter flode
    While upgrading from Clang 19 to Clang 21.1, we noticed incorrect behavior in pdqsort with our custom iterator.

The sort now produces invalid values, and with this minimized repro, it crashes in clang-20, clang-21 and trunk, it works in clang-19:
https://godbolt.org/z/GTo1P86ez
It succeeds with `-O0`, but starts crashing with `-O1`.

The relevant code parts are this part of the insertion sort:
```cpp
for (;(todo > begin) && comp(todo, prev(todo)); --todo) {
    std::swap_ranges(todo.data_, todo.data_ + todo.elementSize_, (todo-1).data_);
}
```
The `prev(todo)` seems to misbehave and modify the `todo` iterator, but that shouldn't happen as it's passed by value:
```cpp
template<class Iter>
Iter prev(Iter it) {
    it += -1;
 return it;
}
```

Some equivalent modifications to the `operator+=` also prevent the crash, seems some different code is generated then:
```cpp
RuntimeSizedElementIterator& RuntimeSizedElementIterator::operator+=(ptrdiff_t offset) {
   data_ += elementSize_ * offset;
   // TODO these work:
   //data_ += ptrdiff_t(elementSize_) * offset;
   //data_ -= -elementSize_ * offset;
 return *this;
}
```


The full code where the insertion sort produced wrong results is here: https://godbolt.org/z/ThYEna541
Switching to Clang-19 outputs the expected values.


_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to