[SimplifyLibCalls] Fix memchr opt to use CreateLogicalAnd
authorJuneyoung Lee <aqjune@gmail.com>
Fri, 25 Jun 2021 08:56:10 +0000 (17:56 +0900)
committerJuneyoung Lee <aqjune@gmail.com>
Fri, 25 Jun 2021 20:59:35 +0000 (05:59 +0900)
commit160559344026824ee0b510741c7906c0e165f9a7
tree1f1f1a91849966d3b1336fd4357892cd99569e84
parent5ccb7424fab3bc8bf6cb2ced989cbd86ec8ccff6
[SimplifyLibCalls] Fix memchr opt to use CreateLogicalAnd

This fixes a bug at LibCallSimplifier::optimizeMemChr which does the following transformation:

```
// memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
// != 0
//   after bounds check.
```

As written above, a bounds check on C (whether it is less than integer bitwidth) is done before doing `1 << C` otherwise 1 << C will overflow.
If the bounds check is false, the result of (1 << C & ...) must not be used at all, otherwise the result of shift (which is poison) will contaminate the whole results.
A correct way to encode this is `select i1 (bounds check), (1 << C & ...), false`  because select does not allow the unused operand to contaminate the result.
However, this optimization was introducing `and (bounds check), (1 << C & ...)` which cannot do that.

The bug was found from compilation of this C++ code: https://reviews.llvm.org/rG2fd3037ac615#1007197

Reviewed By: nikic

Differential Revision: https://reviews.llvm.org/D104901
llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
llvm/test/Transforms/InstCombine/memchr.ll
llvm/test/Transforms/InstCombine/strchr-1.ll