[InstCombine] Don't transform code if DoTransform is false
authorGuozhi Wei <carrot@google.com>
Sat, 19 Jun 2021 01:01:34 +0000 (18:01 -0700)
committerGuozhi Wei <carrot@google.com>
Sat, 19 Jun 2021 01:01:34 +0000 (18:01 -0700)
In patch https://reviews.llvm.org/D72396, it doesn't check DoTransform before transforming the code, and generates wrong result for the attached test case.

Differential Revision: https://reviews.llvm.org/D104567

llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
llvm/test/Transforms/InstCombine/zext.ll

index 433d90a..5b99f4d 100644 (file)
@@ -953,6 +953,9 @@ Instruction *InstCombinerImpl::visitTrunc(TruncInst &Trunc) {
   return nullptr;
 }
 
+/// Transform (zext icmp) to bitwise / integer operations in order to
+/// eliminate it. If DoTransform is false, just test whether the given
+/// (zext icmp) can be transformed.
 Instruction *InstCombinerImpl::transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext,
                                                  bool DoTransform) {
   // If we are just checking for a icmp eq of a single bit and zext'ing it
@@ -1039,6 +1042,9 @@ Instruction *InstCombinerImpl::transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext,
     if (Cmp->hasOneUse() && match(Cmp->getOperand(1), m_ZeroInt()) &&
         match(Cmp->getOperand(0),
               m_OneUse(m_c_And(m_Shl(m_One(), m_Value(ShAmt)), m_Value(X))))) {
+      if (!DoTransform)
+        return Cmp;
+
       if (Cmp->getPredicate() == ICmpInst::ICMP_EQ)
         X = Builder.CreateNot(X);
       Value *Lshr = Builder.CreateLShr(X, ShAmt);
index 9351f5c..77ad2a4 100644 (file)
@@ -409,3 +409,29 @@ define i32 @masked_bit_wrong_pred(i32 %x, i32 %y) {
   %r = zext i1 %cmp to i32
   ret i32 %r
 }
+
+; Assert that zext(or(masked_bit_test, icmp)) can be correctly transformed to
+; or(shifted_masked_bit, zext(icmp))
+
+define void @zext_or_masked_bit_test(i32 %a, i32 %b, i32* %p) {
+; CHECK-LABEL: @zext_or_masked_bit_test
+; CHECK-NEXT:    [[LD:%.*]] = load i32, i32* %p, align 4
+; CHECK-NEXT:    [[CMP:%.*]] = icmp eq i32 [[LD]], %b
+; CHECK-NEXT:    [[SHR:%.*]] = lshr i32 %a, %b
+; CHECK-NEXT:    [[AND:%.*]] = and i32 [[SHR]], 1
+; CHECK-NEXT:    [[EXT:%.*]] = zext i1 [[CMP]] to i32
+; CHECK-NEXT:    [[OR:%.*]] = or i32 [[AND]], [[EXT]]
+; CHECK-NEXT:    store i32 [[OR]], i32* %p, align 4
+; CHECK-NEXT:    ret void
+;
+  %ld = load i32, i32* %p, align 4
+  %shl = shl i32 1, %b
+  %and = and i32 %shl, %a
+  %tobool = icmp ne i32 %and, 0
+  %cmp = icmp eq i32 %ld, %b
+  %or = or i1 %tobool, %cmp
+  %conv = zext i1 %or to i32
+  store i32 %conv, i32* %p, align 4
+  ret void
+}
+