LLVM API Documentation

InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
00001 //===- InstCombineSimplifyDemanded.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 contains logic for simplifying instructions based on information
00011 // about how they are used.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 
00016 #include "InstCombine.h"
00017 #include "llvm/IR/DataLayout.h"
00018 #include "llvm/IR/IntrinsicInst.h"
00019 #include "llvm/IR/PatternMatch.h"
00020 
00021 using namespace llvm;
00022 using namespace llvm::PatternMatch;
00023 
00024 /// ShrinkDemandedConstant - Check to see if the specified operand of the
00025 /// specified instruction is a constant integer.  If so, check to see if there
00026 /// are any bits set in the constant that are not demanded.  If so, shrink the
00027 /// constant and return true.
00028 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
00029                                    APInt Demanded) {
00030   assert(I && "No instruction?");
00031   assert(OpNo < I->getNumOperands() && "Operand index too large");
00032 
00033   // If the operand is not a constant integer, nothing to do.
00034   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
00035   if (!OpC) return false;
00036 
00037   // If there are no bits set that aren't demanded, nothing to do.
00038   Demanded = Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
00039   if ((~Demanded & OpC->getValue()) == 0)
00040     return false;
00041 
00042   // This instruction is producing bits that are not demanded. Shrink the RHS.
00043   Demanded &= OpC->getValue();
00044   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
00045   return true;
00046 }
00047 
00048 
00049 
00050 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
00051 /// SimplifyDemandedBits knows about.  See if the instruction has any
00052 /// properties that allow us to simplify its operands.
00053 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
00054   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
00055   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00056   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
00057 
00058   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
00059                                      KnownZero, KnownOne, 0);
00060   if (V == 0) return false;
00061   if (V == &Inst) return true;
00062   ReplaceInstUsesWith(Inst, V);
00063   return true;
00064 }
00065 
00066 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
00067 /// specified instruction operand if possible, updating it in place.  It returns
00068 /// true if it made any change and false otherwise.
00069 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
00070                                         APInt &KnownZero, APInt &KnownOne,
00071                                         unsigned Depth) {
00072   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
00073                                           KnownZero, KnownOne, Depth);
00074   if (NewVal == 0) return false;
00075   U = NewVal;
00076   return true;
00077 }
00078 
00079 
00080 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
00081 /// value based on the demanded bits.  When this function is called, it is known
00082 /// that only the bits set in DemandedMask of the result of V are ever used
00083 /// downstream. Consequently, depending on the mask and V, it may be possible
00084 /// to replace V with a constant or one of its operands. In such cases, this
00085 /// function does the replacement and returns true. In all other cases, it
00086 /// returns false after analyzing the expression and setting KnownOne and known
00087 /// to be one in the expression.  KnownZero contains all the bits that are known
00088 /// to be zero in the expression. These are provided to potentially allow the
00089 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
00090 /// the expression. KnownOne and KnownZero always follow the invariant that
00091 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
00092 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
00093 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
00094 /// and KnownOne must all be the same.
00095 ///
00096 /// This returns null if it did not change anything and it permits no
00097 /// simplification.  This returns V itself if it did some simplification of V's
00098 /// operands based on the information about what bits are demanded. This returns
00099 /// some other non-null value if it found out that V is equal to another value
00100 /// in the context where the specified bits are demanded, but not for all users.
00101 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
00102                                              APInt &KnownZero, APInt &KnownOne,
00103                                              unsigned Depth) {
00104   assert(V != 0 && "Null pointer of Value???");
00105   assert(Depth <= 6 && "Limit Search Depth");
00106   uint32_t BitWidth = DemandedMask.getBitWidth();
00107   Type *VTy = V->getType();
00108   assert((DL || !VTy->isPointerTy()) &&
00109          "SimplifyDemandedBits needs to know bit widths!");
00110   assert((!DL || DL->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
00111          (!VTy->isIntOrIntVectorTy() ||
00112           VTy->getScalarSizeInBits() == BitWidth) &&
00113          KnownZero.getBitWidth() == BitWidth &&
00114          KnownOne.getBitWidth() == BitWidth &&
00115          "Value *V, DemandedMask, KnownZero and KnownOne "
00116          "must have same BitWidth");
00117   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00118     // We know all of the bits for a constant!
00119     KnownOne = CI->getValue() & DemandedMask;
00120     KnownZero = ~KnownOne & DemandedMask;
00121     return 0;
00122   }
00123   if (isa<ConstantPointerNull>(V)) {
00124     // We know all of the bits for a constant!
00125     KnownOne.clearAllBits();
00126     KnownZero = DemandedMask;
00127     return 0;
00128   }
00129 
00130   KnownZero.clearAllBits();
00131   KnownOne.clearAllBits();
00132   if (DemandedMask == 0) {   // Not demanding any bits from V.
00133     if (isa<UndefValue>(V))
00134       return 0;
00135     return UndefValue::get(VTy);
00136   }
00137 
00138   if (Depth == 6)        // Limit search depth.
00139     return 0;
00140 
00141   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00142   APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00143 
00144   Instruction *I = dyn_cast<Instruction>(V);
00145   if (!I) {
00146     ComputeMaskedBits(V, KnownZero, KnownOne, Depth);
00147     return 0;        // Only analyze instructions.
00148   }
00149 
00150   // If there are multiple uses of this value and we aren't at the root, then
00151   // we can't do any simplifications of the operands, because DemandedMask
00152   // only reflects the bits demanded by *one* of the users.
00153   if (Depth != 0 && !I->hasOneUse()) {
00154     // Despite the fact that we can't simplify this instruction in all User's
00155     // context, we can at least compute the knownzero/knownone bits, and we can
00156     // do simplifications that apply to *just* the one user if we know that
00157     // this instruction has a simpler value in that context.
00158     if (I->getOpcode() == Instruction::And) {
00159       // If either the LHS or the RHS are Zero, the result is zero.
00160       ComputeMaskedBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1);
00161       ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
00162 
00163       // If all of the demanded bits are known 1 on one side, return the other.
00164       // These bits cannot contribute to the result of the 'and' in this
00165       // context.
00166       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
00167           (DemandedMask & ~LHSKnownZero))
00168         return I->getOperand(0);
00169       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
00170           (DemandedMask & ~RHSKnownZero))
00171         return I->getOperand(1);
00172 
00173       // If all of the demanded bits in the inputs are known zeros, return zero.
00174       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
00175         return Constant::getNullValue(VTy);
00176 
00177     } else if (I->getOpcode() == Instruction::Or) {
00178       // We can simplify (X|Y) -> X or Y in the user's context if we know that
00179       // only bits from X or Y are demanded.
00180 
00181       // If either the LHS or the RHS are One, the result is One.
00182       ComputeMaskedBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1);
00183       ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
00184 
00185       // If all of the demanded bits are known zero on one side, return the
00186       // other.  These bits cannot contribute to the result of the 'or' in this
00187       // context.
00188       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
00189           (DemandedMask & ~LHSKnownOne))
00190         return I->getOperand(0);
00191       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
00192           (DemandedMask & ~RHSKnownOne))
00193         return I->getOperand(1);
00194 
00195       // If all of the potentially set bits on one side are known to be set on
00196       // the other side, just use the 'other' side.
00197       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
00198           (DemandedMask & (~RHSKnownZero)))
00199         return I->getOperand(0);
00200       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
00201           (DemandedMask & (~LHSKnownZero)))
00202         return I->getOperand(1);
00203     } else if (I->getOpcode() == Instruction::Xor) {
00204       // We can simplify (X^Y) -> X or Y in the user's context if we know that
00205       // only bits from X or Y are demanded.
00206 
00207       ComputeMaskedBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1);
00208       ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
00209 
00210       // If all of the demanded bits are known zero on one side, return the
00211       // other.
00212       if ((DemandedMask & RHSKnownZero) == DemandedMask)
00213         return I->getOperand(0);
00214       if ((DemandedMask & LHSKnownZero) == DemandedMask)
00215         return I->getOperand(1);
00216     }
00217 
00218     // Compute the KnownZero/KnownOne bits to simplify things downstream.
00219     ComputeMaskedBits(I, KnownZero, KnownOne, Depth);
00220     return 0;
00221   }
00222 
00223   // If this is the root being simplified, allow it to have multiple uses,
00224   // just set the DemandedMask to all bits so that we can try to simplify the
00225   // operands.  This allows visitTruncInst (for example) to simplify the
00226   // operand of a trunc without duplicating all the logic below.
00227   if (Depth == 0 && !V->hasOneUse())
00228     DemandedMask = APInt::getAllOnesValue(BitWidth);
00229 
00230   switch (I->getOpcode()) {
00231   default:
00232     ComputeMaskedBits(I, KnownZero, KnownOne, Depth);
00233     break;
00234   case Instruction::And:
00235     // If either the LHS or the RHS are Zero, the result is zero.
00236     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00237                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00238         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
00239                              LHSKnownZero, LHSKnownOne, Depth+1))
00240       return I;
00241     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00242     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00243 
00244     // If all of the demanded bits are known 1 on one side, return the other.
00245     // These bits cannot contribute to the result of the 'and'.
00246     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
00247         (DemandedMask & ~LHSKnownZero))
00248       return I->getOperand(0);
00249     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
00250         (DemandedMask & ~RHSKnownZero))
00251       return I->getOperand(1);
00252 
00253     // If all of the demanded bits in the inputs are known zeros, return zero.
00254     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
00255       return Constant::getNullValue(VTy);
00256 
00257     // If the RHS is a constant, see if we can simplify it.
00258     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
00259       return I;
00260 
00261     // Output known-1 bits are only known if set in both the LHS & RHS.
00262     KnownOne = RHSKnownOne & LHSKnownOne;
00263     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00264     KnownZero = RHSKnownZero | LHSKnownZero;
00265     break;
00266   case Instruction::Or:
00267     // If either the LHS or the RHS are One, the result is One.
00268     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00269                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00270         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
00271                              LHSKnownZero, LHSKnownOne, Depth+1))
00272       return I;
00273     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00274     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00275 
00276     // If all of the demanded bits are known zero on one side, return the other.
00277     // These bits cannot contribute to the result of the 'or'.
00278     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
00279         (DemandedMask & ~LHSKnownOne))
00280       return I->getOperand(0);
00281     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
00282         (DemandedMask & ~RHSKnownOne))
00283       return I->getOperand(1);
00284 
00285     // If all of the potentially set bits on one side are known to be set on
00286     // the other side, just use the 'other' side.
00287     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
00288         (DemandedMask & (~RHSKnownZero)))
00289       return I->getOperand(0);
00290     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
00291         (DemandedMask & (~LHSKnownZero)))
00292       return I->getOperand(1);
00293 
00294     // If the RHS is a constant, see if we can simplify it.
00295     if (ShrinkDemandedConstant(I, 1, DemandedMask))
00296       return I;
00297 
00298     // Output known-0 bits are only known if clear in both the LHS & RHS.
00299     KnownZero = RHSKnownZero & LHSKnownZero;
00300     // Output known-1 are known to be set if set in either the LHS | RHS.
00301     KnownOne = RHSKnownOne | LHSKnownOne;
00302     break;
00303   case Instruction::Xor: {
00304     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00305                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00306         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00307                              LHSKnownZero, LHSKnownOne, Depth+1))
00308       return I;
00309     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00310     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00311 
00312     // If all of the demanded bits are known zero on one side, return the other.
00313     // These bits cannot contribute to the result of the 'xor'.
00314     if ((DemandedMask & RHSKnownZero) == DemandedMask)
00315       return I->getOperand(0);
00316     if ((DemandedMask & LHSKnownZero) == DemandedMask)
00317       return I->getOperand(1);
00318 
00319     // If all of the demanded bits are known to be zero on one side or the
00320     // other, turn this into an *inclusive* or.
00321     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
00322     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
00323       Instruction *Or =
00324         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
00325                                  I->getName());
00326       return InsertNewInstWith(Or, *I);
00327     }
00328 
00329     // If all of the demanded bits on one side are known, and all of the set
00330     // bits on that side are also known to be set on the other side, turn this
00331     // into an AND, as we know the bits will be cleared.
00332     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
00333     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
00334       // all known
00335       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
00336         Constant *AndC = Constant::getIntegerValue(VTy,
00337                                                    ~RHSKnownOne & DemandedMask);
00338         Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
00339         return InsertNewInstWith(And, *I);
00340       }
00341     }
00342 
00343     // If the RHS is a constant, see if we can simplify it.
00344     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
00345     if (ShrinkDemandedConstant(I, 1, DemandedMask))
00346       return I;
00347 
00348     // If our LHS is an 'and' and if it has one use, and if any of the bits we
00349     // are flipping are known to be set, then the xor is just resetting those
00350     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
00351     // simplifying both of them.
00352     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
00353       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
00354           isa<ConstantInt>(I->getOperand(1)) &&
00355           isa<ConstantInt>(LHSInst->getOperand(1)) &&
00356           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
00357         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
00358         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
00359         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
00360 
00361         Constant *AndC =
00362           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
00363         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
00364         InsertNewInstWith(NewAnd, *I);
00365 
00366         Constant *XorC =
00367           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
00368         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
00369         return InsertNewInstWith(NewXor, *I);
00370       }
00371 
00372     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00373     KnownZero= (RHSKnownZero & LHSKnownZero) | (RHSKnownOne & LHSKnownOne);
00374     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00375     KnownOne = (RHSKnownZero & LHSKnownOne) | (RHSKnownOne & LHSKnownZero);
00376     break;
00377   }
00378   case Instruction::Select:
00379     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
00380                              RHSKnownZero, RHSKnownOne, Depth+1) ||
00381         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
00382                              LHSKnownZero, LHSKnownOne, Depth+1))
00383       return I;
00384     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
00385     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
00386 
00387     // If the operands are constants, see if we can simplify them.
00388     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
00389         ShrinkDemandedConstant(I, 2, DemandedMask))
00390       return I;
00391 
00392     // Only known if known in both the LHS and RHS.
00393     KnownOne = RHSKnownOne & LHSKnownOne;
00394     KnownZero = RHSKnownZero & LHSKnownZero;
00395     break;
00396   case Instruction::Trunc: {
00397     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
00398     DemandedMask = DemandedMask.zext(truncBf);
00399     KnownZero = KnownZero.zext(truncBf);
00400     KnownOne = KnownOne.zext(truncBf);
00401     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00402                              KnownZero, KnownOne, Depth+1))
00403       return I;
00404     DemandedMask = DemandedMask.trunc(BitWidth);
00405     KnownZero = KnownZero.trunc(BitWidth);
00406     KnownOne = KnownOne.trunc(BitWidth);
00407     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00408     break;
00409   }
00410   case Instruction::BitCast:
00411     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
00412       return 0;  // vector->int or fp->int?
00413 
00414     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
00415       if (VectorType *SrcVTy =
00416             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
00417         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
00418           // Don't touch a bitcast between vectors of different element counts.
00419           return 0;
00420       } else
00421         // Don't touch a scalar-to-vector bitcast.
00422         return 0;
00423     } else if (I->getOperand(0)->getType()->isVectorTy())
00424       // Don't touch a vector-to-scalar bitcast.
00425       return 0;
00426 
00427     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00428                              KnownZero, KnownOne, Depth+1))
00429       return I;
00430     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00431     break;
00432   case Instruction::ZExt: {
00433     // Compute the bits in the result that are not present in the input.
00434     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
00435 
00436     DemandedMask = DemandedMask.trunc(SrcBitWidth);
00437     KnownZero = KnownZero.trunc(SrcBitWidth);
00438     KnownOne = KnownOne.trunc(SrcBitWidth);
00439     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
00440                              KnownZero, KnownOne, Depth+1))
00441       return I;
00442     DemandedMask = DemandedMask.zext(BitWidth);
00443     KnownZero = KnownZero.zext(BitWidth);
00444     KnownOne = KnownOne.zext(BitWidth);
00445     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00446     // The top bits are known to be zero.
00447     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00448     break;
00449   }
00450   case Instruction::SExt: {
00451     // Compute the bits in the result that are not present in the input.
00452     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
00453 
00454     APInt InputDemandedBits = DemandedMask &
00455                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
00456 
00457     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
00458     // If any of the sign extended bits are demanded, we know that the sign
00459     // bit is demanded.
00460     if ((NewBits & DemandedMask) != 0)
00461       InputDemandedBits.setBit(SrcBitWidth-1);
00462 
00463     InputDemandedBits = InputDemandedBits.trunc(SrcBitWidth);
00464     KnownZero = KnownZero.trunc(SrcBitWidth);
00465     KnownOne = KnownOne.trunc(SrcBitWidth);
00466     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
00467                              KnownZero, KnownOne, Depth+1))
00468       return I;
00469     InputDemandedBits = InputDemandedBits.zext(BitWidth);
00470     KnownZero = KnownZero.zext(BitWidth);
00471     KnownOne = KnownOne.zext(BitWidth);
00472     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00473 
00474     // If the sign bit of the input is known set or clear, then we know the
00475     // top bits of the result.
00476 
00477     // If the input sign bit is known zero, or if the NewBits are not demanded
00478     // convert this into a zero extension.
00479     if (KnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
00480       // Convert to ZExt cast
00481       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
00482       return InsertNewInstWith(NewCast, *I);
00483     } else if (KnownOne[SrcBitWidth-1]) {    // Input sign bit known set
00484       KnownOne |= NewBits;
00485     }
00486     break;
00487   }
00488   case Instruction::Add: {
00489     // Figure out what the input bits are.  If the top bits of the and result
00490     // are not demanded, then the add doesn't demand them from its input
00491     // either.
00492     unsigned NLZ = DemandedMask.countLeadingZeros();
00493 
00494     // If there is a constant on the RHS, there are a variety of xformations
00495     // we can do.
00496     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
00497       // If null, this should be simplified elsewhere.  Some of the xforms here
00498       // won't work if the RHS is zero.
00499       if (RHS->isZero())
00500         break;
00501 
00502       // If the top bit of the output is demanded, demand everything from the
00503       // input.  Otherwise, we demand all the input bits except NLZ top bits.
00504       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
00505 
00506       // Find information about known zero/one bits in the input.
00507       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
00508                                LHSKnownZero, LHSKnownOne, Depth+1))
00509         return I;
00510 
00511       // If the RHS of the add has bits set that can't affect the input, reduce
00512       // the constant.
00513       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
00514         return I;
00515 
00516       // Avoid excess work.
00517       if (LHSKnownZero == 0 && LHSKnownOne == 0)
00518         break;
00519 
00520       // Turn it into OR if input bits are zero.
00521       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
00522         Instruction *Or =
00523           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
00524                                    I->getName());
00525         return InsertNewInstWith(Or, *I);
00526       }
00527 
00528       // We can say something about the output known-zero and known-one bits,
00529       // depending on potential carries from the input constant and the
00530       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
00531       // bits set and the RHS constant is 0x01001, then we know we have a known
00532       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
00533 
00534       // To compute this, we first compute the potential carry bits.  These are
00535       // the bits which may be modified.  I'm not aware of a better way to do
00536       // this scan.
00537       const APInt &RHSVal = RHS->getValue();
00538       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
00539 
00540       // Now that we know which bits have carries, compute the known-1/0 sets.
00541 
00542       // Bits are known one if they are known zero in one operand and one in the
00543       // other, and there is no input carry.
00544       KnownOne = ((LHSKnownZero & RHSVal) |
00545                   (LHSKnownOne & ~RHSVal)) & ~CarryBits;
00546 
00547       // Bits are known zero if they are known zero in both operands and there
00548       // is no input carry.
00549       KnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
00550     } else {
00551       // If the high-bits of this ADD are not demanded, then it does not demand
00552       // the high bits of its LHS or RHS.
00553       if (DemandedMask[BitWidth-1] == 0) {
00554         // Right fill the mask of bits for this ADD to demand the most
00555         // significant bit and all those below it.
00556         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
00557         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
00558                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
00559             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
00560                                  LHSKnownZero, LHSKnownOne, Depth+1))
00561           return I;
00562       }
00563     }
00564     break;
00565   }
00566   case Instruction::Sub:
00567     // If the high-bits of this SUB are not demanded, then it does not demand
00568     // the high bits of its LHS or RHS.
00569     if (DemandedMask[BitWidth-1] == 0) {
00570       // Right fill the mask of bits for this SUB to demand the most
00571       // significant bit and all those below it.
00572       uint32_t NLZ = DemandedMask.countLeadingZeros();
00573       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
00574       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
00575                                LHSKnownZero, LHSKnownOne, Depth+1) ||
00576           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
00577                                LHSKnownZero, LHSKnownOne, Depth+1))
00578         return I;
00579     }
00580 
00581     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
00582     // the known zeros and ones.
00583     ComputeMaskedBits(V, KnownZero, KnownOne, Depth);
00584 
00585     // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
00586     // zero.
00587     if (ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(0))) {
00588       APInt I0 = C0->getValue();
00589       if ((I0 + 1).isPowerOf2() && (I0 | KnownZero).isAllOnesValue()) {
00590         Instruction *Xor = BinaryOperator::CreateXor(I->getOperand(1), C0);
00591         return InsertNewInstWith(Xor, *I);
00592       }
00593     }
00594     break;
00595   case Instruction::Shl:
00596     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00597       {
00598         Value *VarX; ConstantInt *C1;
00599         if (match(I->getOperand(0), m_Shr(m_Value(VarX), m_ConstantInt(C1)))) {
00600           Instruction *Shr = cast<Instruction>(I->getOperand(0));
00601           Value *R = SimplifyShrShlDemandedBits(Shr, I, DemandedMask,
00602                                                 KnownZero, KnownOne);
00603           if (R)
00604             return R;
00605         }
00606       }
00607 
00608       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
00609       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
00610 
00611       // If the shift is NUW/NSW, then it does demand the high bits.
00612       ShlOperator *IOp = cast<ShlOperator>(I);
00613       if (IOp->hasNoSignedWrap())
00614         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
00615       else if (IOp->hasNoUnsignedWrap())
00616         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
00617 
00618       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
00619                                KnownZero, KnownOne, Depth+1))
00620         return I;
00621       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00622       KnownZero <<= ShiftAmt;
00623       KnownOne  <<= ShiftAmt;
00624       // low bits known zero.
00625       if (ShiftAmt)
00626         KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
00627     }
00628     break;
00629   case Instruction::LShr:
00630     // For a logical shift right
00631     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00632       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
00633 
00634       // Unsigned shift right.
00635       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
00636 
00637       // If the shift is exact, then it does demand the low bits (and knows that
00638       // they are zero).
00639       if (cast<LShrOperator>(I)->isExact())
00640         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
00641 
00642       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
00643                                KnownZero, KnownOne, Depth+1))
00644         return I;
00645       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00646       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
00647       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
00648       if (ShiftAmt) {
00649         // Compute the new bits that are at the top now.
00650         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
00651         KnownZero |= HighBits;  // high bits known zero.
00652       }
00653     }
00654     break;
00655   case Instruction::AShr:
00656     // If this is an arithmetic shift right and only the low-bit is set, we can
00657     // always convert this into a logical shr, even if the shift amount is
00658     // variable.  The low bit of the shift cannot be an input sign bit unless
00659     // the shift amount is >= the size of the datatype, which is undefined.
00660     if (DemandedMask == 1) {
00661       // Perform the logical shift right.
00662       Instruction *NewVal = BinaryOperator::CreateLShr(
00663                         I->getOperand(0), I->getOperand(1), I->getName());
00664       return InsertNewInstWith(NewVal, *I);
00665     }
00666 
00667     // If the sign bit is the only bit demanded by this ashr, then there is no
00668     // need to do it, the shift doesn't change the high bit.
00669     if (DemandedMask.isSignBit())
00670       return I->getOperand(0);
00671 
00672     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00673       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
00674 
00675       // Signed shift right.
00676       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
00677       // If any of the "high bits" are demanded, we should set the sign bit as
00678       // demanded.
00679       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
00680         DemandedMaskIn.setBit(BitWidth-1);
00681 
00682       // If the shift is exact, then it does demand the low bits (and knows that
00683       // they are zero).
00684       if (cast<AShrOperator>(I)->isExact())
00685         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
00686 
00687       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
00688                                KnownZero, KnownOne, Depth+1))
00689         return I;
00690       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00691       // Compute the new bits that are at the top now.
00692       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
00693       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
00694       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
00695 
00696       // Handle the sign bits.
00697       APInt SignBit(APInt::getSignBit(BitWidth));
00698       // Adjust to where it is now in the mask.
00699       SignBit = APIntOps::lshr(SignBit, ShiftAmt);
00700 
00701       // If the input sign bit is known to be zero, or if none of the top bits
00702       // are demanded, turn this into an unsigned shift right.
00703       if (BitWidth <= ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||
00704           (HighBits & ~DemandedMask) == HighBits) {
00705         // Perform the logical shift right.
00706         BinaryOperator *NewVal = BinaryOperator::CreateLShr(I->getOperand(0),
00707                                                             SA, I->getName());
00708         NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
00709         return InsertNewInstWith(NewVal, *I);
00710       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
00711         KnownOne |= HighBits;
00712       }
00713     }
00714     break;
00715   case Instruction::SRem:
00716     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
00717       // X % -1 demands all the bits because we don't want to introduce
00718       // INT_MIN % -1 (== undef) by accident.
00719       if (Rem->isAllOnesValue())
00720         break;
00721       APInt RA = Rem->getValue().abs();
00722       if (RA.isPowerOf2()) {
00723         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
00724           return I->getOperand(0);
00725 
00726         APInt LowBits = RA - 1;
00727         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
00728         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
00729                                  LHSKnownZero, LHSKnownOne, Depth+1))
00730           return I;
00731 
00732         // The low bits of LHS are unchanged by the srem.
00733         KnownZero = LHSKnownZero & LowBits;
00734         KnownOne = LHSKnownOne & LowBits;
00735 
00736         // If LHS is non-negative or has all low bits zero, then the upper bits
00737         // are all zero.
00738         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
00739           KnownZero |= ~LowBits;
00740 
00741         // If LHS is negative and not all low bits are zero, then the upper bits
00742         // are all one.
00743         if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
00744           KnownOne |= ~LowBits;
00745 
00746         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
00747       }
00748     }
00749 
00750     // The sign bit is the LHS's sign bit, except when the result of the
00751     // remainder is zero.
00752     if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
00753       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00754       ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1);
00755       // If it's known zero, our sign bit is also zero.
00756       if (LHSKnownZero.isNegative())
00757         KnownZero.setBit(KnownZero.getBitWidth() - 1);
00758     }
00759     break;
00760   case Instruction::URem: {
00761     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
00762     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
00763     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
00764                              KnownZero2, KnownOne2, Depth+1) ||
00765         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
00766                              KnownZero2, KnownOne2, Depth+1))
00767       return I;
00768 
00769     unsigned Leaders = KnownZero2.countLeadingOnes();
00770     Leaders = std::max(Leaders,
00771                        KnownZero2.countLeadingOnes());
00772     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
00773     break;
00774   }
00775   case Instruction::Call:
00776     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00777       switch (II->getIntrinsicID()) {
00778       default: break;
00779       case Intrinsic::bswap: {
00780         // If the only bits demanded come from one byte of the bswap result,
00781         // just shift the input byte into position to eliminate the bswap.
00782         unsigned NLZ = DemandedMask.countLeadingZeros();
00783         unsigned NTZ = DemandedMask.countTrailingZeros();
00784 
00785         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
00786         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
00787         // have 14 leading zeros, round to 8.
00788         NLZ &= ~7;
00789         NTZ &= ~7;
00790         // If we need exactly one byte, we can do this transformation.
00791         if (BitWidth-NLZ-NTZ == 8) {
00792           unsigned ResultBit = NTZ;
00793           unsigned InputBit = BitWidth-NTZ-8;
00794 
00795           // Replace this with either a left or right shift to get the byte into
00796           // the right place.
00797           Instruction *NewVal;
00798           if (InputBit > ResultBit)
00799             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
00800                     ConstantInt::get(I->getType(), InputBit-ResultBit));
00801           else
00802             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
00803                     ConstantInt::get(I->getType(), ResultBit-InputBit));
00804           NewVal->takeName(I);
00805           return InsertNewInstWith(NewVal, *I);
00806         }
00807 
00808         // TODO: Could compute known zero/one bits based on the input.
00809         break;
00810       }
00811       case Intrinsic::x86_sse42_crc32_64_64:
00812         KnownZero = APInt::getHighBitsSet(64, 32);
00813         return 0;
00814       }
00815     }
00816     ComputeMaskedBits(V, KnownZero, KnownOne, Depth);
00817     break;
00818   }
00819 
00820   // If the client is only demanding bits that we know, return the known
00821   // constant.
00822   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
00823     return Constant::getIntegerValue(VTy, KnownOne);
00824   return 0;
00825 }
00826 
00827 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
00828 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
00829 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
00830 /// of "C2-C1".
00831 ///
00832 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
00833 /// ..., bn}, without considering the specific value X is holding.
00834 /// This transformation is legal iff one of following conditions is hold:
00835 ///  1) All the bit in S are 0, in this case E1 == E2.
00836 ///  2) We don't care those bits in S, per the input DemandedMask.
00837 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
00838 ///     rest bits.
00839 ///
00840 /// Currently we only test condition 2).
00841 ///
00842 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
00843 /// not successful.
00844 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
00845   Instruction *Shl, APInt DemandedMask, APInt &KnownZero, APInt &KnownOne) {
00846 
00847   const APInt &ShlOp1 = cast<ConstantInt>(Shl->getOperand(1))->getValue();
00848   const APInt &ShrOp1 = cast<ConstantInt>(Shr->getOperand(1))->getValue();
00849   if (!ShlOp1 || !ShrOp1)
00850       return 0; // Noop.
00851 
00852   Value *VarX = Shr->getOperand(0);
00853   Type *Ty = VarX->getType();
00854   unsigned BitWidth = Ty->getIntegerBitWidth();
00855   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
00856     return 0; // Undef.
00857 
00858   unsigned ShlAmt = ShlOp1.getZExtValue();
00859   unsigned ShrAmt = ShrOp1.getZExtValue();
00860 
00861   KnownOne.clearAllBits();
00862   KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
00863   KnownZero &= DemandedMask;
00864 
00865   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
00866   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
00867 
00868   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
00869   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
00870                       (BitMask1.ashr(ShrAmt) << ShlAmt);
00871 
00872   if (ShrAmt <= ShlAmt) {
00873     BitMask2 <<= (ShlAmt - ShrAmt);
00874   } else {
00875     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
00876                         BitMask2.ashr(ShrAmt - ShlAmt);
00877   }
00878 
00879   // Check if condition-2 (see the comment to this function) is satified.
00880   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
00881     if (ShrAmt == ShlAmt)
00882       return VarX;
00883 
00884     if (!Shr->hasOneUse())
00885       return 0;
00886 
00887     BinaryOperator *New;
00888     if (ShrAmt < ShlAmt) {
00889       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
00890       New = BinaryOperator::CreateShl(VarX, Amt);
00891       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
00892       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
00893       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
00894     } else {
00895       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
00896       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
00897                      BinaryOperator::CreateAShr(VarX, Amt);
00898       if (cast<BinaryOperator>(Shr)->isExact())
00899         New->setIsExact(true);
00900     }
00901 
00902     return InsertNewInstWith(New, *Shl);
00903   }
00904 
00905   return 0;
00906 }
00907 
00908 /// SimplifyDemandedVectorElts - The specified value produces a vector with
00909 /// any number of elements. DemandedElts contains the set of elements that are
00910 /// actually used by the caller.  This method analyzes which elements of the
00911 /// operand are undef and returns that information in UndefElts.
00912 ///
00913 /// If the information about demanded elements can be used to simplify the
00914 /// operation, the operation is simplified, then the resultant value is
00915 /// returned.  This returns null if no change was made.
00916 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
00917                                                 APInt &UndefElts,
00918                                                 unsigned Depth) {
00919   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
00920   APInt EltMask(APInt::getAllOnesValue(VWidth));
00921   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
00922 
00923   if (isa<UndefValue>(V)) {
00924     // If the entire vector is undefined, just return this info.
00925     UndefElts = EltMask;
00926     return 0;
00927   }
00928 
00929   if (DemandedElts == 0) { // If nothing is demanded, provide undef.
00930     UndefElts = EltMask;
00931     return UndefValue::get(V->getType());
00932   }
00933 
00934   UndefElts = 0;
00935 
00936   // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
00937   if (Constant *C = dyn_cast<Constant>(V)) {
00938     // Check if this is identity. If so, return 0 since we are not simplifying
00939     // anything.
00940     if (DemandedElts.isAllOnesValue())
00941       return 0;
00942 
00943     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
00944     Constant *Undef = UndefValue::get(EltTy);
00945 
00946     SmallVector<Constant*, 16> Elts;
00947     for (unsigned i = 0; i != VWidth; ++i) {
00948       if (!DemandedElts[i]) {   // If not demanded, set to undef.
00949         Elts.push_back(Undef);
00950         UndefElts.setBit(i);
00951         continue;
00952       }
00953 
00954       Constant *Elt = C->getAggregateElement(i);
00955       if (Elt == 0) return 0;
00956 
00957       if (isa<UndefValue>(Elt)) {   // Already undef.
00958         Elts.push_back(Undef);
00959         UndefElts.setBit(i);
00960       } else {                               // Otherwise, defined.
00961         Elts.push_back(Elt);
00962       }
00963     }
00964 
00965     // If we changed the constant, return it.
00966     Constant *NewCV = ConstantVector::get(Elts);
00967     return NewCV != C ? NewCV : 0;
00968   }
00969 
00970   // Limit search depth.
00971   if (Depth == 10)
00972     return 0;
00973 
00974   // If multiple users are using the root value, proceed with
00975   // simplification conservatively assuming that all elements
00976   // are needed.
00977   if (!V->hasOneUse()) {
00978     // Quit if we find multiple users of a non-root value though.
00979     // They'll be handled when it's their turn to be visited by
00980     // the main instcombine process.
00981     if (Depth != 0)
00982       // TODO: Just compute the UndefElts information recursively.
00983       return 0;
00984 
00985     // Conservatively assume that all elements are needed.
00986     DemandedElts = EltMask;
00987   }
00988 
00989   Instruction *I = dyn_cast<Instruction>(V);
00990   if (!I) return 0;        // Only analyze instructions.
00991 
00992   bool MadeChange = false;
00993   APInt UndefElts2(VWidth, 0);
00994   Value *TmpV;
00995   switch (I->getOpcode()) {
00996   default: break;
00997 
00998   case Instruction::InsertElement: {
00999     // If this is a variable index, we don't know which element it overwrites.
01000     // demand exactly the same input as we produce.
01001     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
01002     if (Idx == 0) {
01003       // Note that we can't propagate undef elt info, because we don't know
01004       // which elt is getting updated.
01005       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01006                                         UndefElts2, Depth+1);
01007       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01008       break;
01009     }
01010 
01011     // If this is inserting an element that isn't demanded, remove this
01012     // insertelement.
01013     unsigned IdxNo = Idx->getZExtValue();
01014     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
01015       Worklist.Add(I);
01016       return I->getOperand(0);
01017     }
01018 
01019     // Otherwise, the element inserted overwrites whatever was there, so the
01020     // input demanded set is simpler than the output set.
01021     APInt DemandedElts2 = DemandedElts;
01022     DemandedElts2.clearBit(IdxNo);
01023     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
01024                                       UndefElts, Depth+1);
01025     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01026 
01027     // The inserted element is defined.
01028     UndefElts.clearBit(IdxNo);
01029     break;
01030   }
01031   case Instruction::ShuffleVector: {
01032     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
01033     uint64_t LHSVWidth =
01034       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
01035     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
01036     for (unsigned i = 0; i < VWidth; i++) {
01037       if (DemandedElts[i]) {
01038         unsigned MaskVal = Shuffle->getMaskValue(i);
01039         if (MaskVal != -1u) {
01040           assert(MaskVal < LHSVWidth * 2 &&
01041                  "shufflevector mask index out of range!");
01042           if (MaskVal < LHSVWidth)
01043             LeftDemanded.setBit(MaskVal);
01044           else
01045             RightDemanded.setBit(MaskVal - LHSVWidth);
01046         }
01047       }
01048     }
01049 
01050     APInt UndefElts4(LHSVWidth, 0);
01051     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
01052                                       UndefElts4, Depth+1);
01053     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01054 
01055     APInt UndefElts3(LHSVWidth, 0);
01056     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
01057                                       UndefElts3, Depth+1);
01058     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01059 
01060     bool NewUndefElts = false;
01061     for (unsigned i = 0; i < VWidth; i++) {
01062       unsigned MaskVal = Shuffle->getMaskValue(i);
01063       if (MaskVal == -1u) {
01064         UndefElts.setBit(i);
01065       } else if (!DemandedElts[i]) {
01066         NewUndefElts = true;
01067         UndefElts.setBit(i);
01068       } else if (MaskVal < LHSVWidth) {
01069         if (UndefElts4[MaskVal]) {
01070           NewUndefElts = true;
01071           UndefElts.setBit(i);
01072         }
01073       } else {
01074         if (UndefElts3[MaskVal - LHSVWidth]) {
01075           NewUndefElts = true;
01076           UndefElts.setBit(i);
01077         }
01078       }
01079     }
01080 
01081     if (NewUndefElts) {
01082       // Add additional discovered undefs.
01083       SmallVector<Constant*, 16> Elts;
01084       for (unsigned i = 0; i < VWidth; ++i) {
01085         if (UndefElts[i])
01086           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
01087         else
01088           Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
01089                                           Shuffle->getMaskValue(i)));
01090       }
01091       I->setOperand(2, ConstantVector::get(Elts));
01092       MadeChange = true;
01093     }
01094     break;
01095   }
01096   case Instruction::Select: {
01097     APInt LeftDemanded(DemandedElts), RightDemanded(DemandedElts);
01098     if (ConstantVector* CV = dyn_cast<ConstantVector>(I->getOperand(0))) {
01099       for (unsigned i = 0; i < VWidth; i++) {
01100         if (CV->getAggregateElement(i)->isNullValue())
01101           LeftDemanded.clearBit(i);
01102         else
01103           RightDemanded.clearBit(i);
01104       }
01105     }
01106 
01107     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded,
01108                                       UndefElts, Depth+1);
01109     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01110 
01111     TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
01112                                       UndefElts2, Depth+1);
01113     if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
01114 
01115     // Output elements are undefined if both are undefined.
01116     UndefElts &= UndefElts2;
01117     break;
01118   }
01119   case Instruction::BitCast: {
01120     // Vector->vector casts only.
01121     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
01122     if (!VTy) break;
01123     unsigned InVWidth = VTy->getNumElements();
01124     APInt InputDemandedElts(InVWidth, 0);
01125     unsigned Ratio;
01126 
01127     if (VWidth == InVWidth) {
01128       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
01129       // elements as are demanded of us.
01130       Ratio = 1;
01131       InputDemandedElts = DemandedElts;
01132     } else if (VWidth > InVWidth) {
01133       // Untested so far.
01134       break;
01135 
01136       // If there are more elements in the result than there are in the source,
01137       // then an input element is live if any of the corresponding output
01138       // elements are live.
01139       Ratio = VWidth/InVWidth;
01140       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
01141         if (DemandedElts[OutIdx])
01142           InputDemandedElts.setBit(OutIdx/Ratio);
01143       }
01144     } else {
01145       // Untested so far.
01146       break;
01147 
01148       // If there are more elements in the source than there are in the result,
01149       // then an input element is live if the corresponding output element is
01150       // live.
01151       Ratio = InVWidth/VWidth;
01152       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
01153         if (DemandedElts[InIdx/Ratio])
01154           InputDemandedElts.setBit(InIdx);
01155     }
01156 
01157     // div/rem demand all inputs, because they don't want divide by zero.
01158     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
01159                                       UndefElts2, Depth+1);
01160     if (TmpV) {
01161       I->setOperand(0, TmpV);
01162       MadeChange = true;
01163     }
01164 
01165     UndefElts = UndefElts2;
01166     if (VWidth > InVWidth) {
01167       llvm_unreachable("Unimp");
01168       // If there are more elements in the result than there are in the source,
01169       // then an output element is undef if the corresponding input element is
01170       // undef.
01171       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
01172         if (UndefElts2[OutIdx/Ratio])
01173           UndefElts.setBit(OutIdx);
01174     } else if (VWidth < InVWidth) {
01175       llvm_unreachable("Unimp");
01176       // If there are more elements in the source than there are in the result,
01177       // then a result element is undef if all of the corresponding input
01178       // elements are undef.
01179       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
01180       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
01181         if (!UndefElts2[InIdx])            // Not undef?
01182           UndefElts.clearBit(InIdx/Ratio);    // Clear undef bit.
01183     }
01184     break;
01185   }
01186   case Instruction::And:
01187   case Instruction::Or:
01188   case Instruction::Xor:
01189   case Instruction::Add:
01190   case Instruction::Sub:
01191   case Instruction::Mul:
01192     // div/rem demand all inputs, because they don't want divide by zero.
01193     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01194                                       UndefElts, Depth+1);
01195     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01196     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
01197                                       UndefElts2, Depth+1);
01198     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
01199 
01200     // Output elements are undefined if both are undefined.  Consider things
01201     // like undef&0.  The result is known zero, not undef.
01202     UndefElts &= UndefElts2;
01203     break;
01204   case Instruction::FPTrunc:
01205   case Instruction::FPExt:
01206     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
01207                                       UndefElts, Depth+1);
01208     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
01209     break;
01210 
01211   case Instruction::Call: {
01212     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
01213     if (!II) break;
01214     switch (II->getIntrinsicID()) {
01215     default: break;
01216 
01217     // Binary vector operations that work column-wise.  A dest element is a
01218     // function of the corresponding input elements from the two inputs.
01219     case Intrinsic::x86_sse_sub_ss:
01220     case Intrinsic::x86_sse_mul_ss:
01221     case Intrinsic::x86_sse_min_ss:
01222     case Intrinsic::x86_sse_max_ss:
01223     case Intrinsic::x86_sse2_sub_sd:
01224     case Intrinsic::x86_sse2_mul_sd:
01225     case Intrinsic::x86_sse2_min_sd:
01226     case Intrinsic::x86_sse2_max_sd:
01227       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
01228                                         UndefElts, Depth+1);
01229       if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
01230       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(1), DemandedElts,
01231                                         UndefElts2, Depth+1);
01232       if (TmpV) { II->setArgOperand(1, TmpV); MadeChange = true; }
01233 
01234       // If only the low elt is demanded and this is a scalarizable intrinsic,
01235       // scalarize it now.
01236       if (DemandedElts == 1) {
01237         switch (II->getIntrinsicID()) {
01238         default: break;
01239         case Intrinsic::x86_sse_sub_ss:
01240         case Intrinsic::x86_sse_mul_ss:
01241         case Intrinsic::x86_sse2_sub_sd:
01242         case Intrinsic::x86_sse2_mul_sd:
01243           // TODO: Lower MIN/MAX/ABS/etc
01244           Value *LHS = II->getArgOperand(0);
01245           Value *RHS = II->getArgOperand(1);
01246           // Extract the element as scalars.
01247           LHS = InsertNewInstWith(ExtractElementInst::Create(LHS,
01248             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
01249           RHS = InsertNewInstWith(ExtractElementInst::Create(RHS,
01250             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
01251 
01252           switch (II->getIntrinsicID()) {
01253           default: llvm_unreachable("Case stmts out of sync!");
01254           case Intrinsic::x86_sse_sub_ss:
01255           case Intrinsic::x86_sse2_sub_sd:
01256             TmpV = InsertNewInstWith(BinaryOperator::CreateFSub(LHS, RHS,
01257                                                         II->getName()), *II);
01258             break;
01259           case Intrinsic::x86_sse_mul_ss:
01260           case Intrinsic::x86_sse2_mul_sd:
01261             TmpV = InsertNewInstWith(BinaryOperator::CreateFMul(LHS, RHS,
01262                                                          II->getName()), *II);
01263             break;
01264           }
01265 
01266           Instruction *New =
01267             InsertElementInst::Create(
01268               UndefValue::get(II->getType()), TmpV,
01269               ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
01270                                       II->getName());
01271           InsertNewInstWith(New, *II);
01272           return New;
01273         }
01274       }
01275 
01276       // Output elements are undefined if both are undefined.  Consider things
01277       // like undef&0.  The result is known zero, not undef.
01278       UndefElts &= UndefElts2;
01279       break;
01280     }
01281     break;
01282   }
01283   }
01284   return MadeChange ? I : 0;
01285 }