<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/107844>107844</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Clang C++ optimiser generates incorrect code
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
filiplukasik
</td>
</tr>
</table>
<pre>
`
#include <optional>
#include <iostream>
inline std::optional<int> fail() {
std::terminate();
}
std::optional<int> test(int index) {
if (0 == index) {
return std::optional<int>{};
} else {
return fail();
}
}
int main(int argc, const char * argv[]) {
// This should evaluate to an empty optional
auto color = test(0);
if (color.has_value()) {
// With -Os set, we hit this branch on armv8
std::cout << color.value() << std::endl;
} else {
// Without optimisations we hit this branch
std::cout << "Color Empty" << std::endl;
}
return 0;
}
`
The code above results in "bad_optional_access" exception being thrown when compiled for armv8 in clang 18.1.0 and -Os (it also seems to crash in clang 17 and 16 according to compiler explorer + corresponding Apple clang forks - tested with Xcode 15.3 and Xcode 16 betas)
https://godbolt.org/z/r1qbfb4nE
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVE1zozgQ_TXtS1dcIGyDDxwcO77uZap2b6lGNEYbIbGScDL767ckf27GM5McSBn1637v9UPkvToY5hqWz7DczWgKvXV1p7Qa9fRGXr3NGtt-r2GVQbaDbAOiUEbqqWWEYmvHoKwhDcXLo2NlfXBMw-04PZXRyjD60EKxgWJz67JVJkDxgh0pDaICsUYon08oRLxBArtBGQp8qoLiXATl7n7SL0YE9gFEpUxAZVr--GGW6hBElSEUOyh2PymKf47D5Mwv5EREubtyjBgod8ja80-73Rz4jHsoNMoYSJmzInIHCWKL0hofUPbkEMQmvj6eNv2DEBB7EHv81iuPvreTbpGPpCcKjMEiGeRhDN_xKu6KpClYlFZbF626-Jp9Zp6GfDI3oeY9-dc46rLLRx6f6f2pQo9Pf3j0HKK-d8ZeBQyRdePI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