<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/114668>114668</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
LLVM cannot constant fold memchr with local buffer
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
philnik777
</td>
</tr>
</table>
<pre>
LLVM is currently unable to constant fold calls `memchr` when a local buffer is passed. I noticed this while looking into libc++'s `std::find` optimizations.
This is a simple example where Clang doesn't constant fold the function even though it should be able to do that trivially: ([Godbolt](https://godbolt.org/z/xs7sc4TYz))
```c++
auto test() {
char buffer[] = "Banane";
return __builtin_memchr(buffer, 'a', __builtin_strlen(buffer)) == nullptr;
}
```
I think the problem is that `__builtin_memchr` can escape the pointer, so the buffer isn't recognized as immutable, resulting in the constant folder failing.
I'm in no way an expert in compiler optimizations, but I think it would be possible to check whether the pointer actually escapes, and if not, mark the pointer as `noescape` to at least partially solve this problem.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJxkVE1v4zgM_TXyhZjAlr-Sgw_tBFkUmL0NFthTIctMzI0sGRKVtP31C9nJTNMBhCiWxMeP90gVAp0sYifqZ1HvMxV5dL6bRzKWzm3bZr0b3rsfP_75GyiAjt6jZfMO0areILAD7WxgZRmOzgyglTEBRJNPOOnRiyaH64gWFBinlYE-Ho_oE9asQsBhAy9gHZPGAXikANeRDIJx7kz2BGTZgaFeC_m8rHYBDzyI8kmUT0eyQ_LhZqaJPhSTs2Ej8r3In9bfnwmUAigINM0GAd_Usl9H9AjfjbInGBwGK2TLX7LhEeEYrU6wgBe0wKOLpxGIIYwumgF6hHslBgc8Kgb2dCFlzLson0DIraif_3JD7wyLei_kdmSeQ4pfHoQ8nNarjfMnIQ8fQh7eQht09fPfDyF3aa3ZNPm67qVYTlVkB4yBkxu5A9HeLkCPyt-qvXILotyDkPJZWWVRSCnK-1vwyNFbeH3tIxkm-3pjT25vCPI7CNkqIdv09_e7wN6g_fRut0RR7pMzG42Z2f_yI9r9l1w-E_WS-Lfnpeazd73BKfG2VFQ0-R-xNTloZQGDVjOuVo4sr8EGt5z8UttKrkftTpY-cAAVgKYpcuIuGXgMMaEnyS2mD0JAD0dFhuzpQVsvQrZTMrAOruodUjhvM3pOZ9pNMxn0j9pMvvrIcM-WGK53Hc0uBLp31Yj6nDTKI_rP2YHSHJO4bpkviMoOQMfUSOlrUv78aLI0jXWrRaocO1AMBlVgmJXnRa4QnLng2oY3Bm7pZkNXDrtypzLsirbM67puK5mNXVs02zxv6uJYb_NatlvsVbGTssrLYjvIMqNO5rIqilwWZV1XcoNb1dRllReVbnZlVYkqx0mR2RhzmVITZBRCxK4oqqbZZkb1aMIynqS0eIXlNqm33me-S0bf-ngKosoNBQ6_YZjY4Dq5tLLWfe3tVUZwJR4fZlMWvem-tCjxGPuNdpOQh-Tgtn2bvfsPNQt5WMIKQh5ucV86-X8AAAD__ySDvf8">