LLVM API Documentation

InstCombineShifts.cpp
Go to the documentation of this file.
00001 //===- InstCombineShifts.cpp ----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitShl, visitLShr, and visitAShr functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 using namespace llvm;
00020 using namespace PatternMatch;
00021 
00022 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
00023   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
00024   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00025 
00026   // See if we can fold away this shift.
00027   if (SimplifyDemandedInstructionBits(I))
00028     return &I;
00029 
00030   // Try to fold constant and into select arguments.
00031   if (isa<Constant>(Op0))
00032     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
00033       if (Instruction *R = FoldOpIntoSelect(I, SI))
00034         return R;
00035 
00036   if (Constant *CUI = dyn_cast<Constant>(Op1))
00037     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
00038       return Res;
00039 
00040   // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
00041   // Because shifts by negative values (which could occur if A were negative)
00042   // are undefined.
00043   Value *A; const APInt *B;
00044   if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
00045     // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
00046     // demand the sign bit (and many others) here??
00047     Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
00048                                     Op1->getName());
00049     I.setOperand(1, Rem);
00050     return &I;
00051   }
00052 
00053   return 0;
00054 }
00055 
00056 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
00057 /// logically to the left or right by some number of bits.  This should return
00058 /// true if the expression can be computed for the same cost as the current
00059 /// expression tree.  This is used to eliminate extraneous shifting from things
00060 /// like:
00061 ///      %C = shl i128 %A, 64
00062 ///      %D = shl i128 %B, 96
00063 ///      %E = or i128 %C, %D
00064 ///      %F = lshr i128 %E, 64
00065 /// where the client will ask if E can be computed shifted right by 64-bits.  If
00066 /// this succeeds, the GetShiftedValue function will be called to produce the
00067 /// value.
00068 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
00069                                InstCombiner &IC) {
00070   // We can always evaluate constants shifted.
00071   if (isa<Constant>(V))
00072     return true;
00073 
00074   Instruction *I = dyn_cast<Instruction>(V);
00075   if (!I) return false;
00076 
00077   // If this is the opposite shift, we can directly reuse the input of the shift
00078   // if the needed bits are already zero in the input.  This allows us to reuse
00079   // the value which means that we don't care if the shift has multiple uses.
00080   //  TODO:  Handle opposite shift by exact value.
00081   ConstantInt *CI = 0;
00082   if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
00083       (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
00084     if (CI->getZExtValue() == NumBits) {
00085       // TODO: Check that the input bits are already zero with MaskedValueIsZero
00086 #if 0
00087       // If this is a truncate of a logical shr, we can truncate it to a smaller
00088       // lshr iff we know that the bits we would otherwise be shifting in are
00089       // already zeros.
00090       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
00091       uint32_t BitWidth = Ty->getScalarSizeInBits();
00092       if (MaskedValueIsZero(I->getOperand(0),
00093             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
00094           CI->getLimitedValue(BitWidth) < BitWidth) {
00095         return CanEvaluateTruncated(I->getOperand(0), Ty);
00096       }
00097 #endif
00098 
00099     }
00100   }
00101 
00102   // We can't mutate something that has multiple uses: doing so would
00103   // require duplicating the instruction in general, which isn't profitable.
00104   if (!I->hasOneUse()) return false;
00105 
00106   switch (I->getOpcode()) {
00107   default: return false;
00108   case Instruction::And:
00109   case Instruction::Or:
00110   case Instruction::Xor:
00111     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
00112     return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
00113            CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
00114 
00115   case Instruction::Shl: {
00116     // We can often fold the shift into shifts-by-a-constant.
00117     CI = dyn_cast<ConstantInt>(I->getOperand(1));
00118     if (CI == 0) return false;
00119 
00120     // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
00121     if (isLeftShift) return true;
00122 
00123     // We can always turn shl(c)+shr(c) -> and(c2).
00124     if (CI->getValue() == NumBits) return true;
00125 
00126     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
00127 
00128     // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
00129     // profitable unless we know the and'd out bits are already zero.
00130     if (CI->getZExtValue() > NumBits) {
00131       unsigned LowBits = TypeWidth - CI->getZExtValue();
00132       if (MaskedValueIsZero(I->getOperand(0),
00133                        APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
00134         return true;
00135     }
00136 
00137     return false;
00138   }
00139   case Instruction::LShr: {
00140     // We can often fold the shift into shifts-by-a-constant.
00141     CI = dyn_cast<ConstantInt>(I->getOperand(1));
00142     if (CI == 0) return false;
00143 
00144     // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
00145     if (!isLeftShift) return true;
00146 
00147     // We can always turn lshr(c)+shl(c) -> and(c2).
00148     if (CI->getValue() == NumBits) return true;
00149 
00150     unsigned TypeWidth = I->getType()->getScalarSizeInBits();
00151 
00152     // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
00153     // profitable unless we know the and'd out bits are already zero.
00154     if (CI->getValue().ult(TypeWidth) && CI->getZExtValue() > NumBits) {
00155       unsigned LowBits = CI->getZExtValue() - NumBits;
00156       if (MaskedValueIsZero(I->getOperand(0),
00157                           APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
00158         return true;
00159     }
00160 
00161     return false;
00162   }
00163   case Instruction::Select: {
00164     SelectInst *SI = cast<SelectInst>(I);
00165     return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
00166            CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
00167   }
00168   case Instruction::PHI: {
00169     // We can change a phi if we can change all operands.  Note that we never
00170     // get into trouble with cyclic PHIs here because we only consider
00171     // instructions with a single use.
00172     PHINode *PN = cast<PHINode>(I);
00173     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00174       if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
00175         return false;
00176     return true;
00177   }
00178   }
00179 }
00180 
00181 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
00182 /// this value inserts the new computation that produces the shifted value.
00183 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
00184                               InstCombiner &IC) {
00185   // We can always evaluate constants shifted.
00186   if (Constant *C = dyn_cast<Constant>(V)) {
00187     if (isLeftShift)
00188       V = IC.Builder->CreateShl(C, NumBits);
00189     else
00190       V = IC.Builder->CreateLShr(C, NumBits);
00191     // If we got a constantexpr back, try to simplify it with TD info.
00192     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00193       V = ConstantFoldConstantExpression(CE, IC.getDataLayout(),
00194                                          IC.getTargetLibraryInfo());
00195     return V;
00196   }
00197 
00198   Instruction *I = cast<Instruction>(V);
00199   IC.Worklist.Add(I);
00200 
00201   switch (I->getOpcode()) {
00202   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
00203   case Instruction::And:
00204   case Instruction::Or:
00205   case Instruction::Xor:
00206     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
00207     I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
00208     I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
00209     return I;
00210 
00211   case Instruction::Shl: {
00212     BinaryOperator *BO = cast<BinaryOperator>(I);
00213     unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
00214 
00215     // We only accept shifts-by-a-constant in CanEvaluateShifted.
00216     ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
00217 
00218     // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
00219     if (isLeftShift) {
00220       // If this is oversized composite shift, then unsigned shifts get 0.
00221       unsigned NewShAmt = NumBits+CI->getZExtValue();
00222       if (NewShAmt >= TypeWidth)
00223         return Constant::getNullValue(I->getType());
00224 
00225       BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
00226       BO->setHasNoUnsignedWrap(false);
00227       BO->setHasNoSignedWrap(false);
00228       return I;
00229     }
00230 
00231     // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
00232     // zeros.
00233     if (CI->getValue() == NumBits) {
00234       APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
00235       V = IC.Builder->CreateAnd(BO->getOperand(0),
00236                                 ConstantInt::get(BO->getContext(), Mask));
00237       if (Instruction *VI = dyn_cast<Instruction>(V)) {
00238         VI->moveBefore(BO);
00239         VI->takeName(BO);
00240       }
00241       return V;
00242     }
00243 
00244     // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
00245     // the and won't be needed.
00246     assert(CI->getZExtValue() > NumBits);
00247     BO->setOperand(1, ConstantInt::get(BO->getType(),
00248                                        CI->getZExtValue() - NumBits));
00249     BO->setHasNoUnsignedWrap(false);
00250     BO->setHasNoSignedWrap(false);
00251     return BO;
00252   }
00253   case Instruction::LShr: {
00254     BinaryOperator *BO = cast<BinaryOperator>(I);
00255     unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
00256     // We only accept shifts-by-a-constant in CanEvaluateShifted.
00257     ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
00258 
00259     // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
00260     if (!isLeftShift) {
00261       // If this is oversized composite shift, then unsigned shifts get 0.
00262       unsigned NewShAmt = NumBits+CI->getZExtValue();
00263       if (NewShAmt >= TypeWidth)
00264         return Constant::getNullValue(BO->getType());
00265 
00266       BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
00267       BO->setIsExact(false);
00268       return I;
00269     }
00270 
00271     // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
00272     // zeros.
00273     if (CI->getValue() == NumBits) {
00274       APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
00275       V = IC.Builder->CreateAnd(I->getOperand(0),
00276                                 ConstantInt::get(BO->getContext(), Mask));
00277       if (Instruction *VI = dyn_cast<Instruction>(V)) {
00278         VI->moveBefore(I);
00279         VI->takeName(I);
00280       }
00281       return V;
00282     }
00283 
00284     // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
00285     // the and won't be needed.
00286     assert(CI->getZExtValue() > NumBits);
00287     BO->setOperand(1, ConstantInt::get(BO->getType(),
00288                                        CI->getZExtValue() - NumBits));
00289     BO->setIsExact(false);
00290     return BO;
00291   }
00292 
00293   case Instruction::Select:
00294     I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
00295     I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
00296     return I;
00297   case Instruction::PHI: {
00298     // We can change a phi if we can change all operands.  Note that we never
00299     // get into trouble with cyclic PHIs here because we only consider
00300     // instructions with a single use.
00301     PHINode *PN = cast<PHINode>(I);
00302     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00303       PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
00304                                               NumBits, isLeftShift, IC));
00305     return PN;
00306   }
00307   }
00308 }
00309 
00310 
00311 
00312 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
00313                                                BinaryOperator &I) {
00314   bool isLeftShift = I.getOpcode() == Instruction::Shl;
00315 
00316   ConstantInt *COp1 = nullptr;
00317   if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
00318     COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
00319   else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
00320     COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
00321   else
00322     COp1 = dyn_cast<ConstantInt>(Op1);
00323 
00324   if (!COp1)
00325     return nullptr;
00326 
00327   // See if we can propagate this shift into the input, this covers the trivial
00328   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
00329   if (I.getOpcode() != Instruction::AShr &&
00330       CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this)) {
00331     DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
00332               " to eliminate shift:\n  IN: " << *Op0 << "\n  SH: " << I <<"\n");
00333 
00334     return ReplaceInstUsesWith(I,
00335                  GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this));
00336   }
00337 
00338 
00339   // See if we can simplify any instructions used by the instruction whose sole
00340   // purpose is to compute bits we don't care about.
00341   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
00342 
00343   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
00344   // a signed shift.
00345   //
00346   if (COp1->uge(TypeBits)) {
00347     if (I.getOpcode() != Instruction::AShr)
00348       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
00349     // ashr i32 X, 32 --> ashr i32 X, 31
00350     I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
00351     return &I;
00352   }
00353 
00354   // ((X*C1) << C2) == (X * (C1 << C2))
00355   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
00356     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
00357       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
00358         return BinaryOperator::CreateMul(BO->getOperand(0),
00359                                         ConstantExpr::getShl(BOOp, Op1));
00360 
00361   // Try to fold constant and into select arguments.
00362   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00363     if (Instruction *R = FoldOpIntoSelect(I, SI))
00364       return R;
00365   if (isa<PHINode>(Op0))
00366     if (Instruction *NV = FoldOpIntoPhi(I))
00367       return NV;
00368 
00369   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
00370   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
00371     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
00372     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
00373     // place.  Don't try to do this transformation in this case.  Also, we
00374     // require that the input operand is a shift-by-constant so that we have
00375     // confidence that the shifts will get folded together.  We could do this
00376     // xform in more cases, but it is unlikely to be profitable.
00377     if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
00378         isa<ConstantInt>(TrOp->getOperand(1))) {
00379       // Okay, we'll do this xform.  Make the shift of shift.
00380       Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
00381       // (shift2 (shift1 & 0x00FF), c2)
00382       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
00383 
00384       // For logical shifts, the truncation has the effect of making the high
00385       // part of the register be zeros.  Emulate this by inserting an AND to
00386       // clear the top bits as needed.  This 'and' will usually be zapped by
00387       // other xforms later if dead.
00388       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
00389       unsigned DstSize = TI->getType()->getScalarSizeInBits();
00390       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
00391 
00392       // The mask we constructed says what the trunc would do if occurring
00393       // between the shifts.  We want to know the effect *after* the second
00394       // shift.  We know that it is a logical shift by a constant, so adjust the
00395       // mask as appropriate.
00396       if (I.getOpcode() == Instruction::Shl)
00397         MaskV <<= COp1->getZExtValue();
00398       else {
00399         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
00400         MaskV = MaskV.lshr(COp1->getZExtValue());
00401       }
00402 
00403       // shift1 & 0x00FF
00404       Value *And = Builder->CreateAnd(NSh,
00405                                       ConstantInt::get(I.getContext(), MaskV),
00406                                       TI->getName());
00407 
00408       // Return the value truncated to the interesting size.
00409       return new TruncInst(And, I.getType());
00410     }
00411   }
00412 
00413   if (Op0->hasOneUse()) {
00414     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
00415       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
00416       Value *V1, *V2;
00417       ConstantInt *CC;
00418       switch (Op0BO->getOpcode()) {
00419       default: break;
00420       case Instruction::Add:
00421       case Instruction::And:
00422       case Instruction::Or:
00423       case Instruction::Xor: {
00424         // These operators commute.
00425         // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
00426         if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
00427             match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
00428                   m_Specific(Op1)))) {
00429           Value *YS =         // (Y << C)
00430             Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
00431           // (X + (Y << C))
00432           Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
00433                                           Op0BO->getOperand(1)->getName());
00434           uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
00435 
00436           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
00437           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
00438           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
00439             Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
00440           return BinaryOperator::CreateAnd(X, Mask);
00441         }
00442 
00443         // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
00444         Value *Op0BOOp1 = Op0BO->getOperand(1);
00445         if (isLeftShift && Op0BOOp1->hasOneUse() &&
00446             match(Op0BOOp1,
00447                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
00448                         m_ConstantInt(CC)))) {
00449           Value *YS =   // (Y << C)
00450             Builder->CreateShl(Op0BO->getOperand(0), Op1,
00451                                          Op0BO->getName());
00452           // X & (CC << C)
00453           Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
00454                                          V1->getName()+".mask");
00455           return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
00456         }
00457       }
00458 
00459       // FALL THROUGH.
00460       case Instruction::Sub: {
00461         // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
00462         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
00463             match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
00464                   m_Specific(Op1)))) {
00465           Value *YS =  // (Y << C)
00466             Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
00467           // (X + (Y << C))
00468           Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
00469                                           Op0BO->getOperand(0)->getName());
00470           uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
00471 
00472           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
00473           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
00474           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
00475             Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
00476           return BinaryOperator::CreateAnd(X, Mask);
00477         }
00478 
00479         // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
00480         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
00481             match(Op0BO->getOperand(0),
00482                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
00483                         m_ConstantInt(CC))) && V2 == Op1) {
00484           Value *YS = // (Y << C)
00485             Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
00486           // X & (CC << C)
00487           Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
00488                                          V1->getName()+".mask");
00489 
00490           return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
00491         }
00492 
00493         break;
00494       }
00495       }
00496 
00497 
00498       // If the operand is an bitwise operator with a constant RHS, and the
00499       // shift is the only use, we can pull it out of the shift.
00500       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
00501         bool isValid = true;     // Valid only for And, Or, Xor
00502         bool highBitSet = false; // Transform if high bit of constant set?
00503 
00504         switch (Op0BO->getOpcode()) {
00505         default: isValid = false; break;   // Do not perform transform!
00506         case Instruction::Add:
00507           isValid = isLeftShift;
00508           break;
00509         case Instruction::Or:
00510         case Instruction::Xor:
00511           highBitSet = false;
00512           break;
00513         case Instruction::And:
00514           highBitSet = true;
00515           break;
00516         }
00517 
00518         // If this is a signed shift right, and the high bit is modified
00519         // by the logical operation, do not perform the transformation.
00520         // The highBitSet boolean indicates the value of the high bit of
00521         // the constant which would cause it to be modified for this
00522         // operation.
00523         //
00524         if (isValid && I.getOpcode() == Instruction::AShr)
00525           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
00526 
00527         if (isValid) {
00528           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
00529 
00530           Value *NewShift =
00531             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
00532           NewShift->takeName(Op0BO);
00533 
00534           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
00535                                         NewRHS);
00536         }
00537       }
00538     }
00539   }
00540 
00541   // Find out if this is a shift of a shift by a constant.
00542   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
00543   if (ShiftOp && !ShiftOp->isShift())
00544     ShiftOp = 0;
00545 
00546   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
00547 
00548     // This is a constant shift of a constant shift. Be careful about hiding
00549     // shl instructions behind bit masks. They are used to represent multiplies
00550     // by a constant, and it is important that simple arithmetic expressions
00551     // are still recognizable by scalar evolution.
00552     //
00553     // The transforms applied to shl are very similar to the transforms applied
00554     // to mul by constant. We can be more aggressive about optimizing right
00555     // shifts.
00556     //
00557     // Combinations of right and left shifts will still be optimized in
00558     // DAGCombine where scalar evolution no longer applies.
00559 
00560     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
00561     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
00562     uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
00563     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
00564     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
00565     Value *X = ShiftOp->getOperand(0);
00566 
00567     IntegerType *Ty = cast<IntegerType>(I.getType());
00568 
00569     // Check for (X << c1) << c2  and  (X >> c1) >> c2
00570     if (I.getOpcode() == ShiftOp->getOpcode()) {
00571       uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
00572       // If this is oversized composite shift, then unsigned shifts get 0, ashr
00573       // saturates.
00574       if (AmtSum >= TypeBits) {
00575         if (I.getOpcode() != Instruction::AShr)
00576           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
00577         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
00578       }
00579 
00580       return BinaryOperator::Create(I.getOpcode(), X,
00581                                     ConstantInt::get(Ty, AmtSum));
00582     }
00583 
00584     if (ShiftAmt1 == ShiftAmt2) {
00585       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
00586       if (I.getOpcode() == Instruction::LShr &&
00587           ShiftOp->getOpcode() == Instruction::Shl) {
00588         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
00589         return BinaryOperator::CreateAnd(X,
00590                                         ConstantInt::get(I.getContext(), Mask));
00591       }
00592     } else if (ShiftAmt1 < ShiftAmt2) {
00593       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
00594 
00595       // (X >>?,exact C1) << C2 --> X << (C2-C1)
00596       // The inexact version is deferred to DAGCombine so we don't hide shl
00597       // behind a bit mask.
00598       if (I.getOpcode() == Instruction::Shl &&
00599           ShiftOp->getOpcode() != Instruction::Shl &&
00600           ShiftOp->isExact()) {
00601         assert(ShiftOp->getOpcode() == Instruction::LShr ||
00602                ShiftOp->getOpcode() == Instruction::AShr);
00603         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00604         BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
00605                                                         X, ShiftDiffCst);
00606         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
00607         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
00608         return NewShl;
00609       }
00610 
00611       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
00612       if (I.getOpcode() == Instruction::LShr &&
00613           ShiftOp->getOpcode() == Instruction::Shl) {
00614         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00615         // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
00616         if (ShiftOp->hasNoUnsignedWrap()) {
00617           BinaryOperator *NewLShr = BinaryOperator::Create(Instruction::LShr,
00618                                                            X, ShiftDiffCst);
00619           NewLShr->setIsExact(I.isExact());
00620           return NewLShr;
00621         }
00622         Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
00623 
00624         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
00625         return BinaryOperator::CreateAnd(Shift,
00626                                          ConstantInt::get(I.getContext(),Mask));
00627       }
00628 
00629       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
00630       // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
00631       if (I.getOpcode() == Instruction::AShr &&
00632           ShiftOp->getOpcode() == Instruction::Shl) {
00633         if (ShiftOp->hasNoSignedWrap()) {
00634           // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
00635           ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00636           BinaryOperator *NewAShr = BinaryOperator::Create(Instruction::AShr,
00637                                                            X, ShiftDiffCst);
00638           NewAShr->setIsExact(I.isExact());
00639           return NewAShr;
00640         }
00641       }
00642     } else {
00643       assert(ShiftAmt2 < ShiftAmt1);
00644       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
00645 
00646       // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
00647       // The inexact version is deferred to DAGCombine so we don't hide shl
00648       // behind a bit mask.
00649       if (I.getOpcode() == Instruction::Shl &&
00650           ShiftOp->getOpcode() != Instruction::Shl &&
00651           ShiftOp->isExact()) {
00652         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00653         BinaryOperator *NewShr = BinaryOperator::Create(ShiftOp->getOpcode(),
00654                                                         X, ShiftDiffCst);
00655         NewShr->setIsExact(true);
00656         return NewShr;
00657       }
00658 
00659       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
00660       if (I.getOpcode() == Instruction::LShr &&
00661           ShiftOp->getOpcode() == Instruction::Shl) {
00662         ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00663         if (ShiftOp->hasNoUnsignedWrap()) {
00664           // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
00665           BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
00666                                                           X, ShiftDiffCst);
00667           NewShl->setHasNoUnsignedWrap(true);
00668           return NewShl;
00669         }
00670         Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
00671 
00672         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
00673         return BinaryOperator::CreateAnd(Shift,
00674                                          ConstantInt::get(I.getContext(),Mask));
00675       }
00676 
00677       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
00678       // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
00679       if (I.getOpcode() == Instruction::AShr &&
00680           ShiftOp->getOpcode() == Instruction::Shl) {
00681         if (ShiftOp->hasNoSignedWrap()) {
00682           // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
00683           ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
00684           BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
00685                                                           X, ShiftDiffCst);
00686           NewShl->setHasNoSignedWrap(true);
00687           return NewShl;
00688         }
00689       }
00690     }
00691   }
00692   return 0;
00693 }
00694 
00695 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
00696   if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
00697                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
00698                                  DL))
00699     return ReplaceInstUsesWith(I, V);
00700 
00701   if (Instruction *V = commonShiftTransforms(I))
00702     return V;
00703 
00704   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
00705     unsigned ShAmt = Op1C->getZExtValue();
00706 
00707     // If the shifted-out value is known-zero, then this is a NUW shift.
00708     if (!I.hasNoUnsignedWrap() &&
00709         MaskedValueIsZero(I.getOperand(0),
00710                           APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt))) {
00711           I.setHasNoUnsignedWrap();
00712           return &I;
00713         }
00714 
00715     // If the shifted out value is all signbits, this is a NSW shift.
00716     if (!I.hasNoSignedWrap() &&
00717         ComputeNumSignBits(I.getOperand(0)) > ShAmt) {
00718       I.setHasNoSignedWrap();
00719       return &I;
00720     }
00721   }
00722 
00723   // (C1 << A) << C2 -> (C1 << C2) << A
00724   Constant *C1, *C2;
00725   Value *A;
00726   if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
00727       match(I.getOperand(1), m_Constant(C2)))
00728     return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
00729 
00730   return 0;
00731 }
00732 
00733 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
00734   if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
00735                                   I.isExact(), DL))
00736     return ReplaceInstUsesWith(I, V);
00737 
00738   if (Instruction *R = commonShiftTransforms(I))
00739     return R;
00740 
00741   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00742 
00743   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
00744     unsigned ShAmt = Op1C->getZExtValue();
00745 
00746     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
00747       unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
00748       // ctlz.i32(x)>>5  --> zext(x == 0)
00749       // cttz.i32(x)>>5  --> zext(x == 0)
00750       // ctpop.i32(x)>>5 --> zext(x == -1)
00751       if ((II->getIntrinsicID() == Intrinsic::ctlz ||
00752            II->getIntrinsicID() == Intrinsic::cttz ||
00753            II->getIntrinsicID() == Intrinsic::ctpop) &&
00754           isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
00755         bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
00756         Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
00757         Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
00758         return new ZExtInst(Cmp, II->getType());
00759       }
00760     }
00761 
00762     // If the shifted-out value is known-zero, then this is an exact shift.
00763     if (!I.isExact() &&
00764         MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
00765       I.setIsExact();
00766       return &I;
00767     }
00768   }
00769 
00770   return 0;
00771 }
00772 
00773 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
00774   if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
00775                                   I.isExact(), DL))
00776     return ReplaceInstUsesWith(I, V);
00777 
00778   if (Instruction *R = commonShiftTransforms(I))
00779     return R;
00780 
00781   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00782 
00783   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
00784     unsigned ShAmt = Op1C->getZExtValue();
00785 
00786     // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
00787     // have a sign-extend idiom.
00788     Value *X;
00789     if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
00790       // If the left shift is just shifting out partial signbits, delete the
00791       // extension.
00792       if (cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
00793         return ReplaceInstUsesWith(I, X);
00794 
00795       // If the input is an extension from the shifted amount value, e.g.
00796       //   %x = zext i8 %A to i32
00797       //   %y = shl i32 %x, 24
00798       //   %z = ashr %y, 24
00799       // then turn this into "z = sext i8 A to i32".
00800       if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
00801         uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
00802         uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
00803         if (Op1C->getZExtValue() == DestBits-SrcBits)
00804           return new SExtInst(ZI->getOperand(0), ZI->getType());
00805       }
00806     }
00807 
00808     // If the shifted-out value is known-zero, then this is an exact shift.
00809     if (!I.isExact() &&
00810         MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
00811       I.setIsExact();
00812       return &I;
00813     }
00814   }
00815 
00816   // See if we can turn a signed shr into an unsigned shr.
00817   if (MaskedValueIsZero(Op0,
00818                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
00819     return BinaryOperator::CreateLShr(Op0, Op1);
00820 
00821   // Arithmetic shifting an all-sign-bit value is a no-op.
00822   unsigned NumSignBits = ComputeNumSignBits(Op0);
00823   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
00824     return ReplaceInstUsesWith(I, Op0);
00825 
00826   return 0;
00827 }