Turn sdiv into udiv if both operands have a clear sign bit. This occurs
authorChris Lattner <sabre@nondot.org>
Sat, 5 Nov 2005 07:40:31 +0000 (07:40 +0000)
committerChris Lattner <sabre@nondot.org>
Sat, 5 Nov 2005 07:40:31 +0000 (07:40 +0000)
a few times in crafty:

OLD:    %tmp.36 = div int %tmp.35, 8            ; <int> [#uses=1]
NEW:    %tmp.36 = div uint %tmp.35, 8           ; <uint> [#uses=0]
OLD:    %tmp.19 = div int %tmp.18, 8            ; <int> [#uses=1]
NEW:    %tmp.19 = div uint %tmp.18, 8           ; <uint> [#uses=0]
OLD:    %tmp.117 = div int %tmp.116, 8          ; <int> [#uses=1]
NEW:    %tmp.117 = div uint %tmp.116, 8         ; <uint> [#uses=0]
OLD:    %tmp.92 = div int %tmp.91, 8            ; <int> [#uses=1]
NEW:    %tmp.92 = div uint %tmp.91, 8           ; <uint> [#uses=0]

Which all turn into shrs.

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

lib/Transforms/Scalar/InstructionCombining.cpp

index 4a764c996d7d54a5d64a2b28cf771ffbb8bea174..1164fb2e03e0192641ba674d0aca878a4067473b 100644 (file)
@@ -1240,6 +1240,25 @@ Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
     if (LHS->equalsInt(0))
       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
 
+  if (I.getType()->isSigned()) {
+    // If the top bits of both operands are zero (i.e. we can prove they are
+    // unsigned inputs), turn this into a udiv.
+    ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
+    if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
+      const Type *NTy = Op0->getType()->getUnsignedVersion();
+      Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
+      InsertNewInstBefore(LHS, I);
+      Value *RHS;
+      if (Constant *R = dyn_cast<Constant>(Op1))
+        RHS = ConstantExpr::getCast(R, NTy);
+      else
+        RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
+      Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
+      InsertNewInstBefore(Div, I);
+      return new CastInst(Div, I.getType());
+    }      
+  }
+  
   return 0;
 }