Instcombine was transforming:
authorEvan Cheng <evan.cheng@apple.com>
Thu, 12 Jul 2012 01:45:35 +0000 (01:45 +0000)
committerEvan Cheng <evan.cheng@apple.com>
Thu, 12 Jul 2012 01:45:35 +0000 (01:45 +0000)
  %shr = lshr i64 %key, 3
  %0 = load i64* %val, align 8
  %sub = add i64 %0, -1
  %and = and i64 %sub, %shr
  ret i64 %and

to:
  %shr = lshr i64 %key, 3
  %0 = load i64* %val, align 8
  %sub = add i64 %0, 2305843009213693951
  %and = and i64 %sub, %shr
  ret i64 %and

The demanded bit optimization is actually a pessimization because add -1 would
be codegen'ed as a sub 1. Teach the demanded constant shrinking optimization
to check for negated constant to make sure it is actually reducing the width
of the constant.

rdar://11793464

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@160101 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
test/Transforms/InstCombine/2012-07-11-AddSubDemandedBits.ll [new file with mode: 0644]

index 125c74a89a119e458c2c9605ef25c33acc6091c8..0a622424368e8d3bf7fc0a5e9b3f19d259c557c3 100644 (file)
@@ -40,6 +40,13 @@ static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
 
   // This instruction is producing bits that are not demanded. Shrink the RHS.
   Demanded &= OpC->getValue();
+  if (I->getOpcode() == Instruction::Add) {
+    // However, if the instruction is an add then the constant may be negated
+    // when the opcode is changed to sub. Check if the transformation is really
+    // shrinking the constant.
+    if (Demanded.abs().getActiveBits() > OpC->getValue().abs().getActiveBits())
+      return false;
+  }
   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
   return true;
 }
diff --git a/test/Transforms/InstCombine/2012-07-11-AddSubDemandedBits.ll b/test/Transforms/InstCombine/2012-07-11-AddSubDemandedBits.ll
new file mode 100644 (file)
index 0000000..d62a886
--- /dev/null
@@ -0,0 +1,18 @@
+; RUN: opt < %s -instcombine -S | FileCheck %s
+
+; When shrinking demanded constant operand of an add instruction, keep in
+; mind the opcode can be changed to sub and the constant negated. Make sure
+; the shrinking the constant would actually reduce the width.
+; rdar://11793464
+
+define i64 @t(i64 %key, i64* %val) nounwind {
+entry:
+; CHECK: @t
+; CHECK-NOT: add i64 %0, 2305843009213693951
+; CHECK: add i64 %0, -1
+  %shr = lshr i64 %key, 3
+  %0 = load i64* %val, align 8
+  %sub = sub i64 %0, 1
+  %and = and i64 %sub, %shr
+  ret i64 %and
+}