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