InstCombine: Also turn selects fed by an and into arithmetic when the types don't match.

Inserting a zext or trunc is sufficient. This pattern is somewhat common in
LLVM's pointer mangling code.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@185270 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Benjamin Kramer 2013-06-29 21:17:04 +00:00
parent 97daabf318
commit edac9151fd
2 changed files with 45 additions and 4 deletions

View File

@ -662,7 +662,7 @@ static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
ConstantInt *FalseVal,
InstCombiner::BuilderTy *Builder) {
const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
if (!IC || !IC->isEquality())
if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
return 0;
if (!match(IC->getOperand(1), m_Zero()))
@ -670,8 +670,7 @@ static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
ConstantInt *AndRHS;
Value *LHS = IC->getOperand(0);
if (LHS->getType() != SI.getType() ||
!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
return 0;
// If both select arms are non-zero see if we have a select of the form
@ -705,7 +704,13 @@ static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
unsigned ValZeros = ValC->getValue().logBase2();
unsigned AndZeros = AndRHS->getValue().logBase2();
Value *V = LHS;
// If types don't match we can still convert the select by introducing a zext
// or a trunc of the 'and'. The trunc case requires that all of the truncated
// bits are zero, we can figure that out by looking at the 'and' mask.
if (AndZeros >= ValC->getBitWidth())
return 0;
Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
if (ValZeros > AndZeros)
V = Builder->CreateShl(V, ValZeros - AndZeros);
else if (ValZeros < AndZeros)

View File

@ -985,3 +985,39 @@ define i32 @select_icmp_ne_0_and_8_or_1073741824(i8 %x, i32 %y) {
%select = select i1 %cmp, i32 %y, i32 %or
ret i32 %select
}
define i32 @test65(i64 %x) {
%1 = and i64 %x, 16
%2 = icmp ne i64 %1, 0
%3 = select i1 %2, i32 40, i32 42
ret i32 %3
; CHECK: @test65
; CHECK: and i64 %x, 16
; CHECK: trunc i64 %1 to i32
; CHECK: lshr exact i32 %2, 3
; CHECK: xor i32 %3, 42
}
define i32 @test66(i64 %x) {
%1 = and i64 %x, 4294967296
%2 = icmp ne i64 %1, 0
%3 = select i1 %2, i32 40, i32 42
ret i32 %3
; CHECK: @test66
; CHECK: select
}
define i32 @test67(i16 %x) {
%1 = and i16 %x, 4
%2 = icmp ne i16 %1, 0
%3 = select i1 %2, i32 40, i32 42
ret i32 %3
; CHECK: @test67
; CHECK: and i16 %x, 4
; CHECK: zext i16 %1 to i32
; CHECK: lshr exact i32 %2, 1
; CHECK: xor i32 %3, 42
}