[PATCH] D12210: [InstCombine] Transform A & (L - 1) u< L --> L != 0

Sanjoy Das via llvm-commits llvm-commits at lists.llvm.org
Thu Aug 20 13:29:21 PDT 2015


sanjoy created this revision.
sanjoy added reviewers: majnemer, reames.
sanjoy added a subscriber: llvm-commits.

This transform is never a pessimization at the IR level (since it
replaces an `icmp` with another), and has potentiall payoffs:

 1. It may make the `icmp` fold away or become loop invariant.
 2. It may make the `A & (L - 1)` computation dead.

This shows up in Java, in range checks generated by array accesses of
the form `a[i & (a.length - 1)]`.

http://reviews.llvm.org/D12210

Files:
  lib/Transforms/InstCombine/InstCombineCompares.cpp
  test/Transforms/InstCombine/ult-and-bitwise-and.ll

Index: test/Transforms/InstCombine/ult-and-bitwise-and.ll
===================================================================
--- /dev/null
+++ test/Transforms/InstCombine/ult-and-bitwise-and.ll
@@ -0,0 +1,11 @@
+; RUN: opt -S -instcombine < %s | FileCheck %s
+
+define i1 @f(i32 %val, i32 %lim) {
+; CHECK: @f(
+  %lim.sub = add i32 %lim, -1
+  %val.and = and i32 %val, %lim.sub
+  %r = icmp ult i32 %val.and, %lim
+; CHECK: [[RESULT:%[a-z0-9]+]] = icmp ne i32 %lim, 0
+; ret i1 [[RESULT]]
+  ret i1 %r
+}
Index: lib/Transforms/InstCombine/InstCombineCompares.cpp
===================================================================
--- lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -3490,6 +3490,21 @@
       }
       }
     }
+
+    if (BO0) {
+      // Transform  A & (L - 1) `ult` L --> L != 0
+      Value *L;
+      auto LSubOne = m_CombineOr(m_Sub(m_Value(L), m_SpecificInt(1)),
+                                 m_Add(m_Value(L), m_AllOnes()));
+      auto BitwiseAnd =
+        m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
+
+      if (match(BO0, BitwiseAnd) &&
+          I.getPredicate() == ICmpInst::ICMP_ULT) {
+        auto *Zero = ConstantInt::getSigned(BO0->getType(), 0);
+        return new ICmpInst(ICmpInst::ICMP_NE, L, Zero);
+      }
+    }
   }
 
   { Value *A, *B;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D12210.32730.patch
Type: text/x-patch
Size: 1374 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20150820/95798fd6/attachment.bin>


More information about the llvm-commits mailing list