<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/56985>56985</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
-O2 and -O3 can create infinite loop
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Sainan
</td>
</tr>
</table>
<pre>
The following code can be used to reproduce this issue:
```C++
#include <iostream>
#include <vector>
template <typename K, typename V>
class RangeMap
{
private:
struct Entry
{
K lower;
K upper;
V data;
};
std::vector<Entry> data;
public:
V& emplace(K begin, K end, V val)
{
return data.emplace_back(Entry{ std::move(begin), std::move(end), std::move(val) }).data;
}
[[nodiscard]] V* find(const K& k)
{
auto first = data.begin();
auto last = data.end();
while (true)
{
auto size = std::distance(first, last);
auto pivot = first + (size / 2);
if (pivot->lower <= k && k <= pivot->upper)
{
return &pivot->data;
}
if (size == 1)
{
return nullptr;
}
if (pivot->lower < k)
{
first = pivot;
}
else
{
last = pivot;
}
}
}
};
int main()
{
RangeMap<int, std::string> rm;
rm.emplace(1, 69, "Nice");
rm.emplace(70, 420, "Epic");
std::cout << *rm.find(0);
}
```
I know it's quite a handful, but I need the optimiser to be uncertain about the runtime behaviour.
What I assume the optimiser does in this case is: It sees that the return value of find is derefenced, implies that to mean the result is not nullptr, then removes the `return nullptr;` path from this loop, thus making it infinite.
I know this code relies on a hardware exception being thrown, but I don't consider that to be UB, at least not when targeting x64.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyVVtuOozgQ_RryYnVETIDwwEOn0yO1Wrsj7aX3ceVAEbxtbMaYZHq_fqsMIdcZ9UpWgu26nCofV3lryo_8jxpYZZQyB6l3rDAlsEJotgXWd1AyZ5iF1pqyL4C5WnZMdl0PQfQYhJsgPP4m4TCeAr6mMazySOpC9WgyiJ6k6ZwF0QTR873tPRTO2NOm_3XQtEo4L-A-WtCiAfY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