Home | History | Annotate | Download | only in InstCombine
      1 //===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file contains logic for simplifying instructions based on information
     11 // about how they are used.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "InstCombineInternal.h"
     16 #include "llvm/Analysis/ValueTracking.h"
     17 #include "llvm/IR/IntrinsicInst.h"
     18 #include "llvm/IR/PatternMatch.h"
     19 
     20 using namespace llvm;
     21 using namespace llvm::PatternMatch;
     22 
     23 #define DEBUG_TYPE "instcombine"
     24 
     25 /// Check to see if the specified operand of the specified instruction is a
     26 /// constant integer. If so, check to see if there are any bits set in the
     27 /// constant that are not demanded. If so, shrink the constant and return true.
     28 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
     29                                    APInt Demanded) {
     30   assert(I && "No instruction?");
     31   assert(OpNo < I->getNumOperands() && "Operand index too large");
     32 
     33   // If the operand is not a constant integer, nothing to do.
     34   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
     35   if (!OpC) return false;
     36 
     37   // If there are no bits set that aren't demanded, nothing to do.
     38   Demanded = Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
     39   if ((~Demanded & OpC->getValue()) == 0)
     40     return false;
     41 
     42   // This instruction is producing bits that are not demanded. Shrink the RHS.
     43   Demanded &= OpC->getValue();
     44   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
     45 
     46   return true;
     47 }
     48 
     49 
     50 
     51 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
     52 /// the instruction has any properties that allow us to simplify its operands.
     53 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
     54   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
     55   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
     56   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
     57 
     58   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, KnownZero, KnownOne,
     59                                      0, &Inst);
     60   if (!V) return false;
     61   if (V == &Inst) return true;
     62   replaceInstUsesWith(Inst, V);
     63   return true;
     64 }
     65 
     66 /// This form of SimplifyDemandedBits simplifies the specified instruction
     67 /// operand if possible, updating it in place. It returns true if it made any
     68 /// change and false otherwise.
     69 bool InstCombiner::SimplifyDemandedBits(Use &U, const APInt &DemandedMask,
     70                                         APInt &KnownZero, APInt &KnownOne,
     71                                         unsigned Depth) {
     72   auto *UserI = dyn_cast<Instruction>(U.getUser());
     73   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, KnownZero,
     74                                           KnownOne, Depth, UserI);
     75   if (!NewVal) return false;
     76   U = NewVal;
     77   return true;
     78 }
     79 
     80 
     81 /// This function attempts to replace V with a simpler value based on the
     82 /// demanded bits. When this function is called, it is known that only the bits
     83 /// set in DemandedMask of the result of V are ever used downstream.
     84 /// Consequently, depending on the mask and V, it may be possible to replace V
     85 /// with a constant or one of its operands. In such cases, this function does
     86 /// the replacement and returns true. In all other cases, it returns false after
     87 /// analyzing the expression and setting KnownOne and known to be one in the
     88 /// expression. KnownZero contains all the bits that are known to be zero in the
     89 /// expression. These are provided to potentially allow the caller (which might
     90 /// recursively be SimplifyDemandedBits itself) to simplify the expression.
     91 /// KnownOne and KnownZero always follow the invariant that:
     92 ///   KnownOne & KnownZero == 0.
     93 /// That is, a bit can't be both 1 and 0. Note that the bits in KnownOne and
     94 /// KnownZero may only be accurate for those bits set in DemandedMask. Note also
     95 /// that the bitwidth of V, DemandedMask, KnownZero and KnownOne must all be the
     96 /// same.
     97 ///
     98 /// This returns null if it did not change anything and it permits no
     99 /// simplification.  This returns V itself if it did some simplification of V's
    100 /// operands based on the information about what bits are demanded. This returns
    101 /// some other non-null value if it found out that V is equal to another value
    102 /// in the context where the specified bits are demanded, but not for all users.
    103 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
    104                                              APInt &KnownZero, APInt &KnownOne,
    105                                              unsigned Depth,
    106                                              Instruction *CxtI) {
    107   assert(V != nullptr && "Null pointer of Value???");
    108   assert(Depth <= 6 && "Limit Search Depth");
    109   uint32_t BitWidth = DemandedMask.getBitWidth();
    110   Type *VTy = V->getType();
    111   assert(
    112       (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
    113       KnownZero.getBitWidth() == BitWidth &&
    114       KnownOne.getBitWidth() == BitWidth &&
    115       "Value *V, DemandedMask, KnownZero and KnownOne "
    116       "must have same BitWidth");
    117   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    118     // We know all of the bits for a constant!
    119     KnownOne = CI->getValue() & DemandedMask;
    120     KnownZero = ~KnownOne & DemandedMask;
    121     return nullptr;
    122   }
    123   if (isa<ConstantPointerNull>(V)) {
    124     // We know all of the bits for a constant!
    125     KnownOne.clearAllBits();
    126     KnownZero = DemandedMask;
    127     return nullptr;
    128   }
    129 
    130   KnownZero.clearAllBits();
    131   KnownOne.clearAllBits();
    132   if (DemandedMask == 0) {   // Not demanding any bits from V.
    133     if (isa<UndefValue>(V))
    134       return nullptr;
    135     return UndefValue::get(VTy);
    136   }
    137 
    138   if (Depth == 6)        // Limit search depth.
    139     return nullptr;
    140 
    141   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
    142   APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
    143 
    144   Instruction *I = dyn_cast<Instruction>(V);
    145   if (!I) {
    146     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
    147     return nullptr;        // Only analyze instructions.
    148   }
    149 
    150   // If there are multiple uses of this value and we aren't at the root, then
    151   // we can't do any simplifications of the operands, because DemandedMask
    152   // only reflects the bits demanded by *one* of the users.
    153   if (Depth != 0 && !I->hasOneUse()) {
    154     // Despite the fact that we can't simplify this instruction in all User's
    155     // context, we can at least compute the knownzero/knownone bits, and we can
    156     // do simplifications that apply to *just* the one user if we know that
    157     // this instruction has a simpler value in that context.
    158     if (I->getOpcode() == Instruction::And) {
    159       // If either the LHS or the RHS are Zero, the result is zero.
    160       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
    161                        CxtI);
    162       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
    163                        CxtI);
    164 
    165       // If all of the demanded bits are known 1 on one side, return the other.
    166       // These bits cannot contribute to the result of the 'and' in this
    167       // context.
    168       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
    169           (DemandedMask & ~LHSKnownZero))
    170         return I->getOperand(0);
    171       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
    172           (DemandedMask & ~RHSKnownZero))
    173         return I->getOperand(1);
    174 
    175       // If all of the demanded bits in the inputs are known zeros, return zero.
    176       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
    177         return Constant::getNullValue(VTy);
    178 
    179     } else if (I->getOpcode() == Instruction::Or) {
    180       // We can simplify (X|Y) -> X or Y in the user's context if we know that
    181       // only bits from X or Y are demanded.
    182 
    183       // If either the LHS or the RHS are One, the result is One.
    184       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
    185                        CxtI);
    186       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
    187                        CxtI);
    188 
    189       // If all of the demanded bits are known zero on one side, return the
    190       // other.  These bits cannot contribute to the result of the 'or' in this
    191       // context.
    192       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
    193           (DemandedMask & ~LHSKnownOne))
    194         return I->getOperand(0);
    195       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
    196           (DemandedMask & ~RHSKnownOne))
    197         return I->getOperand(1);
    198 
    199       // If all of the potentially set bits on one side are known to be set on
    200       // the other side, just use the 'other' side.
    201       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
    202           (DemandedMask & (~RHSKnownZero)))
    203         return I->getOperand(0);
    204       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
    205           (DemandedMask & (~LHSKnownZero)))
    206         return I->getOperand(1);
    207     } else if (I->getOpcode() == Instruction::Xor) {
    208       // We can simplify (X^Y) -> X or Y in the user's context if we know that
    209       // only bits from X or Y are demanded.
    210 
    211       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
    212                        CxtI);
    213       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
    214                        CxtI);
    215 
    216       // If all of the demanded bits are known zero on one side, return the
    217       // other.
    218       if ((DemandedMask & RHSKnownZero) == DemandedMask)
    219         return I->getOperand(0);
    220       if ((DemandedMask & LHSKnownZero) == DemandedMask)
    221         return I->getOperand(1);
    222     }
    223 
    224     // Compute the KnownZero/KnownOne bits to simplify things downstream.
    225     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
    226     return nullptr;
    227   }
    228 
    229   // If this is the root being simplified, allow it to have multiple uses,
    230   // just set the DemandedMask to all bits so that we can try to simplify the
    231   // operands.  This allows visitTruncInst (for example) to simplify the
    232   // operand of a trunc without duplicating all the logic below.
    233   if (Depth == 0 && !V->hasOneUse())
    234     DemandedMask = APInt::getAllOnesValue(BitWidth);
    235 
    236   switch (I->getOpcode()) {
    237   default:
    238     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
    239     break;
    240   case Instruction::And:
    241     // If either the LHS or the RHS are Zero, the result is zero.
    242     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, RHSKnownZero,
    243                              RHSKnownOne, Depth + 1) ||
    244         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
    245                              LHSKnownZero, LHSKnownOne, Depth + 1))
    246       return I;
    247     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
    248     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
    249 
    250     // If the client is only demanding bits that we know, return the known
    251     // constant.
    252     if ((DemandedMask & ((RHSKnownZero | LHSKnownZero)|
    253                          (RHSKnownOne & LHSKnownOne))) == DemandedMask)
    254       return Constant::getIntegerValue(VTy, RHSKnownOne & LHSKnownOne);
    255 
    256     // If all of the demanded bits are known 1 on one side, return the other.
    257     // These bits cannot contribute to the result of the 'and'.
    258     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
    259         (DemandedMask & ~LHSKnownZero))
    260       return I->getOperand(0);
    261     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
    262         (DemandedMask & ~RHSKnownZero))
    263       return I->getOperand(1);
    264 
    265     // If all of the demanded bits in the inputs are known zeros, return zero.
    266     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
    267       return Constant::getNullValue(VTy);
    268 
    269     // If the RHS is a constant, see if we can simplify it.
    270     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
    271       return I;
    272 
    273     // Output known-1 bits are only known if set in both the LHS & RHS.
    274     KnownOne = RHSKnownOne & LHSKnownOne;
    275     // Output known-0 are known to be clear if zero in either the LHS | RHS.
    276     KnownZero = RHSKnownZero | LHSKnownZero;
    277     break;
    278   case Instruction::Or:
    279     // If either the LHS or the RHS are One, the result is One.
    280     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, RHSKnownZero,
    281                              RHSKnownOne, Depth + 1) ||
    282         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
    283                              LHSKnownZero, LHSKnownOne, Depth + 1))
    284       return I;
    285     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
    286     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
    287 
    288     // If the client is only demanding bits that we know, return the known
    289     // constant.
    290     if ((DemandedMask & ((RHSKnownZero & LHSKnownZero)|
    291                          (RHSKnownOne | LHSKnownOne))) == DemandedMask)
    292       return Constant::getIntegerValue(VTy, RHSKnownOne | LHSKnownOne);
    293 
    294     // If all of the demanded bits are known zero on one side, return the other.
    295     // These bits cannot contribute to the result of the 'or'.
    296     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
    297         (DemandedMask & ~LHSKnownOne))
    298       return I->getOperand(0);
    299     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
    300         (DemandedMask & ~RHSKnownOne))
    301       return I->getOperand(1);
    302 
    303     // If all of the potentially set bits on one side are known to be set on
    304     // the other side, just use the 'other' side.
    305     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
    306         (DemandedMask & (~RHSKnownZero)))
    307       return I->getOperand(0);
    308     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
    309         (DemandedMask & (~LHSKnownZero)))
    310       return I->getOperand(1);
    311 
    312     // If the RHS is a constant, see if we can simplify it.
    313     if (ShrinkDemandedConstant(I, 1, DemandedMask))
    314       return I;
    315 
    316     // Output known-0 bits are only known if clear in both the LHS & RHS.
    317     KnownZero = RHSKnownZero & LHSKnownZero;
    318     // Output known-1 are known to be set if set in either the LHS | RHS.
    319     KnownOne = RHSKnownOne | LHSKnownOne;
    320     break;
    321   case Instruction::Xor: {
    322     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, RHSKnownZero,
    323                              RHSKnownOne, Depth + 1) ||
    324         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, LHSKnownZero,
    325                              LHSKnownOne, Depth + 1))
    326       return I;
    327     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
    328     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
    329 
    330     // Output known-0 bits are known if clear or set in both the LHS & RHS.
    331     APInt IKnownZero = (RHSKnownZero & LHSKnownZero) |
    332                        (RHSKnownOne & LHSKnownOne);
    333     // Output known-1 are known to be set if set in only one of the LHS, RHS.
    334     APInt IKnownOne =  (RHSKnownZero & LHSKnownOne) |
    335                        (RHSKnownOne & LHSKnownZero);
    336 
    337     // If the client is only demanding bits that we know, return the known
    338     // constant.
    339     if ((DemandedMask & (IKnownZero|IKnownOne)) == DemandedMask)
    340       return Constant::getIntegerValue(VTy, IKnownOne);
    341 
    342     // If all of the demanded bits are known zero on one side, return the other.
    343     // These bits cannot contribute to the result of the 'xor'.
    344     if ((DemandedMask & RHSKnownZero) == DemandedMask)
    345       return I->getOperand(0);
    346     if ((DemandedMask & LHSKnownZero) == DemandedMask)
    347       return I->getOperand(1);
    348 
    349     // If all of the demanded bits are known to be zero on one side or the
    350     // other, turn this into an *inclusive* or.
    351     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
    352     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
    353       Instruction *Or =
    354         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
    355                                  I->getName());
    356       return InsertNewInstWith(Or, *I);
    357     }
    358 
    359     // If all of the demanded bits on one side are known, and all of the set
    360     // bits on that side are also known to be set on the other side, turn this
    361     // into an AND, as we know the bits will be cleared.
    362     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
    363     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
    364       // all known
    365       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
    366         Constant *AndC = Constant::getIntegerValue(VTy,
    367                                                    ~RHSKnownOne & DemandedMask);
    368         Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
    369         return InsertNewInstWith(And, *I);
    370       }
    371     }
    372 
    373     // If the RHS is a constant, see if we can simplify it.
    374     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
    375     if (ShrinkDemandedConstant(I, 1, DemandedMask))
    376       return I;
    377 
    378     // If our LHS is an 'and' and if it has one use, and if any of the bits we
    379     // are flipping are known to be set, then the xor is just resetting those
    380     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
    381     // simplifying both of them.
    382     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
    383       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
    384           isa<ConstantInt>(I->getOperand(1)) &&
    385           isa<ConstantInt>(LHSInst->getOperand(1)) &&
    386           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
    387         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
    388         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
    389         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
    390 
    391         Constant *AndC =
    392           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
    393         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
    394         InsertNewInstWith(NewAnd, *I);
    395 
    396         Constant *XorC =
    397           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
    398         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
    399         return InsertNewInstWith(NewXor, *I);
    400       }
    401 
    402     // Output known-0 bits are known if clear or set in both the LHS & RHS.
    403     KnownZero= (RHSKnownZero & LHSKnownZero) | (RHSKnownOne & LHSKnownOne);
    404     // Output known-1 are known to be set if set in only one of the LHS, RHS.
    405     KnownOne = (RHSKnownZero & LHSKnownOne) | (RHSKnownOne & LHSKnownZero);
    406     break;
    407   }
    408   case Instruction::Select:
    409     // If this is a select as part of a min/max pattern, don't simplify any
    410     // further in case we break the structure.
    411     Value *LHS, *RHS;
    412     if (matchSelectPattern(I, LHS, RHS).Flavor != SPF_UNKNOWN)
    413       return nullptr;
    414 
    415     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask, RHSKnownZero,
    416                              RHSKnownOne, Depth + 1) ||
    417         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, LHSKnownZero,
    418                              LHSKnownOne, Depth + 1))
    419       return I;
    420     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
    421     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
    422 
    423     // If the operands are constants, see if we can simplify them.
    424     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
    425         ShrinkDemandedConstant(I, 2, DemandedMask))
    426       return I;
    427 
    428     // Only known if known in both the LHS and RHS.
    429     KnownOne = RHSKnownOne & LHSKnownOne;
    430     KnownZero = RHSKnownZero & LHSKnownZero;
    431     break;
    432   case Instruction::Trunc: {
    433     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
    434     DemandedMask = DemandedMask.zext(truncBf);
    435     KnownZero = KnownZero.zext(truncBf);
    436     KnownOne = KnownOne.zext(truncBf);
    437     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, KnownZero,
    438                              KnownOne, Depth + 1))
    439       return I;
    440     DemandedMask = DemandedMask.trunc(BitWidth);
    441     KnownZero = KnownZero.trunc(BitWidth);
    442     KnownOne = KnownOne.trunc(BitWidth);
    443     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    444     break;
    445   }
    446   case Instruction::BitCast:
    447     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
    448       return nullptr;  // vector->int or fp->int?
    449 
    450     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
    451       if (VectorType *SrcVTy =
    452             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
    453         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
    454           // Don't touch a bitcast between vectors of different element counts.
    455           return nullptr;
    456       } else
    457         // Don't touch a scalar-to-vector bitcast.
    458         return nullptr;
    459     } else if (I->getOperand(0)->getType()->isVectorTy())
    460       // Don't touch a vector-to-scalar bitcast.
    461       return nullptr;
    462 
    463     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, KnownZero,
    464                              KnownOne, Depth + 1))
    465       return I;
    466     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    467     break;
    468   case Instruction::ZExt: {
    469     // Compute the bits in the result that are not present in the input.
    470     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
    471 
    472     DemandedMask = DemandedMask.trunc(SrcBitWidth);
    473     KnownZero = KnownZero.trunc(SrcBitWidth);
    474     KnownOne = KnownOne.trunc(SrcBitWidth);
    475     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, KnownZero,
    476                              KnownOne, Depth + 1))
    477       return I;
    478     DemandedMask = DemandedMask.zext(BitWidth);
    479     KnownZero = KnownZero.zext(BitWidth);
    480     KnownOne = KnownOne.zext(BitWidth);
    481     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    482     // The top bits are known to be zero.
    483     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
    484     break;
    485   }
    486   case Instruction::SExt: {
    487     // Compute the bits in the result that are not present in the input.
    488     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
    489 
    490     APInt InputDemandedBits = DemandedMask &
    491                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
    492 
    493     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
    494     // If any of the sign extended bits are demanded, we know that the sign
    495     // bit is demanded.
    496     if ((NewBits & DemandedMask) != 0)
    497       InputDemandedBits.setBit(SrcBitWidth-1);
    498 
    499     InputDemandedBits = InputDemandedBits.trunc(SrcBitWidth);
    500     KnownZero = KnownZero.trunc(SrcBitWidth);
    501     KnownOne = KnownOne.trunc(SrcBitWidth);
    502     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits, KnownZero,
    503                              KnownOne, Depth + 1))
    504       return I;
    505     InputDemandedBits = InputDemandedBits.zext(BitWidth);
    506     KnownZero = KnownZero.zext(BitWidth);
    507     KnownOne = KnownOne.zext(BitWidth);
    508     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    509 
    510     // If the sign bit of the input is known set or clear, then we know the
    511     // top bits of the result.
    512 
    513     // If the input sign bit is known zero, or if the NewBits are not demanded
    514     // convert this into a zero extension.
    515     if (KnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
    516       // Convert to ZExt cast
    517       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
    518       return InsertNewInstWith(NewCast, *I);
    519     } else if (KnownOne[SrcBitWidth-1]) {    // Input sign bit known set
    520       KnownOne |= NewBits;
    521     }
    522     break;
    523   }
    524   case Instruction::Add:
    525   case Instruction::Sub: {
    526     /// If the high-bits of an ADD/SUB are not demanded, then we do not care
    527     /// about the high bits of the operands.
    528     unsigned NLZ = DemandedMask.countLeadingZeros();
    529     if (NLZ > 0) {
    530       // Right fill the mask of bits for this ADD/SUB to demand the most
    531       // significant bit and all those below it.
    532       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
    533       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
    534                                LHSKnownZero, LHSKnownOne, Depth + 1) ||
    535           ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
    536           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
    537                                LHSKnownZero, LHSKnownOne, Depth + 1)) {
    538         // Disable the nsw and nuw flags here: We can no longer guarantee that
    539         // we won't wrap after simplification. Removing the nsw/nuw flags is
    540         // legal here because the top bit is not demanded.
    541         BinaryOperator &BinOP = *cast<BinaryOperator>(I);
    542         BinOP.setHasNoSignedWrap(false);
    543         BinOP.setHasNoUnsignedWrap(false);
    544         return I;
    545       }
    546     }
    547 
    548     // Otherwise just hand the add/sub off to computeKnownBits to fill in
    549     // the known zeros and ones.
    550     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
    551     break;
    552   }
    553   case Instruction::Shl:
    554     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
    555       {
    556         Value *VarX; ConstantInt *C1;
    557         if (match(I->getOperand(0), m_Shr(m_Value(VarX), m_ConstantInt(C1)))) {
    558           Instruction *Shr = cast<Instruction>(I->getOperand(0));
    559           Value *R = SimplifyShrShlDemandedBits(Shr, I, DemandedMask,
    560                                                 KnownZero, KnownOne);
    561           if (R)
    562             return R;
    563         }
    564       }
    565 
    566       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
    567       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
    568 
    569       // If the shift is NUW/NSW, then it does demand the high bits.
    570       ShlOperator *IOp = cast<ShlOperator>(I);
    571       if (IOp->hasNoSignedWrap())
    572         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
    573       else if (IOp->hasNoUnsignedWrap())
    574         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
    575 
    576       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
    577                                KnownOne, Depth + 1))
    578         return I;
    579       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    580       KnownZero <<= ShiftAmt;
    581       KnownOne  <<= ShiftAmt;
    582       // low bits known zero.
    583       if (ShiftAmt)
    584         KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
    585     }
    586     break;
    587   case Instruction::LShr:
    588     // For a logical shift right
    589     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
    590       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
    591 
    592       // Unsigned shift right.
    593       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
    594 
    595       // If the shift is exact, then it does demand the low bits (and knows that
    596       // they are zero).
    597       if (cast<LShrOperator>(I)->isExact())
    598         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
    599 
    600       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
    601                                KnownOne, Depth + 1))
    602         return I;
    603       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    604       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
    605       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
    606       if (ShiftAmt) {
    607         // Compute the new bits that are at the top now.
    608         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
    609         KnownZero |= HighBits;  // high bits known zero.
    610       }
    611     }
    612     break;
    613   case Instruction::AShr:
    614     // If this is an arithmetic shift right and only the low-bit is set, we can
    615     // always convert this into a logical shr, even if the shift amount is
    616     // variable.  The low bit of the shift cannot be an input sign bit unless
    617     // the shift amount is >= the size of the datatype, which is undefined.
    618     if (DemandedMask == 1) {
    619       // Perform the logical shift right.
    620       Instruction *NewVal = BinaryOperator::CreateLShr(
    621                         I->getOperand(0), I->getOperand(1), I->getName());
    622       return InsertNewInstWith(NewVal, *I);
    623     }
    624 
    625     // If the sign bit is the only bit demanded by this ashr, then there is no
    626     // need to do it, the shift doesn't change the high bit.
    627     if (DemandedMask.isSignBit())
    628       return I->getOperand(0);
    629 
    630     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
    631       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
    632 
    633       // Signed shift right.
    634       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
    635       // If any of the "high bits" are demanded, we should set the sign bit as
    636       // demanded.
    637       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
    638         DemandedMaskIn.setBit(BitWidth-1);
    639 
    640       // If the shift is exact, then it does demand the low bits (and knows that
    641       // they are zero).
    642       if (cast<AShrOperator>(I)->isExact())
    643         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
    644 
    645       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
    646                                KnownOne, Depth + 1))
    647         return I;
    648       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    649       // Compute the new bits that are at the top now.
    650       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
    651       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
    652       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
    653 
    654       // Handle the sign bits.
    655       APInt SignBit(APInt::getSignBit(BitWidth));
    656       // Adjust to where it is now in the mask.
    657       SignBit = APIntOps::lshr(SignBit, ShiftAmt);
    658 
    659       // If the input sign bit is known to be zero, or if none of the top bits
    660       // are demanded, turn this into an unsigned shift right.
    661       if (BitWidth <= ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||
    662           (HighBits & ~DemandedMask) == HighBits) {
    663         // Perform the logical shift right.
    664         BinaryOperator *NewVal = BinaryOperator::CreateLShr(I->getOperand(0),
    665                                                             SA, I->getName());
    666         NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
    667         return InsertNewInstWith(NewVal, *I);
    668       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
    669         KnownOne |= HighBits;
    670       }
    671     }
    672     break;
    673   case Instruction::SRem:
    674     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
    675       // X % -1 demands all the bits because we don't want to introduce
    676       // INT_MIN % -1 (== undef) by accident.
    677       if (Rem->isAllOnesValue())
    678         break;
    679       APInt RA = Rem->getValue().abs();
    680       if (RA.isPowerOf2()) {
    681         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
    682           return I->getOperand(0);
    683 
    684         APInt LowBits = RA - 1;
    685         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
    686         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2, LHSKnownZero,
    687                                  LHSKnownOne, Depth + 1))
    688           return I;
    689 
    690         // The low bits of LHS are unchanged by the srem.
    691         KnownZero = LHSKnownZero & LowBits;
    692         KnownOne = LHSKnownOne & LowBits;
    693 
    694         // If LHS is non-negative or has all low bits zero, then the upper bits
    695         // are all zero.
    696         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
    697           KnownZero |= ~LowBits;
    698 
    699         // If LHS is negative and not all low bits are zero, then the upper bits
    700         // are all one.
    701         if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
    702           KnownOne |= ~LowBits;
    703 
    704         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
    705       }
    706     }
    707 
    708     // The sign bit is the LHS's sign bit, except when the result of the
    709     // remainder is zero.
    710     if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
    711       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
    712       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
    713                        CxtI);
    714       // If it's known zero, our sign bit is also zero.
    715       if (LHSKnownZero.isNegative())
    716         KnownZero.setBit(KnownZero.getBitWidth() - 1);
    717     }
    718     break;
    719   case Instruction::URem: {
    720     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
    721     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
    722     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes, KnownZero2,
    723                              KnownOne2, Depth + 1) ||
    724         SimplifyDemandedBits(I->getOperandUse(1), AllOnes, KnownZero2,
    725                              KnownOne2, Depth + 1))
    726       return I;
    727 
    728     unsigned Leaders = KnownZero2.countLeadingOnes();
    729     Leaders = std::max(Leaders,
    730                        KnownZero2.countLeadingOnes());
    731     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
    732     break;
    733   }
    734   case Instruction::Call:
    735     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
    736       switch (II->getIntrinsicID()) {
    737       default: break;
    738       case Intrinsic::bswap: {
    739         // If the only bits demanded come from one byte of the bswap result,
    740         // just shift the input byte into position to eliminate the bswap.
    741         unsigned NLZ = DemandedMask.countLeadingZeros();
    742         unsigned NTZ = DemandedMask.countTrailingZeros();
    743 
    744         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
    745         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
    746         // have 14 leading zeros, round to 8.
    747         NLZ &= ~7;
    748         NTZ &= ~7;
    749         // If we need exactly one byte, we can do this transformation.
    750         if (BitWidth-NLZ-NTZ == 8) {
    751           unsigned ResultBit = NTZ;
    752           unsigned InputBit = BitWidth-NTZ-8;
    753 
    754           // Replace this with either a left or right shift to get the byte into
    755           // the right place.
    756           Instruction *NewVal;
    757           if (InputBit > ResultBit)
    758             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
    759                     ConstantInt::get(I->getType(), InputBit-ResultBit));
    760           else
    761             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
    762                     ConstantInt::get(I->getType(), ResultBit-InputBit));
    763           NewVal->takeName(I);
    764           return InsertNewInstWith(NewVal, *I);
    765         }
    766 
    767         // TODO: Could compute known zero/one bits based on the input.
    768         break;
    769       }
    770       case Intrinsic::x86_mmx_pmovmskb:
    771       case Intrinsic::x86_sse_movmsk_ps:
    772       case Intrinsic::x86_sse2_movmsk_pd:
    773       case Intrinsic::x86_sse2_pmovmskb_128:
    774       case Intrinsic::x86_avx_movmsk_ps_256:
    775       case Intrinsic::x86_avx_movmsk_pd_256:
    776       case Intrinsic::x86_avx2_pmovmskb: {
    777         // MOVMSK copies the vector elements' sign bits to the low bits
    778         // and zeros the high bits.
    779         unsigned ArgWidth;
    780         if (II->getIntrinsicID() == Intrinsic::x86_mmx_pmovmskb) {
    781           ArgWidth = 8; // Arg is x86_mmx, but treated as <8 x i8>.
    782         } else {
    783           auto Arg = II->getArgOperand(0);
    784           auto ArgType = cast<VectorType>(Arg->getType());
    785           ArgWidth = ArgType->getNumElements();
    786         }
    787 
    788         // If we don't need any of low bits then return zero,
    789         // we know that DemandedMask is non-zero already.
    790         APInt DemandedElts = DemandedMask.zextOrTrunc(ArgWidth);
    791         if (DemandedElts == 0)
    792           return ConstantInt::getNullValue(VTy);
    793 
    794         // We know that the upper bits are set to zero.
    795         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - ArgWidth);
    796         return nullptr;
    797       }
    798       case Intrinsic::x86_sse42_crc32_64_64:
    799         KnownZero = APInt::getHighBitsSet(64, 32);
    800         return nullptr;
    801       }
    802     }
    803     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
    804     break;
    805   }
    806 
    807   // If the client is only demanding bits that we know, return the known
    808   // constant.
    809   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
    810     return Constant::getIntegerValue(VTy, KnownOne);
    811   return nullptr;
    812 }
    813 
    814 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
    815 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
    816 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
    817 /// of "C2-C1".
    818 ///
    819 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
    820 /// ..., bn}, without considering the specific value X is holding.
    821 /// This transformation is legal iff one of following conditions is hold:
    822 ///  1) All the bit in S are 0, in this case E1 == E2.
    823 ///  2) We don't care those bits in S, per the input DemandedMask.
    824 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
    825 ///     rest bits.
    826 ///
    827 /// Currently we only test condition 2).
    828 ///
    829 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
    830 /// not successful.
    831 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
    832                                                 Instruction *Shl,
    833                                                 const APInt &DemandedMask,
    834                                                 APInt &KnownZero,
    835                                                 APInt &KnownOne) {
    836 
    837   const APInt &ShlOp1 = cast<ConstantInt>(Shl->getOperand(1))->getValue();
    838   const APInt &ShrOp1 = cast<ConstantInt>(Shr->getOperand(1))->getValue();
    839   if (!ShlOp1 || !ShrOp1)
    840       return nullptr; // Noop.
    841 
    842   Value *VarX = Shr->getOperand(0);
    843   Type *Ty = VarX->getType();
    844   unsigned BitWidth = Ty->getIntegerBitWidth();
    845   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
    846     return nullptr; // Undef.
    847 
    848   unsigned ShlAmt = ShlOp1.getZExtValue();
    849   unsigned ShrAmt = ShrOp1.getZExtValue();
    850 
    851   KnownOne.clearAllBits();
    852   KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
    853   KnownZero &= DemandedMask;
    854 
    855   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
    856   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
    857 
    858   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
    859   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
    860                       (BitMask1.ashr(ShrAmt) << ShlAmt);
    861 
    862   if (ShrAmt <= ShlAmt) {
    863     BitMask2 <<= (ShlAmt - ShrAmt);
    864   } else {
    865     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
    866                         BitMask2.ashr(ShrAmt - ShlAmt);
    867   }
    868 
    869   // Check if condition-2 (see the comment to this function) is satified.
    870   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
    871     if (ShrAmt == ShlAmt)
    872       return VarX;
    873 
    874     if (!Shr->hasOneUse())
    875       return nullptr;
    876 
    877     BinaryOperator *New;
    878     if (ShrAmt < ShlAmt) {
    879       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
    880       New = BinaryOperator::CreateShl(VarX, Amt);
    881       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
    882       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
    883       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
    884     } else {
    885       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
    886       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
    887                      BinaryOperator::CreateAShr(VarX, Amt);
    888       if (cast<BinaryOperator>(Shr)->isExact())
    889         New->setIsExact(true);
    890     }
    891 
    892     return InsertNewInstWith(New, *Shl);
    893   }
    894 
    895   return nullptr;
    896 }
    897 
    898 /// The specified value produces a vector with any number of elements.
    899 /// DemandedElts contains the set of elements that are actually used by the
    900 /// caller. This method analyzes which elements of the operand are undef and
    901 /// returns that information in UndefElts.
    902 ///
    903 /// If the information about demanded elements can be used to simplify the
    904 /// operation, the operation is simplified, then the resultant value is
    905 /// returned.  This returns null if no change was made.
    906 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
    907                                                 APInt &UndefElts,
    908                                                 unsigned Depth) {
    909   unsigned VWidth = V->getType()->getVectorNumElements();
    910   APInt EltMask(APInt::getAllOnesValue(VWidth));
    911   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
    912 
    913   if (isa<UndefValue>(V)) {
    914     // If the entire vector is undefined, just return this info.
    915     UndefElts = EltMask;
    916     return nullptr;
    917   }
    918 
    919   if (DemandedElts == 0) { // If nothing is demanded, provide undef.
    920     UndefElts = EltMask;
    921     return UndefValue::get(V->getType());
    922   }
    923 
    924   UndefElts = 0;
    925 
    926   // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
    927   if (Constant *C = dyn_cast<Constant>(V)) {
    928     // Check if this is identity. If so, return 0 since we are not simplifying
    929     // anything.
    930     if (DemandedElts.isAllOnesValue())
    931       return nullptr;
    932 
    933     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
    934     Constant *Undef = UndefValue::get(EltTy);
    935 
    936     SmallVector<Constant*, 16> Elts;
    937     for (unsigned i = 0; i != VWidth; ++i) {
    938       if (!DemandedElts[i]) {   // If not demanded, set to undef.
    939         Elts.push_back(Undef);
    940         UndefElts.setBit(i);
    941         continue;
    942       }
    943 
    944       Constant *Elt = C->getAggregateElement(i);
    945       if (!Elt) return nullptr;
    946 
    947       if (isa<UndefValue>(Elt)) {   // Already undef.
    948         Elts.push_back(Undef);
    949         UndefElts.setBit(i);
    950       } else {                               // Otherwise, defined.
    951         Elts.push_back(Elt);
    952       }
    953     }
    954 
    955     // If we changed the constant, return it.
    956     Constant *NewCV = ConstantVector::get(Elts);
    957     return NewCV != C ? NewCV : nullptr;
    958   }
    959 
    960   // Limit search depth.
    961   if (Depth == 10)
    962     return nullptr;
    963 
    964   // If multiple users are using the root value, proceed with
    965   // simplification conservatively assuming that all elements
    966   // are needed.
    967   if (!V->hasOneUse()) {
    968     // Quit if we find multiple users of a non-root value though.
    969     // They'll be handled when it's their turn to be visited by
    970     // the main instcombine process.
    971     if (Depth != 0)
    972       // TODO: Just compute the UndefElts information recursively.
    973       return nullptr;
    974 
    975     // Conservatively assume that all elements are needed.
    976     DemandedElts = EltMask;
    977   }
    978 
    979   Instruction *I = dyn_cast<Instruction>(V);
    980   if (!I) return nullptr;        // Only analyze instructions.
    981 
    982   bool MadeChange = false;
    983   APInt UndefElts2(VWidth, 0);
    984   Value *TmpV;
    985   switch (I->getOpcode()) {
    986   default: break;
    987 
    988   case Instruction::InsertElement: {
    989     // If this is a variable index, we don't know which element it overwrites.
    990     // demand exactly the same input as we produce.
    991     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
    992     if (!Idx) {
    993       // Note that we can't propagate undef elt info, because we don't know
    994       // which elt is getting updated.
    995       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
    996                                         UndefElts2, Depth + 1);
    997       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
    998       break;
    999     }
   1000 
   1001     // If this is inserting an element that isn't demanded, remove this
   1002     // insertelement.
   1003     unsigned IdxNo = Idx->getZExtValue();
   1004     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
   1005       Worklist.Add(I);
   1006       return I->getOperand(0);
   1007     }
   1008 
   1009     // Otherwise, the element inserted overwrites whatever was there, so the
   1010     // input demanded set is simpler than the output set.
   1011     APInt DemandedElts2 = DemandedElts;
   1012     DemandedElts2.clearBit(IdxNo);
   1013     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
   1014                                       UndefElts, Depth + 1);
   1015     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
   1016 
   1017     // The inserted element is defined.
   1018     UndefElts.clearBit(IdxNo);
   1019     break;
   1020   }
   1021   case Instruction::ShuffleVector: {
   1022     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
   1023     uint64_t LHSVWidth =
   1024       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
   1025     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
   1026     for (unsigned i = 0; i < VWidth; i++) {
   1027       if (DemandedElts[i]) {
   1028         unsigned MaskVal = Shuffle->getMaskValue(i);
   1029         if (MaskVal != -1u) {
   1030           assert(MaskVal < LHSVWidth * 2 &&
   1031                  "shufflevector mask index out of range!");
   1032           if (MaskVal < LHSVWidth)
   1033             LeftDemanded.setBit(MaskVal);
   1034           else
   1035             RightDemanded.setBit(MaskVal - LHSVWidth);
   1036         }
   1037       }
   1038     }
   1039 
   1040     APInt UndefElts4(LHSVWidth, 0);
   1041     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
   1042                                       UndefElts4, Depth + 1);
   1043     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
   1044 
   1045     APInt UndefElts3(LHSVWidth, 0);
   1046     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
   1047                                       UndefElts3, Depth + 1);
   1048     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
   1049 
   1050     bool NewUndefElts = false;
   1051     for (unsigned i = 0; i < VWidth; i++) {
   1052       unsigned MaskVal = Shuffle->getMaskValue(i);
   1053       if (MaskVal == -1u) {
   1054         UndefElts.setBit(i);
   1055       } else if (!DemandedElts[i]) {
   1056         NewUndefElts = true;
   1057         UndefElts.setBit(i);
   1058       } else if (MaskVal < LHSVWidth) {
   1059         if (UndefElts4[MaskVal]) {
   1060           NewUndefElts = true;
   1061           UndefElts.setBit(i);
   1062         }
   1063       } else {
   1064         if (UndefElts3[MaskVal - LHSVWidth]) {
   1065           NewUndefElts = true;
   1066           UndefElts.setBit(i);
   1067         }
   1068       }
   1069     }
   1070 
   1071     if (NewUndefElts) {
   1072       // Add additional discovered undefs.
   1073       SmallVector<Constant*, 16> Elts;
   1074       for (unsigned i = 0; i < VWidth; ++i) {
   1075         if (UndefElts[i])
   1076           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
   1077         else
   1078           Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
   1079                                           Shuffle->getMaskValue(i)));
   1080       }
   1081       I->setOperand(2, ConstantVector::get(Elts));
   1082       MadeChange = true;
   1083     }
   1084     break;
   1085   }
   1086   case Instruction::Select: {
   1087     APInt LeftDemanded(DemandedElts), RightDemanded(DemandedElts);
   1088     if (ConstantVector* CV = dyn_cast<ConstantVector>(I->getOperand(0))) {
   1089       for (unsigned i = 0; i < VWidth; i++) {
   1090         Constant *CElt = CV->getAggregateElement(i);
   1091         // Method isNullValue always returns false when called on a
   1092         // ConstantExpr. If CElt is a ConstantExpr then skip it in order to
   1093         // to avoid propagating incorrect information.
   1094         if (isa<ConstantExpr>(CElt))
   1095           continue;
   1096         if (CElt->isNullValue())
   1097           LeftDemanded.clearBit(i);
   1098         else
   1099           RightDemanded.clearBit(i);
   1100       }
   1101     }
   1102 
   1103     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded, UndefElts,
   1104                                       Depth + 1);
   1105     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
   1106 
   1107     TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
   1108                                       UndefElts2, Depth + 1);
   1109     if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
   1110 
   1111     // Output elements are undefined if both are undefined.
   1112     UndefElts &= UndefElts2;
   1113     break;
   1114   }
   1115   case Instruction::BitCast: {
   1116     // Vector->vector casts only.
   1117     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
   1118     if (!VTy) break;
   1119     unsigned InVWidth = VTy->getNumElements();
   1120     APInt InputDemandedElts(InVWidth, 0);
   1121     UndefElts2 = APInt(InVWidth, 0);
   1122     unsigned Ratio;
   1123 
   1124     if (VWidth == InVWidth) {
   1125       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
   1126       // elements as are demanded of us.
   1127       Ratio = 1;
   1128       InputDemandedElts = DemandedElts;
   1129     } else if ((VWidth % InVWidth) == 0) {
   1130       // If the number of elements in the output is a multiple of the number of
   1131       // elements in the input then an input element is live if any of the
   1132       // corresponding output elements are live.
   1133       Ratio = VWidth / InVWidth;
   1134       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
   1135         if (DemandedElts[OutIdx])
   1136           InputDemandedElts.setBit(OutIdx / Ratio);
   1137     } else if ((InVWidth % VWidth) == 0) {
   1138       // If the number of elements in the input is a multiple of the number of
   1139       // elements in the output then an input element is live if the
   1140       // corresponding output element is live.
   1141       Ratio = InVWidth / VWidth;
   1142       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
   1143         if (DemandedElts[InIdx / Ratio])
   1144           InputDemandedElts.setBit(InIdx);
   1145     } else {
   1146       // Unsupported so far.
   1147       break;
   1148     }
   1149 
   1150     // div/rem demand all inputs, because they don't want divide by zero.
   1151     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
   1152                                       UndefElts2, Depth + 1);
   1153     if (TmpV) {
   1154       I->setOperand(0, TmpV);
   1155       MadeChange = true;
   1156     }
   1157 
   1158     if (VWidth == InVWidth) {
   1159       UndefElts = UndefElts2;
   1160     } else if ((VWidth % InVWidth) == 0) {
   1161       // If the number of elements in the output is a multiple of the number of
   1162       // elements in the input then an output element is undef if the
   1163       // corresponding input element is undef.
   1164       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
   1165         if (UndefElts2[OutIdx / Ratio])
   1166           UndefElts.setBit(OutIdx);
   1167     } else if ((InVWidth % VWidth) == 0) {
   1168       // If the number of elements in the input is a multiple of the number of
   1169       // elements in the output then an output element is undef if all of the
   1170       // corresponding input elements are undef.
   1171       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
   1172         APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
   1173         if (SubUndef.countPopulation() == Ratio)
   1174           UndefElts.setBit(OutIdx);
   1175       }
   1176     } else {
   1177       llvm_unreachable("Unimp");
   1178     }
   1179     break;
   1180   }
   1181   case Instruction::And:
   1182   case Instruction::Or:
   1183   case Instruction::Xor:
   1184   case Instruction::Add:
   1185   case Instruction::Sub:
   1186   case Instruction::Mul:
   1187     // div/rem demand all inputs, because they don't want divide by zero.
   1188     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts, UndefElts,
   1189                                       Depth + 1);
   1190     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
   1191     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
   1192                                       UndefElts2, Depth + 1);
   1193     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
   1194 
   1195     // Output elements are undefined if both are undefined.  Consider things
   1196     // like undef&0.  The result is known zero, not undef.
   1197     UndefElts &= UndefElts2;
   1198     break;
   1199   case Instruction::FPTrunc:
   1200   case Instruction::FPExt:
   1201     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts, UndefElts,
   1202                                       Depth + 1);
   1203     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
   1204     break;
   1205 
   1206   case Instruction::Call: {
   1207     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
   1208     if (!II) break;
   1209     switch (II->getIntrinsicID()) {
   1210     default: break;
   1211 
   1212     // Unary scalar-as-vector operations that work column-wise.
   1213     case Intrinsic::x86_sse_rcp_ss:
   1214     case Intrinsic::x86_sse_rsqrt_ss:
   1215     case Intrinsic::x86_sse_sqrt_ss:
   1216     case Intrinsic::x86_sse2_sqrt_sd:
   1217     case Intrinsic::x86_xop_vfrcz_ss:
   1218     case Intrinsic::x86_xop_vfrcz_sd:
   1219       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
   1220                                         UndefElts, Depth + 1);
   1221       if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
   1222 
   1223       // If lowest element of a scalar op isn't used then use Arg0.
   1224       if (DemandedElts.getLoBits(1) != 1)
   1225         return II->getArgOperand(0);
   1226       // TODO: If only low elt lower SQRT to FSQRT (with rounding/exceptions
   1227       // checks).
   1228       break;
   1229 
   1230     // Binary scalar-as-vector operations that work column-wise.  A dest element
   1231     // is a function of the corresponding input elements from the two inputs.
   1232     case Intrinsic::x86_sse_add_ss:
   1233     case Intrinsic::x86_sse_sub_ss:
   1234     case Intrinsic::x86_sse_mul_ss:
   1235     case Intrinsic::x86_sse_div_ss:
   1236     case Intrinsic::x86_sse_min_ss:
   1237     case Intrinsic::x86_sse_max_ss:
   1238     case Intrinsic::x86_sse_cmp_ss:
   1239     case Intrinsic::x86_sse2_add_sd:
   1240     case Intrinsic::x86_sse2_sub_sd:
   1241     case Intrinsic::x86_sse2_mul_sd:
   1242     case Intrinsic::x86_sse2_div_sd:
   1243     case Intrinsic::x86_sse2_min_sd:
   1244     case Intrinsic::x86_sse2_max_sd:
   1245     case Intrinsic::x86_sse2_cmp_sd:
   1246     case Intrinsic::x86_sse41_round_ss:
   1247     case Intrinsic::x86_sse41_round_sd:
   1248       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
   1249                                         UndefElts, Depth + 1);
   1250       if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
   1251       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(1), DemandedElts,
   1252                                         UndefElts2, Depth + 1);
   1253       if (TmpV) { II->setArgOperand(1, TmpV); MadeChange = true; }
   1254 
   1255       // If only the low elt is demanded and this is a scalarizable intrinsic,
   1256       // scalarize it now.
   1257       if (DemandedElts == 1) {
   1258         switch (II->getIntrinsicID()) {
   1259         default: break;
   1260         case Intrinsic::x86_sse_add_ss:
   1261         case Intrinsic::x86_sse_sub_ss:
   1262         case Intrinsic::x86_sse_mul_ss:
   1263         case Intrinsic::x86_sse_div_ss:
   1264         case Intrinsic::x86_sse2_add_sd:
   1265         case Intrinsic::x86_sse2_sub_sd:
   1266         case Intrinsic::x86_sse2_mul_sd:
   1267         case Intrinsic::x86_sse2_div_sd:
   1268           // TODO: Lower MIN/MAX/etc.
   1269           Value *LHS = II->getArgOperand(0);
   1270           Value *RHS = II->getArgOperand(1);
   1271           // Extract the element as scalars.
   1272           LHS = InsertNewInstWith(ExtractElementInst::Create(LHS,
   1273             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
   1274           RHS = InsertNewInstWith(ExtractElementInst::Create(RHS,
   1275             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
   1276 
   1277           switch (II->getIntrinsicID()) {
   1278           default: llvm_unreachable("Case stmts out of sync!");
   1279           case Intrinsic::x86_sse_add_ss:
   1280           case Intrinsic::x86_sse2_add_sd:
   1281             TmpV = InsertNewInstWith(BinaryOperator::CreateFAdd(LHS, RHS,
   1282                                                         II->getName()), *II);
   1283             break;
   1284           case Intrinsic::x86_sse_sub_ss:
   1285           case Intrinsic::x86_sse2_sub_sd:
   1286             TmpV = InsertNewInstWith(BinaryOperator::CreateFSub(LHS, RHS,
   1287                                                         II->getName()), *II);
   1288             break;
   1289           case Intrinsic::x86_sse_mul_ss:
   1290           case Intrinsic::x86_sse2_mul_sd:
   1291             TmpV = InsertNewInstWith(BinaryOperator::CreateFMul(LHS, RHS,
   1292                                                          II->getName()), *II);
   1293             break;
   1294           case Intrinsic::x86_sse_div_ss:
   1295           case Intrinsic::x86_sse2_div_sd:
   1296             TmpV = InsertNewInstWith(BinaryOperator::CreateFDiv(LHS, RHS,
   1297                                                          II->getName()), *II);
   1298             break;
   1299           }
   1300 
   1301           Instruction *New =
   1302             InsertElementInst::Create(
   1303               UndefValue::get(II->getType()), TmpV,
   1304               ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
   1305                                       II->getName());
   1306           InsertNewInstWith(New, *II);
   1307           return New;
   1308         }
   1309       }
   1310 
   1311       // If lowest element of a scalar op isn't used then use Arg0.
   1312       if (DemandedElts.getLoBits(1) != 1)
   1313         return II->getArgOperand(0);
   1314 
   1315       // Output elements are undefined if both are undefined.  Consider things
   1316       // like undef&0.  The result is known zero, not undef.
   1317       UndefElts &= UndefElts2;
   1318       break;
   1319 
   1320     // SSE4A instructions leave the upper 64-bits of the 128-bit result
   1321     // in an undefined state.
   1322     case Intrinsic::x86_sse4a_extrq:
   1323     case Intrinsic::x86_sse4a_extrqi:
   1324     case Intrinsic::x86_sse4a_insertq:
   1325     case Intrinsic::x86_sse4a_insertqi:
   1326       UndefElts |= APInt::getHighBitsSet(VWidth, VWidth / 2);
   1327       break;
   1328     }
   1329     break;
   1330   }
   1331   }
   1332   return MadeChange ? I : nullptr;
   1333 }
   1334