LLVM  mainline
InstCombineAndOrXor.cpp
Go to the documentation of this file.
00001 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitAnd, visitOr, and visitXor functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombineInternal.h"
00015 #include "llvm/Analysis/InstructionSimplify.h"
00016 #include "llvm/IR/ConstantRange.h"
00017 #include "llvm/IR/Intrinsics.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
00020 #include "llvm/Transforms/Utils/Local.h"
00021 using namespace llvm;
00022 using namespace PatternMatch;
00023 
00024 #define DEBUG_TYPE "instcombine"
00025 
00026 static inline Value *dyn_castNotVal(Value *V) {
00027   // If this is not(not(x)) don't return that this is a not: we want the two
00028   // not's to be folded first.
00029   if (BinaryOperator::isNot(V)) {
00030     Value *Operand = BinaryOperator::getNotArgument(V);
00031     if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
00032       return Operand;
00033   }
00034 
00035   // Constants can be considered to be not'ed values...
00036   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
00037     return ConstantInt::get(C->getType(), ~C->getValue());
00038   return nullptr;
00039 }
00040 
00041 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
00042 /// a three bit mask. It also returns whether it is an ordered predicate by
00043 /// reference.
00044 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
00045   isOrdered = false;
00046   switch (CC) {
00047   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
00048   case FCmpInst::FCMP_UNO:                   return 0;  // 000
00049   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
00050   case FCmpInst::FCMP_UGT:                   return 1;  // 001
00051   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
00052   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
00053   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
00054   case FCmpInst::FCMP_UGE:                   return 3;  // 011
00055   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
00056   case FCmpInst::FCMP_ULT:                   return 4;  // 100
00057   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
00058   case FCmpInst::FCMP_UNE:                   return 5;  // 101
00059   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
00060   case FCmpInst::FCMP_ULE:                   return 6;  // 110
00061     // True -> 7
00062   default:
00063     // Not expecting FCMP_FALSE and FCMP_TRUE;
00064     llvm_unreachable("Unexpected FCmp predicate!");
00065   }
00066 }
00067 
00068 /// This is the complement of getICmpCode, which turns an opcode and two
00069 /// operands into either a constant true or false, or a brand new ICmp
00070 /// instruction. The sign is passed in to determine which kind of predicate to
00071 /// use in the new icmp instruction.
00072 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
00073                               InstCombiner::BuilderTy *Builder) {
00074   ICmpInst::Predicate NewPred;
00075   if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
00076     return NewConstant;
00077   return Builder->CreateICmp(NewPred, LHS, RHS);
00078 }
00079 
00080 /// This is the complement of getFCmpCode, which turns an opcode and two
00081 /// operands into either a FCmp instruction. isordered is passed in to determine
00082 /// which kind of predicate to use in the new fcmp instruction.
00083 static Value *getFCmpValue(bool isordered, unsigned code,
00084                            Value *LHS, Value *RHS,
00085                            InstCombiner::BuilderTy *Builder) {
00086   CmpInst::Predicate Pred;
00087   switch (code) {
00088   default: llvm_unreachable("Illegal FCmp code!");
00089   case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
00090   case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
00091   case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
00092   case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
00093   case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
00094   case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
00095   case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
00096   case 7:
00097     if (!isordered)
00098       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
00099     Pred = FCmpInst::FCMP_ORD; break;
00100   }
00101   return Builder->CreateFCmp(Pred, LHS, RHS);
00102 }
00103 
00104 /// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
00105 /// \param I Binary operator to transform.
00106 /// \return Pointer to node that must replace the original binary operator, or
00107 ///         null pointer if no transformation was made.
00108 Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
00109   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
00110 
00111   // Can't do vectors.
00112   if (I.getType()->isVectorTy()) return nullptr;
00113 
00114   // Can only do bitwise ops.
00115   unsigned Op = I.getOpcode();
00116   if (Op != Instruction::And && Op != Instruction::Or &&
00117       Op != Instruction::Xor)
00118     return nullptr;
00119 
00120   Value *OldLHS = I.getOperand(0);
00121   Value *OldRHS = I.getOperand(1);
00122   ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
00123   ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
00124   IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
00125   IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
00126   bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
00127   bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
00128 
00129   if (!IsBswapLHS && !IsBswapRHS)
00130     return nullptr;
00131 
00132   if (!IsBswapLHS && !ConstLHS)
00133     return nullptr;
00134 
00135   if (!IsBswapRHS && !ConstRHS)
00136     return nullptr;
00137 
00138   /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
00139   /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
00140   Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
00141                   Builder->getInt(ConstLHS->getValue().byteSwap());
00142 
00143   Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
00144                   Builder->getInt(ConstRHS->getValue().byteSwap());
00145 
00146   Value *BinOp = nullptr;
00147   if (Op == Instruction::And)
00148     BinOp = Builder->CreateAnd(NewLHS, NewRHS);
00149   else if (Op == Instruction::Or)
00150     BinOp = Builder->CreateOr(NewLHS, NewRHS);
00151   else //if (Op == Instruction::Xor)
00152     BinOp = Builder->CreateXor(NewLHS, NewRHS);
00153 
00154   Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
00155   return Builder->CreateCall(F, BinOp);
00156 }
00157 
00158 /// This handles expressions of the form ((val OP C1) & C2).  Where
00159 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
00160 /// guaranteed to be a binary operator.
00161 Instruction *InstCombiner::OptAndOp(Instruction *Op,
00162                                     ConstantInt *OpRHS,
00163                                     ConstantInt *AndRHS,
00164                                     BinaryOperator &TheAnd) {
00165   Value *X = Op->getOperand(0);
00166   Constant *Together = nullptr;
00167   if (!Op->isShift())
00168     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
00169 
00170   switch (Op->getOpcode()) {
00171   case Instruction::Xor:
00172     if (Op->hasOneUse()) {
00173       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
00174       Value *And = Builder->CreateAnd(X, AndRHS);
00175       And->takeName(Op);
00176       return BinaryOperator::CreateXor(And, Together);
00177     }
00178     break;
00179   case Instruction::Or:
00180     if (Op->hasOneUse()){
00181       if (Together != OpRHS) {
00182         // (X | C1) & C2 --> (X | (C1&C2)) & C2
00183         Value *Or = Builder->CreateOr(X, Together);
00184         Or->takeName(Op);
00185         return BinaryOperator::CreateAnd(Or, AndRHS);
00186       }
00187 
00188       ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
00189       if (TogetherCI && !TogetherCI->isZero()){
00190         // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
00191         // NOTE: This reduces the number of bits set in the & mask, which
00192         // can expose opportunities for store narrowing.
00193         Together = ConstantExpr::getXor(AndRHS, Together);
00194         Value *And = Builder->CreateAnd(X, Together);
00195         And->takeName(Op);
00196         return BinaryOperator::CreateOr(And, OpRHS);
00197       }
00198     }
00199 
00200     break;
00201   case Instruction::Add:
00202     if (Op->hasOneUse()) {
00203       // Adding a one to a single bit bit-field should be turned into an XOR
00204       // of the bit.  First thing to check is to see if this AND is with a
00205       // single bit constant.
00206       const APInt &AndRHSV = AndRHS->getValue();
00207 
00208       // If there is only one bit set.
00209       if (AndRHSV.isPowerOf2()) {
00210         // Ok, at this point, we know that we are masking the result of the
00211         // ADD down to exactly one bit.  If the constant we are adding has
00212         // no bits set below this bit, then we can eliminate the ADD.
00213         const APInt& AddRHS = OpRHS->getValue();
00214 
00215         // Check to see if any bits below the one bit set in AndRHSV are set.
00216         if ((AddRHS & (AndRHSV-1)) == 0) {
00217           // If not, the only thing that can effect the output of the AND is
00218           // the bit specified by AndRHSV.  If that bit is set, the effect of
00219           // the XOR is to toggle the bit.  If it is clear, then the ADD has
00220           // no effect.
00221           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
00222             TheAnd.setOperand(0, X);
00223             return &TheAnd;
00224           } else {
00225             // Pull the XOR out of the AND.
00226             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
00227             NewAnd->takeName(Op);
00228             return BinaryOperator::CreateXor(NewAnd, AndRHS);
00229           }
00230         }
00231       }
00232     }
00233     break;
00234 
00235   case Instruction::Shl: {
00236     // We know that the AND will not produce any of the bits shifted in, so if
00237     // the anded constant includes them, clear them now!
00238     //
00239     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
00240     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
00241     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
00242     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
00243 
00244     if (CI->getValue() == ShlMask)
00245       // Masking out bits that the shift already masks.
00246       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
00247 
00248     if (CI != AndRHS) {                  // Reducing bits set in and.
00249       TheAnd.setOperand(1, CI);
00250       return &TheAnd;
00251     }
00252     break;
00253   }
00254   case Instruction::LShr: {
00255     // We know that the AND will not produce any of the bits shifted in, so if
00256     // the anded constant includes them, clear them now!  This only applies to
00257     // unsigned shifts, because a signed shr may bring in set bits!
00258     //
00259     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
00260     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
00261     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
00262     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
00263 
00264     if (CI->getValue() == ShrMask)
00265       // Masking out bits that the shift already masks.
00266       return ReplaceInstUsesWith(TheAnd, Op);
00267 
00268     if (CI != AndRHS) {
00269       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
00270       return &TheAnd;
00271     }
00272     break;
00273   }
00274   case Instruction::AShr:
00275     // Signed shr.
00276     // See if this is shifting in some sign extension, then masking it out
00277     // with an and.
00278     if (Op->hasOneUse()) {
00279       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
00280       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
00281       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
00282       Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
00283       if (C == AndRHS) {          // Masking out bits shifted in.
00284         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
00285         // Make the argument unsigned.
00286         Value *ShVal = Op->getOperand(0);
00287         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
00288         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
00289       }
00290     }
00291     break;
00292   }
00293   return nullptr;
00294 }
00295 
00296 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
00297 /// (V < Lo || V >= Hi).  In practice, we emit the more efficient
00298 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
00299 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
00300 /// insert new instructions.
00301 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
00302                                      bool isSigned, bool Inside) {
00303   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
00304             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
00305          "Lo is not <= Hi in range emission code!");
00306 
00307   if (Inside) {
00308     if (Lo == Hi)  // Trivially false.
00309       return Builder->getFalse();
00310 
00311     // V >= Min && V < Hi --> V < Hi
00312     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
00313       ICmpInst::Predicate pred = (isSigned ?
00314         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
00315       return Builder->CreateICmp(pred, V, Hi);
00316     }
00317 
00318     // Emit V-Lo <u Hi-Lo
00319     Constant *NegLo = ConstantExpr::getNeg(Lo);
00320     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
00321     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
00322     return Builder->CreateICmpULT(Add, UpperBound);
00323   }
00324 
00325   if (Lo == Hi)  // Trivially true.
00326     return Builder->getTrue();
00327 
00328   // V < Min || V >= Hi -> V > Hi-1
00329   Hi = SubOne(cast<ConstantInt>(Hi));
00330   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
00331     ICmpInst::Predicate pred = (isSigned ?
00332         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
00333     return Builder->CreateICmp(pred, V, Hi);
00334   }
00335 
00336   // Emit V-Lo >u Hi-1-Lo
00337   // Note that Hi has already had one subtracted from it, above.
00338   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
00339   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
00340   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
00341   return Builder->CreateICmpUGT(Add, LowerBound);
00342 }
00343 
00344 /// Returns true iff Val consists of one contiguous run of 1s with any number
00345 /// of 0s on either side.  The 1s are allowed to wrap from LSB to MSB,
00346 /// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
00347 /// not, since all 1s are not contiguous.
00348 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
00349   const APInt& V = Val->getValue();
00350   uint32_t BitWidth = Val->getType()->getBitWidth();
00351   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
00352 
00353   // look for the first zero bit after the run of ones
00354   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
00355   // look for the first non-zero bit
00356   ME = V.getActiveBits();
00357   return true;
00358 }
00359 
00360 /// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
00361 /// whether the operator is a sub. If we can fold one of the following xforms:
00362 ///
00363 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
00364 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
00365 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
00366 ///
00367 /// return (A +/- B).
00368 ///
00369 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
00370                                         ConstantInt *Mask, bool isSub,
00371                                         Instruction &I) {
00372   Instruction *LHSI = dyn_cast<Instruction>(LHS);
00373   if (!LHSI || LHSI->getNumOperands() != 2 ||
00374       !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
00375 
00376   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
00377 
00378   switch (LHSI->getOpcode()) {
00379   default: return nullptr;
00380   case Instruction::And:
00381     if (ConstantExpr::getAnd(N, Mask) == Mask) {
00382       // If the AndRHS is a power of two minus one (0+1+), this is simple.
00383       if ((Mask->getValue().countLeadingZeros() +
00384            Mask->getValue().countPopulation()) ==
00385           Mask->getValue().getBitWidth())
00386         break;
00387 
00388       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
00389       // part, we don't need any explicit masks to take them out of A.  If that
00390       // is all N is, ignore it.
00391       uint32_t MB = 0, ME = 0;
00392       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
00393         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
00394         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
00395         if (MaskedValueIsZero(RHS, Mask, 0, &I))
00396           break;
00397       }
00398     }
00399     return nullptr;
00400   case Instruction::Or:
00401   case Instruction::Xor:
00402     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
00403     if ((Mask->getValue().countLeadingZeros() +
00404          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
00405         && ConstantExpr::getAnd(N, Mask)->isNullValue())
00406       break;
00407     return nullptr;
00408   }
00409 
00410   if (isSub)
00411     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
00412   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
00413 }
00414 
00415 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
00416 /// One of A and B is considered the mask, the other the value. This is
00417 /// described as the "AMask" or "BMask" part of the enum. If the enum
00418 /// contains only "Mask", then both A and B can be considered masks.
00419 /// If A is the mask, then it was proven, that (A & C) == C. This
00420 /// is trivial if C == A, or C == 0. If both A and C are constants, this
00421 /// proof is also easy.
00422 /// For the following explanations we assume that A is the mask.
00423 /// The part "AllOnes" declares, that the comparison is true only
00424 /// if (A & B) == A, or all bits of A are set in B.
00425 ///   Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
00426 /// The part "AllZeroes" declares, that the comparison is true only
00427 /// if (A & B) == 0, or all bits of A are cleared in B.
00428 ///   Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
00429 /// The part "Mixed" declares, that (A & B) == C and C might or might not
00430 /// contain any number of one bits and zero bits.
00431 ///   Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
00432 /// The Part "Not" means, that in above descriptions "==" should be replaced
00433 /// by "!=".
00434 ///   Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
00435 /// If the mask A contains a single bit, then the following is equivalent:
00436 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
00437 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
00438 enum MaskedICmpType {
00439   FoldMskICmp_AMask_AllOnes           =     1,
00440   FoldMskICmp_AMask_NotAllOnes        =     2,
00441   FoldMskICmp_BMask_AllOnes           =     4,
00442   FoldMskICmp_BMask_NotAllOnes        =     8,
00443   FoldMskICmp_Mask_AllZeroes          =    16,
00444   FoldMskICmp_Mask_NotAllZeroes       =    32,
00445   FoldMskICmp_AMask_Mixed             =    64,
00446   FoldMskICmp_AMask_NotMixed          =   128,
00447   FoldMskICmp_BMask_Mixed             =   256,
00448   FoldMskICmp_BMask_NotMixed          =   512
00449 };
00450 
00451 /// Return the set of pattern classes (from MaskedICmpType)
00452 /// that (icmp SCC (A & B), C) satisfies.
00453 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
00454                                     ICmpInst::Predicate SCC)
00455 {
00456   ConstantInt *ACst = dyn_cast<ConstantInt>(A);
00457   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
00458   ConstantInt *CCst = dyn_cast<ConstantInt>(C);
00459   bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
00460   bool icmp_abit = (ACst && !ACst->isZero() &&
00461                     ACst->getValue().isPowerOf2());
00462   bool icmp_bbit = (BCst && !BCst->isZero() &&
00463                     BCst->getValue().isPowerOf2());
00464   unsigned result = 0;
00465   if (CCst && CCst->isZero()) {
00466     // if C is zero, then both A and B qualify as mask
00467     result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
00468                           FoldMskICmp_Mask_AllZeroes |
00469                           FoldMskICmp_AMask_Mixed |
00470                           FoldMskICmp_BMask_Mixed)
00471                        : (FoldMskICmp_Mask_NotAllZeroes |
00472                           FoldMskICmp_Mask_NotAllZeroes |
00473                           FoldMskICmp_AMask_NotMixed |
00474                           FoldMskICmp_BMask_NotMixed));
00475     if (icmp_abit)
00476       result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
00477                             FoldMskICmp_AMask_NotMixed)
00478                          : (FoldMskICmp_AMask_AllOnes |
00479                             FoldMskICmp_AMask_Mixed));
00480     if (icmp_bbit)
00481       result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
00482                             FoldMskICmp_BMask_NotMixed)
00483                          : (FoldMskICmp_BMask_AllOnes |
00484                             FoldMskICmp_BMask_Mixed));
00485     return result;
00486   }
00487   if (A == C) {
00488     result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
00489                           FoldMskICmp_AMask_Mixed)
00490                        : (FoldMskICmp_AMask_NotAllOnes |
00491                           FoldMskICmp_AMask_NotMixed));
00492     if (icmp_abit)
00493       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
00494                             FoldMskICmp_AMask_NotMixed)
00495                          : (FoldMskICmp_Mask_AllZeroes |
00496                             FoldMskICmp_AMask_Mixed));
00497   } else if (ACst && CCst &&
00498              ConstantExpr::getAnd(ACst, CCst) == CCst) {
00499     result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
00500                        : FoldMskICmp_AMask_NotMixed);
00501   }
00502   if (B == C) {
00503     result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
00504                           FoldMskICmp_BMask_Mixed)
00505                        : (FoldMskICmp_BMask_NotAllOnes |
00506                           FoldMskICmp_BMask_NotMixed));
00507     if (icmp_bbit)
00508       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
00509                             FoldMskICmp_BMask_NotMixed)
00510                          : (FoldMskICmp_Mask_AllZeroes |
00511                             FoldMskICmp_BMask_Mixed));
00512   } else if (BCst && CCst &&
00513              ConstantExpr::getAnd(BCst, CCst) == CCst) {
00514     result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
00515                        : FoldMskICmp_BMask_NotMixed);
00516   }
00517   return result;
00518 }
00519 
00520 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
00521 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
00522 /// is adjacent to the corresponding normal flag (recording ==), this just
00523 /// involves swapping those bits over.
00524 static unsigned conjugateICmpMask(unsigned Mask) {
00525   unsigned NewMask;
00526   NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
00527                      FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
00528                      FoldMskICmp_BMask_Mixed))
00529             << 1;
00530 
00531   NewMask |=
00532       (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
00533                FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
00534                FoldMskICmp_BMask_NotMixed))
00535       >> 1;
00536 
00537   return NewMask;
00538 }
00539 
00540 /// Decompose an icmp into the form ((X & Y) pred Z) if possible.
00541 /// The returned predicate is either == or !=. Returns false if
00542 /// decomposition fails.
00543 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
00544                                  Value *&X, Value *&Y, Value *&Z) {
00545   ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
00546   if (!C)
00547     return false;
00548 
00549   switch (I->getPredicate()) {
00550   default:
00551     return false;
00552   case ICmpInst::ICMP_SLT:
00553     // X < 0 is equivalent to (X & SignBit) != 0.
00554     if (!C->isZero())
00555       return false;
00556     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
00557     Pred = ICmpInst::ICMP_NE;
00558     break;
00559   case ICmpInst::ICMP_SGT:
00560     // X > -1 is equivalent to (X & SignBit) == 0.
00561     if (!C->isAllOnesValue())
00562       return false;
00563     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
00564     Pred = ICmpInst::ICMP_EQ;
00565     break;
00566   case ICmpInst::ICMP_ULT:
00567     // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
00568     if (!C->getValue().isPowerOf2())
00569       return false;
00570     Y = ConstantInt::get(I->getContext(), -C->getValue());
00571     Pred = ICmpInst::ICMP_EQ;
00572     break;
00573   case ICmpInst::ICMP_UGT:
00574     // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
00575     if (!(C->getValue() + 1).isPowerOf2())
00576       return false;
00577     Y = ConstantInt::get(I->getContext(), ~C->getValue());
00578     Pred = ICmpInst::ICMP_NE;
00579     break;
00580   }
00581 
00582   X = I->getOperand(0);
00583   Z = ConstantInt::getNullValue(C->getType());
00584   return true;
00585 }
00586 
00587 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
00588 /// Return the set of pattern classes (from MaskedICmpType)
00589 /// that both LHS and RHS satisfy.
00590 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
00591                                              Value*& B, Value*& C,
00592                                              Value*& D, Value*& E,
00593                                              ICmpInst *LHS, ICmpInst *RHS,
00594                                              ICmpInst::Predicate &LHSCC,
00595                                              ICmpInst::Predicate &RHSCC) {
00596   if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
00597   // vectors are not (yet?) supported
00598   if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
00599 
00600   // Here comes the tricky part:
00601   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
00602   // and L11 & L12 == L21 & L22. The same goes for RHS.
00603   // Now we must find those components L** and R**, that are equal, so
00604   // that we can extract the parameters A, B, C, D, and E for the canonical
00605   // above.
00606   Value *L1 = LHS->getOperand(0);
00607   Value *L2 = LHS->getOperand(1);
00608   Value *L11,*L12,*L21,*L22;
00609   // Check whether the icmp can be decomposed into a bit test.
00610   if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
00611     L21 = L22 = L1 = nullptr;
00612   } else {
00613     // Look for ANDs in the LHS icmp.
00614     if (!L1->getType()->isIntegerTy()) {
00615       // You can icmp pointers, for example. They really aren't masks.
00616       L11 = L12 = nullptr;
00617     } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
00618       // Any icmp can be viewed as being trivially masked; if it allows us to
00619       // remove one, it's worth it.
00620       L11 = L1;
00621       L12 = Constant::getAllOnesValue(L1->getType());
00622     }
00623 
00624     if (!L2->getType()->isIntegerTy()) {
00625       // You can icmp pointers, for example. They really aren't masks.
00626       L21 = L22 = nullptr;
00627     } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
00628       L21 = L2;
00629       L22 = Constant::getAllOnesValue(L2->getType());
00630     }
00631   }
00632 
00633   // Bail if LHS was a icmp that can't be decomposed into an equality.
00634   if (!ICmpInst::isEquality(LHSCC))
00635     return 0;
00636 
00637   Value *R1 = RHS->getOperand(0);
00638   Value *R2 = RHS->getOperand(1);
00639   Value *R11,*R12;
00640   bool ok = false;
00641   if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
00642     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
00643       A = R11; D = R12;
00644     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
00645       A = R12; D = R11;
00646     } else {
00647       return 0;
00648     }
00649     E = R2; R1 = nullptr; ok = true;
00650   } else if (R1->getType()->isIntegerTy()) {
00651     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
00652       // As before, model no mask as a trivial mask if it'll let us do an
00653       // optimization.
00654       R11 = R1;
00655       R12 = Constant::getAllOnesValue(R1->getType());
00656     }
00657 
00658     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
00659       A = R11; D = R12; E = R2; ok = true;
00660     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
00661       A = R12; D = R11; E = R2; ok = true;
00662     }
00663   }
00664 
00665   // Bail if RHS was a icmp that can't be decomposed into an equality.
00666   if (!ICmpInst::isEquality(RHSCC))
00667     return 0;
00668 
00669   // Look for ANDs in on the right side of the RHS icmp.
00670   if (!ok && R2->getType()->isIntegerTy()) {
00671     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
00672       R11 = R2;
00673       R12 = Constant::getAllOnesValue(R2->getType());
00674     }
00675 
00676     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
00677       A = R11; D = R12; E = R1; ok = true;
00678     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
00679       A = R12; D = R11; E = R1; ok = true;
00680     } else {
00681       return 0;
00682     }
00683   }
00684   if (!ok)
00685     return 0;
00686 
00687   if (L11 == A) {
00688     B = L12; C = L2;
00689   } else if (L12 == A) {
00690     B = L11; C = L2;
00691   } else if (L21 == A) {
00692     B = L22; C = L1;
00693   } else if (L22 == A) {
00694     B = L21; C = L1;
00695   }
00696 
00697   unsigned LeftType = getTypeOfMaskedICmp(A, B, C, LHSCC);
00698   unsigned RightType = getTypeOfMaskedICmp(A, D, E, RHSCC);
00699   return LeftType & RightType;
00700 }
00701 
00702 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
00703 /// into a single (icmp(A & X) ==/!= Y).
00704 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
00705                                      llvm::InstCombiner::BuilderTy *Builder) {
00706   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
00707   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
00708   unsigned Mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
00709                                                LHSCC, RHSCC);
00710   if (Mask == 0) return nullptr;
00711   assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
00712          "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
00713 
00714   // In full generality:
00715   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
00716   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
00717   //
00718   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
00719   // equivalent to (icmp (A & X) !Op Y).
00720   //
00721   // Therefore, we can pretend for the rest of this function that we're dealing
00722   // with the conjunction, provided we flip the sense of any comparisons (both
00723   // input and output).
00724 
00725   // In most cases we're going to produce an EQ for the "&&" case.
00726   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
00727   if (!IsAnd) {
00728     // Convert the masking analysis into its equivalent with negated
00729     // comparisons.
00730     Mask = conjugateICmpMask(Mask);
00731   }
00732 
00733   if (Mask & FoldMskICmp_Mask_AllZeroes) {
00734     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
00735     // -> (icmp eq (A & (B|D)), 0)
00736     Value *NewOr = Builder->CreateOr(B, D);
00737     Value *NewAnd = Builder->CreateAnd(A, NewOr);
00738     // We can't use C as zero because we might actually handle
00739     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
00740     // with B and D, having a single bit set.
00741     Value *Zero = Constant::getNullValue(A->getType());
00742     return Builder->CreateICmp(NewCC, NewAnd, Zero);
00743   }
00744   if (Mask & FoldMskICmp_BMask_AllOnes) {
00745     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
00746     // -> (icmp eq (A & (B|D)), (B|D))
00747     Value *NewOr = Builder->CreateOr(B, D);
00748     Value *NewAnd = Builder->CreateAnd(A, NewOr);
00749     return Builder->CreateICmp(NewCC, NewAnd, NewOr);
00750   }
00751   if (Mask & FoldMskICmp_AMask_AllOnes) {
00752     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
00753     // -> (icmp eq (A & (B&D)), A)
00754     Value *NewAnd1 = Builder->CreateAnd(B, D);
00755     Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
00756     return Builder->CreateICmp(NewCC, NewAnd2, A);
00757   }
00758 
00759   // Remaining cases assume at least that B and D are constant, and depend on
00760   // their actual values. This isn't strictly necessary, just a "handle the
00761   // easy cases for now" decision.
00762   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
00763   if (!BCst) return nullptr;
00764   ConstantInt *DCst = dyn_cast<ConstantInt>(D);
00765   if (!DCst) return nullptr;
00766 
00767   if (Mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
00768     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
00769     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
00770     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
00771     // Only valid if one of the masks is a superset of the other (check "B&D" is
00772     // the same as either B or D).
00773     APInt NewMask = BCst->getValue() & DCst->getValue();
00774 
00775     if (NewMask == BCst->getValue())
00776       return LHS;
00777     else if (NewMask == DCst->getValue())
00778       return RHS;
00779   }
00780   if (Mask & FoldMskICmp_AMask_NotAllOnes) {
00781     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
00782     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
00783     // Only valid if one of the masks is a superset of the other (check "B|D" is
00784     // the same as either B or D).
00785     APInt NewMask = BCst->getValue() | DCst->getValue();
00786 
00787     if (NewMask == BCst->getValue())
00788       return LHS;
00789     else if (NewMask == DCst->getValue())
00790       return RHS;
00791   }
00792   if (Mask & FoldMskICmp_BMask_Mixed) {
00793     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
00794     // We already know that B & C == C && D & E == E.
00795     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
00796     // C and E, which are shared by both the mask B and the mask D, don't
00797     // contradict, then we can transform to
00798     // -> (icmp eq (A & (B|D)), (C|E))
00799     // Currently, we only handle the case of B, C, D, and E being constant.
00800     // We can't simply use C and E because we might actually handle
00801     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
00802     // with B and D, having a single bit set.
00803     ConstantInt *CCst = dyn_cast<ConstantInt>(C);
00804     if (!CCst) return nullptr;
00805     ConstantInt *ECst = dyn_cast<ConstantInt>(E);
00806     if (!ECst) return nullptr;
00807     if (LHSCC != NewCC)
00808       CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
00809     if (RHSCC != NewCC)
00810       ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
00811     // If there is a conflict, we should actually return a false for the
00812     // whole construct.
00813     if (((BCst->getValue() & DCst->getValue()) &
00814          (CCst->getValue() ^ ECst->getValue())) != 0)
00815       return ConstantInt::get(LHS->getType(), !IsAnd);
00816     Value *NewOr1 = Builder->CreateOr(B, D);
00817     Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
00818     Value *NewAnd = Builder->CreateAnd(A, NewOr1);
00819     return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
00820   }
00821   return nullptr;
00822 }
00823 
00824 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
00825 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
00826 /// If \p Inverted is true then the check is for the inverted range, e.g.
00827 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
00828 Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
00829                                         bool Inverted) {
00830   // Check the lower range comparison, e.g. x >= 0
00831   // InstCombine already ensured that if there is a constant it's on the RHS.
00832   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
00833   if (!RangeStart)
00834     return nullptr;
00835 
00836   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
00837                                Cmp0->getPredicate());
00838 
00839   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
00840   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
00841         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
00842     return nullptr;
00843 
00844   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
00845                                Cmp1->getPredicate());
00846 
00847   Value *Input = Cmp0->getOperand(0);
00848   Value *RangeEnd;
00849   if (Cmp1->getOperand(0) == Input) {
00850     // For the upper range compare we have: icmp x, n
00851     RangeEnd = Cmp1->getOperand(1);
00852   } else if (Cmp1->getOperand(1) == Input) {
00853     // For the upper range compare we have: icmp n, x
00854     RangeEnd = Cmp1->getOperand(0);
00855     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
00856   } else {
00857     return nullptr;
00858   }
00859 
00860   // Check the upper range comparison, e.g. x < n
00861   ICmpInst::Predicate NewPred;
00862   switch (Pred1) {
00863     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
00864     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
00865     default: return nullptr;
00866   }
00867 
00868   // This simplification is only valid if the upper range is not negative.
00869   bool IsNegative, IsNotNegative;
00870   ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
00871   if (!IsNotNegative)
00872     return nullptr;
00873 
00874   if (Inverted)
00875     NewPred = ICmpInst::getInversePredicate(NewPred);
00876 
00877   return Builder->CreateICmp(NewPred, Input, RangeEnd);
00878 }
00879 
00880 /// Fold (icmp)&(icmp) if possible.
00881 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
00882   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
00883 
00884   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
00885   if (PredicatesFoldable(LHSCC, RHSCC)) {
00886     if (LHS->getOperand(0) == RHS->getOperand(1) &&
00887         LHS->getOperand(1) == RHS->getOperand(0))
00888       LHS->swapOperands();
00889     if (LHS->getOperand(0) == RHS->getOperand(0) &&
00890         LHS->getOperand(1) == RHS->getOperand(1)) {
00891       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
00892       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
00893       bool isSigned = LHS->isSigned() || RHS->isSigned();
00894       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
00895     }
00896   }
00897 
00898   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
00899   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
00900     return V;
00901 
00902   // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
00903   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
00904     return V;
00905 
00906   // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
00907   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
00908     return V;
00909 
00910   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
00911   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
00912   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
00913   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
00914   if (!LHSCst || !RHSCst) return nullptr;
00915 
00916   if (LHSCst == RHSCst && LHSCC == RHSCC) {
00917     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
00918     // where C is a power of 2 or
00919     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
00920     if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
00921         (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
00922       Value *NewOr = Builder->CreateOr(Val, Val2);
00923       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
00924     }
00925   }
00926 
00927   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
00928   // where CMAX is the all ones value for the truncated type,
00929   // iff the lower bits of C2 and CA are zero.
00930   if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
00931       LHS->hasOneUse() && RHS->hasOneUse()) {
00932     Value *V;
00933     ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
00934 
00935     // (trunc x) == C1 & (and x, CA) == C2
00936     // (and x, CA) == C2 & (trunc x) == C1
00937     if (match(Val2, m_Trunc(m_Value(V))) &&
00938         match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
00939       SmallCst = RHSCst;
00940       BigCst = LHSCst;
00941     } else if (match(Val, m_Trunc(m_Value(V))) &&
00942                match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
00943       SmallCst = LHSCst;
00944       BigCst = RHSCst;
00945     }
00946 
00947     if (SmallCst && BigCst) {
00948       unsigned BigBitSize = BigCst->getType()->getBitWidth();
00949       unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
00950 
00951       // Check that the low bits are zero.
00952       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
00953       if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
00954         Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
00955         APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
00956         Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
00957         return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
00958       }
00959     }
00960   }
00961 
00962   // From here on, we only handle:
00963   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
00964   if (Val != Val2) return nullptr;
00965 
00966   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
00967   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
00968       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
00969       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
00970       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
00971     return nullptr;
00972 
00973   // Make a constant range that's the intersection of the two icmp ranges.
00974   // If the intersection is empty, we know that the result is false.
00975   ConstantRange LHSRange =
00976       ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
00977   ConstantRange RHSRange =
00978       ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
00979 
00980   if (LHSRange.intersectWith(RHSRange).isEmptySet())
00981     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
00982 
00983   // We can't fold (ugt x, C) & (sgt x, C2).
00984   if (!PredicatesFoldable(LHSCC, RHSCC))
00985     return nullptr;
00986 
00987   // Ensure that the larger constant is on the RHS.
00988   bool ShouldSwap;
00989   if (CmpInst::isSigned(LHSCC) ||
00990       (ICmpInst::isEquality(LHSCC) &&
00991        CmpInst::isSigned(RHSCC)))
00992     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
00993   else
00994     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
00995 
00996   if (ShouldSwap) {
00997     std::swap(LHS, RHS);
00998     std::swap(LHSCst, RHSCst);
00999     std::swap(LHSCC, RHSCC);
01000   }
01001 
01002   // At this point, we know we have two icmp instructions
01003   // comparing a value against two constants and and'ing the result
01004   // together.  Because of the above check, we know that we only have
01005   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
01006   // (from the icmp folding check above), that the two constants
01007   // are not equal and that the larger constant is on the RHS
01008   assert(LHSCst != RHSCst && "Compares not folded above?");
01009 
01010   switch (LHSCC) {
01011   default: llvm_unreachable("Unknown integer condition code!");
01012   case ICmpInst::ICMP_EQ:
01013     switch (RHSCC) {
01014     default: llvm_unreachable("Unknown integer condition code!");
01015     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
01016     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
01017     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
01018       return LHS;
01019     }
01020   case ICmpInst::ICMP_NE:
01021     switch (RHSCC) {
01022     default: llvm_unreachable("Unknown integer condition code!");
01023     case ICmpInst::ICMP_ULT:
01024       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
01025         return Builder->CreateICmpULT(Val, LHSCst);
01026       if (LHSCst->isNullValue())    // (X !=  0 & X u< 14) -> X-1 u< 13
01027         return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
01028       break;                        // (X != 13 & X u< 15) -> no change
01029     case ICmpInst::ICMP_SLT:
01030       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
01031         return Builder->CreateICmpSLT(Val, LHSCst);
01032       break;                        // (X != 13 & X s< 15) -> no change
01033     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
01034     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
01035     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
01036       return RHS;
01037     case ICmpInst::ICMP_NE:
01038       // Special case to get the ordering right when the values wrap around
01039       // zero.
01040       if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
01041         std::swap(LHSCst, RHSCst);
01042       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
01043         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
01044         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
01045         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
01046                                       Val->getName()+".cmp");
01047       }
01048       break;                        // (X != 13 & X != 15) -> no change
01049     }
01050     break;
01051   case ICmpInst::ICMP_ULT:
01052     switch (RHSCC) {
01053     default: llvm_unreachable("Unknown integer condition code!");
01054     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
01055     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
01056       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01057     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
01058       break;
01059     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
01060     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
01061       return LHS;
01062     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
01063       break;
01064     }
01065     break;
01066   case ICmpInst::ICMP_SLT:
01067     switch (RHSCC) {
01068     default: llvm_unreachable("Unknown integer condition code!");
01069     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
01070       break;
01071     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
01072     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
01073       return LHS;
01074     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
01075       break;
01076     }
01077     break;
01078   case ICmpInst::ICMP_UGT:
01079     switch (RHSCC) {
01080     default: llvm_unreachable("Unknown integer condition code!");
01081     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
01082     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
01083       return RHS;
01084     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
01085       break;
01086     case ICmpInst::ICMP_NE:
01087       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
01088         return Builder->CreateICmp(LHSCC, Val, RHSCst);
01089       break;                        // (X u> 13 & X != 15) -> no change
01090     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
01091       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
01092     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
01093       break;
01094     }
01095     break;
01096   case ICmpInst::ICMP_SGT:
01097     switch (RHSCC) {
01098     default: llvm_unreachable("Unknown integer condition code!");
01099     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
01100     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
01101       return RHS;
01102     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
01103       break;
01104     case ICmpInst::ICMP_NE:
01105       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
01106         return Builder->CreateICmp(LHSCC, Val, RHSCst);
01107       break;                        // (X s> 13 & X != 15) -> no change
01108     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
01109       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
01110     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
01111       break;
01112     }
01113     break;
01114   }
01115 
01116   return nullptr;
01117 }
01118 
01119 /// Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of instcombine, this returns
01120 /// a Value which should already be inserted into the function.
01121 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
01122   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
01123       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
01124     if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
01125       return nullptr;
01126 
01127     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
01128     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
01129       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
01130         // If either of the constants are nans, then the whole thing returns
01131         // false.
01132         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
01133           return Builder->getFalse();
01134         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
01135       }
01136 
01137     // Handle vector zeros.  This occurs because the canonical form of
01138     // "fcmp ord x,x" is "fcmp ord x, 0".
01139     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
01140         isa<ConstantAggregateZero>(RHS->getOperand(1)))
01141       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
01142     return nullptr;
01143   }
01144 
01145   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
01146   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
01147   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
01148 
01149 
01150   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
01151     // Swap RHS operands to match LHS.
01152     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
01153     std::swap(Op1LHS, Op1RHS);
01154   }
01155 
01156   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
01157     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
01158     if (Op0CC == Op1CC)
01159       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
01160     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
01161       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01162     if (Op0CC == FCmpInst::FCMP_TRUE)
01163       return RHS;
01164     if (Op1CC == FCmpInst::FCMP_TRUE)
01165       return LHS;
01166 
01167     bool Op0Ordered;
01168     bool Op1Ordered;
01169     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
01170     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
01171     // uno && ord -> false
01172     if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
01173         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01174     if (Op1Pred == 0) {
01175       std::swap(LHS, RHS);
01176       std::swap(Op0Pred, Op1Pred);
01177       std::swap(Op0Ordered, Op1Ordered);
01178     }
01179     if (Op0Pred == 0) {
01180       // uno && ueq -> uno && (uno || eq) -> uno
01181       // ord && olt -> ord && (ord && lt) -> olt
01182       if (!Op0Ordered && (Op0Ordered == Op1Ordered))
01183         return LHS;
01184       if (Op0Ordered && (Op0Ordered == Op1Ordered))
01185         return RHS;
01186 
01187       // uno && oeq -> uno && (ord && eq) -> false
01188       if (!Op0Ordered)
01189         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
01190       // ord && ueq -> ord && (uno || eq) -> oeq
01191       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
01192     }
01193   }
01194 
01195   return nullptr;
01196 }
01197 
01198 /// Match De Morgan's Laws:
01199 /// (~A & ~B) == (~(A | B))
01200 /// (~A | ~B) == (~(A & B))
01201 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
01202                                        InstCombiner::BuilderTy *Builder) {
01203   auto Opcode = I.getOpcode();
01204   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
01205          "Trying to match De Morgan's Laws with something other than and/or");
01206   // Flip the logic operation.
01207   if (Opcode == Instruction::And)
01208     Opcode = Instruction::Or;
01209   else
01210     Opcode = Instruction::And;
01211 
01212   Value *Op0 = I.getOperand(0);
01213   Value *Op1 = I.getOperand(1);
01214   // TODO: Use pattern matchers instead of dyn_cast.
01215   if (Value *Op0NotVal = dyn_castNotVal(Op0))
01216     if (Value *Op1NotVal = dyn_castNotVal(Op1))
01217       if (Op0->hasOneUse() && Op1->hasOneUse()) {
01218         Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
01219                                               I.getName() + ".demorgan");
01220         return BinaryOperator::CreateNot(LogicOp);
01221       }
01222 
01223   // De Morgan's Law in disguise:
01224   // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
01225   // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
01226   Value *A = nullptr;
01227   Value *B = nullptr;
01228   ConstantInt *C1 = nullptr;
01229   if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
01230       match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
01231     // TODO: This check could be loosened to handle different type sizes.
01232     // Alternatively, we could fix the definition of m_Not to recognize a not
01233     // operation hidden by a zext?
01234     if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
01235         C1->isOne()) {
01236       Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
01237                                             I.getName() + ".demorgan");
01238       Value *Not = Builder->CreateNot(LogicOp);
01239       return CastInst::CreateZExtOrBitCast(Not, I.getType());
01240     }
01241   }
01242 
01243   return nullptr;
01244 }
01245 
01246 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
01247   bool Changed = SimplifyAssociativeOrCommutative(I);
01248   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01249 
01250   if (Value *V = SimplifyVectorOp(I))
01251     return ReplaceInstUsesWith(I, V);
01252 
01253   if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
01254     return ReplaceInstUsesWith(I, V);
01255 
01256   // (A|B)&(A|C) -> A|(B&C) etc
01257   if (Value *V = SimplifyUsingDistributiveLaws(I))
01258     return ReplaceInstUsesWith(I, V);
01259 
01260   // See if we can simplify any instructions used by the instruction whose sole
01261   // purpose is to compute bits we don't care about.
01262   if (SimplifyDemandedInstructionBits(I))
01263     return &I;
01264 
01265   if (Value *V = SimplifyBSwap(I))
01266     return ReplaceInstUsesWith(I, V);
01267 
01268   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
01269     const APInt &AndRHSMask = AndRHS->getValue();
01270 
01271     // Optimize a variety of ((val OP C1) & C2) combinations...
01272     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
01273       Value *Op0LHS = Op0I->getOperand(0);
01274       Value *Op0RHS = Op0I->getOperand(1);
01275       switch (Op0I->getOpcode()) {
01276       default: break;
01277       case Instruction::Xor:
01278       case Instruction::Or: {
01279         // If the mask is only needed on one incoming arm, push it up.
01280         if (!Op0I->hasOneUse()) break;
01281 
01282         APInt NotAndRHS(~AndRHSMask);
01283         if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
01284           // Not masking anything out for the LHS, move to RHS.
01285           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
01286                                              Op0RHS->getName()+".masked");
01287           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
01288         }
01289         if (!isa<Constant>(Op0RHS) &&
01290             MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
01291           // Not masking anything out for the RHS, move to LHS.
01292           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
01293                                              Op0LHS->getName()+".masked");
01294           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
01295         }
01296 
01297         break;
01298       }
01299       case Instruction::Add:
01300         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
01301         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
01302         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
01303         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
01304           return BinaryOperator::CreateAnd(V, AndRHS);
01305         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
01306           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
01307         break;
01308 
01309       case Instruction::Sub:
01310         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
01311         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
01312         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
01313         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
01314           return BinaryOperator::CreateAnd(V, AndRHS);
01315 
01316         // -x & 1 -> x & 1
01317         if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
01318           return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
01319 
01320         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
01321         // has 1's for all bits that the subtraction with A might affect.
01322         if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
01323           uint32_t BitWidth = AndRHSMask.getBitWidth();
01324           uint32_t Zeros = AndRHSMask.countLeadingZeros();
01325           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
01326 
01327           if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
01328             Value *NewNeg = Builder->CreateNeg(Op0RHS);
01329             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
01330           }
01331         }
01332         break;
01333 
01334       case Instruction::Shl:
01335       case Instruction::LShr:
01336         // (1 << x) & 1 --> zext(x == 0)
01337         // (1 >> x) & 1 --> zext(x == 0)
01338         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
01339           Value *NewICmp =
01340             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
01341           return new ZExtInst(NewICmp, I.getType());
01342         }
01343         break;
01344       }
01345 
01346       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
01347         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
01348           return Res;
01349     }
01350 
01351     // If this is an integer truncation, and if the source is an 'and' with
01352     // immediate, transform it.  This frequently occurs for bitfield accesses.
01353     {
01354       Value *X = nullptr; ConstantInt *YC = nullptr;
01355       if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
01356         // Change: and (trunc (and X, YC) to T), C2
01357         // into  : and (trunc X to T), trunc(YC) & C2
01358         // This will fold the two constants together, which may allow
01359         // other simplifications.
01360         Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
01361         Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
01362         C3 = ConstantExpr::getAnd(C3, AndRHS);
01363         return BinaryOperator::CreateAnd(NewCast, C3);
01364       }
01365     }
01366 
01367     // Try to fold constant and into select arguments.
01368     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
01369       if (Instruction *R = FoldOpIntoSelect(I, SI))
01370         return R;
01371     if (isa<PHINode>(Op0))
01372       if (Instruction *NV = FoldOpIntoPhi(I))
01373         return NV;
01374   }
01375 
01376   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
01377     return DeMorgan;
01378 
01379   {
01380     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
01381     // (A|B) & ~(A&B) -> A^B
01382     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
01383         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
01384         ((A == C && B == D) || (A == D && B == C)))
01385       return BinaryOperator::CreateXor(A, B);
01386 
01387     // ~(A&B) & (A|B) -> A^B
01388     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
01389         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
01390         ((A == C && B == D) || (A == D && B == C)))
01391       return BinaryOperator::CreateXor(A, B);
01392 
01393     // A&(A^B) => A & ~B
01394     {
01395       Value *tmpOp0 = Op0;
01396       Value *tmpOp1 = Op1;
01397       if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
01398         if (A == Op1 || B == Op1 ) {
01399           tmpOp1 = Op0;
01400           tmpOp0 = Op1;
01401           // Simplify below
01402         }
01403       }
01404 
01405       if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
01406         if (B == tmpOp0) {
01407           std::swap(A, B);
01408         }
01409         // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
01410         // A is originally -1 (or a vector of -1 and undefs), then we enter
01411         // an endless loop. By checking that A is non-constant we ensure that
01412         // we will never get to the loop.
01413         if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
01414           return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
01415       }
01416     }
01417 
01418     // (A&((~A)|B)) -> A&B
01419     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
01420         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
01421       return BinaryOperator::CreateAnd(A, Op1);
01422     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
01423         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
01424       return BinaryOperator::CreateAnd(A, Op0);
01425 
01426     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
01427     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
01428       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
01429         if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
01430           return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
01431 
01432     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
01433     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
01434       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
01435         if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
01436           return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
01437 
01438     // (A | B) & ((~A) ^ B) -> (A & B)
01439     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
01440         match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
01441       return BinaryOperator::CreateAnd(A, B);
01442 
01443     // ((~A) ^ B) & (A | B) -> (A & B)
01444     if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
01445         match(Op1, m_Or(m_Specific(A), m_Specific(B))))
01446       return BinaryOperator::CreateAnd(A, B);
01447   }
01448 
01449   {
01450     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
01451     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
01452     if (LHS && RHS)
01453       if (Value *Res = FoldAndOfICmps(LHS, RHS))
01454         return ReplaceInstUsesWith(I, Res);
01455 
01456     // TODO: Make this recursive; it's a little tricky because an arbitrary
01457     // number of 'and' instructions might have to be created.
01458     Value *X, *Y;
01459     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
01460       if (auto *Cmp = dyn_cast<ICmpInst>(X))
01461         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
01462           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
01463       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
01464         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
01465           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
01466     }
01467     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
01468       if (auto *Cmp = dyn_cast<ICmpInst>(X))
01469         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
01470           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
01471       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
01472         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
01473           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
01474     }
01475   }
01476 
01477   // If and'ing two fcmp, try combine them into one.
01478   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
01479     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
01480       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
01481         return ReplaceInstUsesWith(I, Res);
01482 
01483 
01484   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
01485     Value *Op0COp = Op0C->getOperand(0);
01486     Type *SrcTy = Op0COp->getType();
01487     // fold (and (cast A), (cast B)) -> (cast (and A, B))
01488     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
01489       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
01490           SrcTy == Op1C->getOperand(0)->getType() &&
01491           SrcTy->isIntOrIntVectorTy()) {
01492         Value *Op1COp = Op1C->getOperand(0);
01493 
01494         // Only do this if the casts both really cause code to be generated.
01495         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
01496             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
01497           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
01498           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
01499         }
01500 
01501         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
01502         // cast is otherwise not optimizable.  This happens for vector sexts.
01503         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
01504           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
01505             if (Value *Res = FoldAndOfICmps(LHS, RHS))
01506               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
01507 
01508         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
01509         // cast is otherwise not optimizable.  This happens for vector sexts.
01510         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
01511           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
01512             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
01513               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
01514       }
01515     }
01516 
01517     // If we are masking off the sign bit of a floating-point value, convert
01518     // this to the canonical fabs intrinsic call and cast back to integer.
01519     // The backend should know how to optimize fabs().
01520     // TODO: This transform should also apply to vectors.
01521     ConstantInt *CI;
01522     if (isa<BitCastInst>(Op0C) && SrcTy->isFloatingPointTy() &&
01523         match(Op1, m_ConstantInt(CI)) && CI->isMaxValue(true)) {
01524       Module *M = I.getModule();
01525       Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, SrcTy);
01526       Value *Call = Builder->CreateCall(Fabs, Op0COp, "fabs");
01527       return CastInst::CreateBitOrPointerCast(Call, I.getType());
01528     }
01529   }
01530 
01531   {
01532     Value *X = nullptr;
01533     bool OpsSwapped = false;
01534     // Canonicalize SExt or Not to the LHS
01535     if (match(Op1, m_SExt(m_Value())) ||
01536         match(Op1, m_Not(m_Value()))) {
01537       std::swap(Op0, Op1);
01538       OpsSwapped = true;
01539     }
01540 
01541     // Fold (and (sext bool to A), B) --> (select bool, B, 0)
01542     if (match(Op0, m_SExt(m_Value(X))) &&
01543         X->getType()->getScalarType()->isIntegerTy(1)) {
01544       Value *Zero = Constant::getNullValue(Op1->getType());
01545       return SelectInst::Create(X, Op1, Zero);
01546     }
01547 
01548     // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
01549     if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
01550         X->getType()->getScalarType()->isIntegerTy(1)) {
01551       Value *Zero = Constant::getNullValue(Op0->getType());
01552       return SelectInst::Create(X, Zero, Op1);
01553     }
01554 
01555     if (OpsSwapped)
01556       std::swap(Op0, Op1);
01557   }
01558 
01559   return Changed ? &I : nullptr;
01560 }
01561 
01562 /// Given an OR instruction, check to see if this is a bswap or bitreverse
01563 /// idiom. If so, insert the new intrinsic and return it.
01564 Instruction *InstCombiner::MatchBSwapOrBitReverse(BinaryOperator &I) {
01565   SmallVector<Instruction*, 4> Insts;
01566   if (!recognizeBitReverseOrBSwapIdiom(&I, true, false, Insts))
01567     return nullptr;
01568   Instruction *LastInst = Insts.pop_back_val();
01569   LastInst->removeFromParent();
01570 
01571   for (auto *Inst : Insts)
01572     Worklist.Add(Inst);
01573   return LastInst;
01574 }
01575 
01576 /// We have an expression of the form (A&C)|(B&D).  Check if A is (cond?-1:0)
01577 /// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
01578 /// expression to "cond ? C : D or B".
01579 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
01580                                          Value *C, Value *D) {
01581   // If A is not a select of -1/0, this cannot match.
01582   Value *Cond = nullptr;
01583   if (!match(A, m_SExt(m_Value(Cond))) ||
01584       !Cond->getType()->isIntegerTy(1))
01585     return nullptr;
01586 
01587   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
01588   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
01589     return SelectInst::Create(Cond, C, B);
01590   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
01591     return SelectInst::Create(Cond, C, B);
01592 
01593   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
01594   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
01595     return SelectInst::Create(Cond, C, D);
01596   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
01597     return SelectInst::Create(Cond, C, D);
01598   return nullptr;
01599 }
01600 
01601 /// Fold (icmp)|(icmp) if possible.
01602 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
01603                                    Instruction *CxtI) {
01604   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
01605 
01606   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
01607   // if K1 and K2 are a one-bit mask.
01608   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
01609   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
01610 
01611   if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
01612       RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
01613 
01614     BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
01615     BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
01616     if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
01617         LAnd->getOpcode() == Instruction::And &&
01618         RAnd->getOpcode() == Instruction::And) {
01619 
01620       Value *Mask = nullptr;
01621       Value *Masked = nullptr;
01622       if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
01623           isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
01624                                  DT) &&
01625           isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
01626                                  DT)) {
01627         Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
01628         Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
01629       } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
01630                  isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
01631                                         CxtI, DT) &&
01632                  isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
01633                                         CxtI, DT)) {
01634         Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
01635         Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
01636       }
01637 
01638       if (Masked)
01639         return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
01640     }
01641   }
01642 
01643   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
01644   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
01645   // The original condition actually refers to the following two ranges:
01646   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
01647   // We can fold these two ranges if:
01648   // 1) C1 and C2 is unsigned greater than C3.
01649   // 2) The two ranges are separated.
01650   // 3) C1 ^ C2 is one-bit mask.
01651   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
01652   // This implies all values in the two ranges differ by exactly one bit.
01653 
01654   if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
01655       LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
01656       RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
01657       LHSCst->getValue() == (RHSCst->getValue())) {
01658 
01659     Value *LAdd = LHS->getOperand(0);
01660     Value *RAdd = RHS->getOperand(0);
01661 
01662     Value *LAddOpnd, *RAddOpnd;
01663     ConstantInt *LAddCst, *RAddCst;
01664     if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
01665         match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
01666         LAddCst->getValue().ugt(LHSCst->getValue()) &&
01667         RAddCst->getValue().ugt(LHSCst->getValue())) {
01668 
01669       APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
01670       if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
01671         ConstantInt *MaxAddCst = nullptr;
01672         if (LAddCst->getValue().ult(RAddCst->getValue()))
01673           MaxAddCst = RAddCst;
01674         else
01675           MaxAddCst = LAddCst;
01676 
01677         APInt RRangeLow = -RAddCst->getValue();
01678         APInt RRangeHigh = RRangeLow + LHSCst->getValue();
01679         APInt LRangeLow = -LAddCst->getValue();
01680         APInt LRangeHigh = LRangeLow + LHSCst->getValue();
01681         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
01682         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
01683         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
01684                                                    : RRangeLow - LRangeLow;
01685 
01686         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
01687             RangeDiff.ugt(LHSCst->getValue())) {
01688           Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
01689 
01690           Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
01691           Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
01692           return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
01693         }
01694       }
01695     }
01696   }
01697 
01698   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
01699   if (PredicatesFoldable(LHSCC, RHSCC)) {
01700     if (LHS->getOperand(0) == RHS->getOperand(1) &&
01701         LHS->getOperand(1) == RHS->getOperand(0))
01702       LHS->swapOperands();
01703     if (LHS->getOperand(0) == RHS->getOperand(0) &&
01704         LHS->getOperand(1) == RHS->getOperand(1)) {
01705       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
01706       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
01707       bool isSigned = LHS->isSigned() || RHS->isSigned();
01708       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
01709     }
01710   }
01711 
01712   // handle (roughly):
01713   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
01714   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
01715     return V;
01716 
01717   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
01718   if (LHS->hasOneUse() || RHS->hasOneUse()) {
01719     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
01720     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
01721     Value *A = nullptr, *B = nullptr;
01722     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
01723       B = Val;
01724       if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
01725         A = Val2;
01726       else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
01727         A = RHS->getOperand(1);
01728     }
01729     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
01730     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
01731     else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
01732       B = Val2;
01733       if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
01734         A = Val;
01735       else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
01736         A = LHS->getOperand(1);
01737     }
01738     if (A && B)
01739       return Builder->CreateICmp(
01740           ICmpInst::ICMP_UGE,
01741           Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
01742   }
01743 
01744   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
01745   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
01746     return V;
01747 
01748   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
01749   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
01750     return V;
01751  
01752   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
01753   if (!LHSCst || !RHSCst) return nullptr;
01754 
01755   if (LHSCst == RHSCst && LHSCC == RHSCC) {
01756     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
01757     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
01758       Value *NewOr = Builder->CreateOr(Val, Val2);
01759       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
01760     }
01761   }
01762 
01763   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
01764   //   iff C2 + CA == C1.
01765   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
01766     ConstantInt *AddCst;
01767     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
01768       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
01769         return Builder->CreateICmpULE(Val, LHSCst);
01770   }
01771 
01772   // From here on, we only handle:
01773   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
01774   if (Val != Val2) return nullptr;
01775 
01776   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
01777   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
01778       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
01779       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
01780       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
01781     return nullptr;
01782 
01783   // We can't fold (ugt x, C) | (sgt x, C2).
01784   if (!PredicatesFoldable(LHSCC, RHSCC))
01785     return nullptr;
01786 
01787   // Ensure that the larger constant is on the RHS.
01788   bool ShouldSwap;
01789   if (CmpInst::isSigned(LHSCC) ||
01790       (ICmpInst::isEquality(LHSCC) &&
01791        CmpInst::isSigned(RHSCC)))
01792     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
01793   else
01794     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
01795 
01796   if (ShouldSwap) {
01797     std::swap(LHS, RHS);
01798     std::swap(LHSCst, RHSCst);
01799     std::swap(LHSCC, RHSCC);
01800   }
01801 
01802   // At this point, we know we have two icmp instructions
01803   // comparing a value against two constants and or'ing the result
01804   // together.  Because of the above check, we know that we only have
01805   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
01806   // icmp folding check above), that the two constants are not
01807   // equal.
01808   assert(LHSCst != RHSCst && "Compares not folded above?");
01809 
01810   switch (LHSCC) {
01811   default: llvm_unreachable("Unknown integer condition code!");
01812   case ICmpInst::ICMP_EQ:
01813     switch (RHSCC) {
01814     default: llvm_unreachable("Unknown integer condition code!");
01815     case ICmpInst::ICMP_EQ:
01816       if (LHS->getOperand(0) == RHS->getOperand(0)) {
01817         // if LHSCst and RHSCst differ only by one bit:
01818         // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
01819         assert(LHSCst->getValue().ule(LHSCst->getValue()));
01820 
01821         APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
01822         if (Xor.isPowerOf2()) {
01823           Value *Cst = Builder->getInt(Xor);
01824           Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
01825           return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
01826         }
01827       }
01828 
01829       if (LHSCst == SubOne(RHSCst)) {
01830         // (X == 13 | X == 14) -> X-13 <u 2
01831         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
01832         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
01833         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
01834         return Builder->CreateICmpULT(Add, AddCST);
01835       }
01836 
01837       break;                         // (X == 13 | X == 15) -> no change
01838     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
01839     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
01840       break;
01841     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
01842     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
01843     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
01844       return RHS;
01845     }
01846     break;
01847   case ICmpInst::ICMP_NE:
01848     switch (RHSCC) {
01849     default: llvm_unreachable("Unknown integer condition code!");
01850     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
01851     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
01852     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
01853       return LHS;
01854     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
01855     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
01856     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
01857       return Builder->getTrue();
01858     }
01859   case ICmpInst::ICMP_ULT:
01860     switch (RHSCC) {
01861     default: llvm_unreachable("Unknown integer condition code!");
01862     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
01863       break;
01864     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
01865       // If RHSCst is [us]MAXINT, it is always false.  Not handling
01866       // this can cause overflow.
01867       if (RHSCst->isMaxValue(false))
01868         return LHS;
01869       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
01870     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
01871       break;
01872     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
01873     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
01874       return RHS;
01875     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
01876       break;
01877     }
01878     break;
01879   case ICmpInst::ICMP_SLT:
01880     switch (RHSCC) {
01881     default: llvm_unreachable("Unknown integer condition code!");
01882     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
01883       break;
01884     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
01885       // If RHSCst is [us]MAXINT, it is always false.  Not handling
01886       // this can cause overflow.
01887       if (RHSCst->isMaxValue(true))
01888         return LHS;
01889       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
01890     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
01891       break;
01892     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
01893     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
01894       return RHS;
01895     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
01896       break;
01897     }
01898     break;
01899   case ICmpInst::ICMP_UGT:
01900     switch (RHSCC) {
01901     default: llvm_unreachable("Unknown integer condition code!");
01902     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
01903     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
01904       return LHS;
01905     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
01906       break;
01907     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
01908     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
01909       return Builder->getTrue();
01910     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
01911       break;
01912     }
01913     break;
01914   case ICmpInst::ICMP_SGT:
01915     switch (RHSCC) {
01916     default: llvm_unreachable("Unknown integer condition code!");
01917     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
01918     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
01919       return LHS;
01920     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
01921       break;
01922     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
01923     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
01924       return Builder->getTrue();
01925     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
01926       break;
01927     }
01928     break;
01929   }
01930   return nullptr;
01931 }
01932 
01933 /// Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of instcombine, this returns
01934 /// a Value which should already be inserted into the function.
01935 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
01936   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
01937       RHS->getPredicate() == FCmpInst::FCMP_UNO &&
01938       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
01939     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
01940       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
01941         // If either of the constants are nans, then the whole thing returns
01942         // true.
01943         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
01944           return Builder->getTrue();
01945 
01946         // Otherwise, no need to compare the two constants, compare the
01947         // rest.
01948         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
01949       }
01950 
01951     // Handle vector zeros.  This occurs because the canonical form of
01952     // "fcmp uno x,x" is "fcmp uno x, 0".
01953     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
01954         isa<ConstantAggregateZero>(RHS->getOperand(1)))
01955       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
01956 
01957     return nullptr;
01958   }
01959 
01960   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
01961   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
01962   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
01963 
01964   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
01965     // Swap RHS operands to match LHS.
01966     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
01967     std::swap(Op1LHS, Op1RHS);
01968   }
01969   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
01970     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
01971     if (Op0CC == Op1CC)
01972       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
01973     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
01974       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
01975     if (Op0CC == FCmpInst::FCMP_FALSE)
01976       return RHS;
01977     if (Op1CC == FCmpInst::FCMP_FALSE)
01978       return LHS;
01979     bool Op0Ordered;
01980     bool Op1Ordered;
01981     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
01982     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
01983     if (Op0Ordered == Op1Ordered) {
01984       // If both are ordered or unordered, return a new fcmp with
01985       // or'ed predicates.
01986       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
01987     }
01988   }
01989   return nullptr;
01990 }
01991 
01992 /// This helper function folds:
01993 ///
01994 ///     ((A | B) & C1) | (B & C2)
01995 ///
01996 /// into:
01997 ///
01998 ///     (A & C1) | B
01999 ///
02000 /// when the XOR of the two constants is "all ones" (-1).
02001 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
02002                                                Value *A, Value *B, Value *C) {
02003   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
02004   if (!CI1) return nullptr;
02005 
02006   Value *V1 = nullptr;
02007   ConstantInt *CI2 = nullptr;
02008   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
02009 
02010   APInt Xor = CI1->getValue() ^ CI2->getValue();
02011   if (!Xor.isAllOnesValue()) return nullptr;
02012 
02013   if (V1 == A || V1 == B) {
02014     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
02015     return BinaryOperator::CreateOr(NewOp, V1);
02016   }
02017 
02018   return nullptr;
02019 }
02020 
02021 /// \brief This helper function folds:
02022 ///
02023 ///     ((A | B) & C1) ^ (B & C2)
02024 ///
02025 /// into:
02026 ///
02027 ///     (A & C1) ^ B
02028 ///
02029 /// when the XOR of the two constants is "all ones" (-1).
02030 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
02031                                                 Value *A, Value *B, Value *C) {
02032   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
02033   if (!CI1)
02034     return nullptr;
02035 
02036   Value *V1 = nullptr;
02037   ConstantInt *CI2 = nullptr;
02038   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
02039     return nullptr;
02040 
02041   APInt Xor = CI1->getValue() ^ CI2->getValue();
02042   if (!Xor.isAllOnesValue())
02043     return nullptr;
02044 
02045   if (V1 == A || V1 == B) {
02046     Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
02047     return BinaryOperator::CreateXor(NewOp, V1);
02048   }
02049 
02050   return nullptr;
02051 }
02052 
02053 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
02054   bool Changed = SimplifyAssociativeOrCommutative(I);
02055   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02056 
02057   if (Value *V = SimplifyVectorOp(I))
02058     return ReplaceInstUsesWith(I, V);
02059 
02060   if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
02061     return ReplaceInstUsesWith(I, V);
02062 
02063   // (A&B)|(A&C) -> A&(B|C) etc
02064   if (Value *V = SimplifyUsingDistributiveLaws(I))
02065     return ReplaceInstUsesWith(I, V);
02066 
02067   // See if we can simplify any instructions used by the instruction whose sole
02068   // purpose is to compute bits we don't care about.
02069   if (SimplifyDemandedInstructionBits(I))
02070     return &I;
02071 
02072   if (Value *V = SimplifyBSwap(I))
02073     return ReplaceInstUsesWith(I, V);
02074 
02075   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02076     ConstantInt *C1 = nullptr; Value *X = nullptr;
02077     // (X & C1) | C2 --> (X | C2) & (C1|C2)
02078     // iff (C1 & C2) == 0.
02079     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
02080         (RHS->getValue() & C1->getValue()) != 0 &&
02081         Op0->hasOneUse()) {
02082       Value *Or = Builder->CreateOr(X, RHS);
02083       Or->takeName(Op0);
02084       return BinaryOperator::CreateAnd(Or,
02085                              Builder->getInt(RHS->getValue() | C1->getValue()));
02086     }
02087 
02088     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
02089     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
02090         Op0->hasOneUse()) {
02091       Value *Or = Builder->CreateOr(X, RHS);
02092       Or->takeName(Op0);
02093       return BinaryOperator::CreateXor(Or,
02094                             Builder->getInt(C1->getValue() & ~RHS->getValue()));
02095     }
02096 
02097     // Try to fold constant and into select arguments.
02098     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02099       if (Instruction *R = FoldOpIntoSelect(I, SI))
02100         return R;
02101 
02102     if (isa<PHINode>(Op0))
02103       if (Instruction *NV = FoldOpIntoPhi(I))
02104         return NV;
02105   }
02106 
02107   Value *A = nullptr, *B = nullptr;
02108   ConstantInt *C1 = nullptr, *C2 = nullptr;
02109 
02110   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
02111   bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
02112                  match(Op1, m_Or(m_Value(), m_Value()));
02113   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
02114   bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
02115                     match(Op1, m_LogicalShift(m_Value(), m_Value()));
02116   // (A & B) | (C & D)                              -> bswap if possible.
02117   bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
02118                   match(Op1, m_And(m_Value(), m_Value()));
02119 
02120   if (OrOfOrs || OrOfShifts || OrOfAnds)
02121     if (Instruction *BSwap = MatchBSwapOrBitReverse(I))
02122       return BSwap;
02123 
02124   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
02125   if (Op0->hasOneUse() &&
02126       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
02127       MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
02128     Value *NOr = Builder->CreateOr(A, Op1);
02129     NOr->takeName(Op0);
02130     return BinaryOperator::CreateXor(NOr, C1);
02131   }
02132 
02133   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
02134   if (Op1->hasOneUse() &&
02135       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
02136       MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
02137     Value *NOr = Builder->CreateOr(A, Op0);
02138     NOr->takeName(Op0);
02139     return BinaryOperator::CreateXor(NOr, C1);
02140   }
02141 
02142   // ((~A & B) | A) -> (A | B)
02143   if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
02144       match(Op1, m_Specific(A)))
02145     return BinaryOperator::CreateOr(A, B);
02146 
02147   // ((A & B) | ~A) -> (~A | B)
02148   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
02149       match(Op1, m_Not(m_Specific(A))))
02150     return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
02151 
02152   // (A & (~B)) | (A ^ B) -> (A ^ B)
02153   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02154       match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
02155     return BinaryOperator::CreateXor(A, B);
02156 
02157   // (A ^ B) | ( A & (~B)) -> (A ^ B)
02158   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
02159       match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
02160     return BinaryOperator::CreateXor(A, B);
02161 
02162   // (A & C)|(B & D)
02163   Value *C = nullptr, *D = nullptr;
02164   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
02165       match(Op1, m_And(m_Value(B), m_Value(D)))) {
02166     Value *V1 = nullptr, *V2 = nullptr;
02167     C1 = dyn_cast<ConstantInt>(C);
02168     C2 = dyn_cast<ConstantInt>(D);
02169     if (C1 && C2) {  // (A & C1)|(B & C2)
02170       if ((C1->getValue() & C2->getValue()) == 0) {
02171         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
02172         // iff (C1&C2) == 0 and (N&~C1) == 0
02173         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
02174             ((V1 == B &&
02175               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
02176              (V2 == B &&
02177               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
02178           return BinaryOperator::CreateAnd(A,
02179                                 Builder->getInt(C1->getValue()|C2->getValue()));
02180         // Or commutes, try both ways.
02181         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
02182             ((V1 == A &&
02183               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
02184              (V2 == A &&
02185               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
02186           return BinaryOperator::CreateAnd(B,
02187                                 Builder->getInt(C1->getValue()|C2->getValue()));
02188 
02189         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
02190         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
02191         ConstantInt *C3 = nullptr, *C4 = nullptr;
02192         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
02193             (C3->getValue() & ~C1->getValue()) == 0 &&
02194             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
02195             (C4->getValue() & ~C2->getValue()) == 0) {
02196           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
02197           return BinaryOperator::CreateAnd(V2,
02198                                 Builder->getInt(C1->getValue()|C2->getValue()));
02199         }
02200       }
02201     }
02202 
02203     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
02204     // Don't do this for vector select idioms, the code generator doesn't handle
02205     // them well yet.
02206     if (!I.getType()->isVectorTy()) {
02207       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
02208         return Match;
02209       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
02210         return Match;
02211       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
02212         return Match;
02213       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
02214         return Match;
02215     }
02216 
02217     // ((A&~B)|(~A&B)) -> A^B
02218     if ((match(C, m_Not(m_Specific(D))) &&
02219          match(B, m_Not(m_Specific(A)))))
02220       return BinaryOperator::CreateXor(A, D);
02221     // ((~B&A)|(~A&B)) -> A^B
02222     if ((match(A, m_Not(m_Specific(D))) &&
02223          match(B, m_Not(m_Specific(C)))))
02224       return BinaryOperator::CreateXor(C, D);
02225     // ((A&~B)|(B&~A)) -> A^B
02226     if ((match(C, m_Not(m_Specific(B))) &&
02227          match(D, m_Not(m_Specific(A)))))
02228       return BinaryOperator::CreateXor(A, B);
02229     // ((~B&A)|(B&~A)) -> A^B
02230     if ((match(A, m_Not(m_Specific(B))) &&
02231          match(D, m_Not(m_Specific(C)))))
02232       return BinaryOperator::CreateXor(C, B);
02233 
02234     // ((A|B)&1)|(B&-2) -> (A&1) | B
02235     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
02236         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
02237       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
02238       if (Ret) return Ret;
02239     }
02240     // (B&-2)|((A|B)&1) -> (A&1) | B
02241     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
02242         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
02243       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
02244       if (Ret) return Ret;
02245     }
02246     // ((A^B)&1)|(B&-2) -> (A&1) ^ B
02247     if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
02248         match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
02249       Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
02250       if (Ret) return Ret;
02251     }
02252     // (B&-2)|((A^B)&1) -> (A&1) ^ B
02253     if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
02254         match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
02255       Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
02256       if (Ret) return Ret;
02257     }
02258   }
02259 
02260   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
02261   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
02262     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
02263       if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
02264         return BinaryOperator::CreateOr(Op0, C);
02265 
02266   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
02267   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
02268     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
02269       if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
02270         return BinaryOperator::CreateOr(Op1, C);
02271 
02272   // ((B | C) & A) | B -> B | (A & C)
02273   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
02274     return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
02275 
02276   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
02277     return DeMorgan;
02278 
02279   // Canonicalize xor to the RHS.
02280   bool SwappedForXor = false;
02281   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
02282     std::swap(Op0, Op1);
02283     SwappedForXor = true;
02284   }
02285 
02286   // A | ( A ^ B) -> A |  B
02287   // A | (~A ^ B) -> A | ~B
02288   // (A & B) | (A ^ B)
02289   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
02290     if (Op0 == A || Op0 == B)
02291       return BinaryOperator::CreateOr(A, B);
02292 
02293     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
02294         match(Op0, m_And(m_Specific(B), m_Specific(A))))
02295       return BinaryOperator::CreateOr(A, B);
02296 
02297     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
02298       Value *Not = Builder->CreateNot(B, B->getName()+".not");
02299       return BinaryOperator::CreateOr(Not, Op0);
02300     }
02301     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
02302       Value *Not = Builder->CreateNot(A, A->getName()+".not");
02303       return BinaryOperator::CreateOr(Not, Op0);
02304     }
02305   }
02306 
02307   // A | ~(A | B) -> A | ~B
02308   // A | ~(A ^ B) -> A | ~B
02309   if (match(Op1, m_Not(m_Value(A))))
02310     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
02311       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
02312           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
02313                                B->getOpcode() == Instruction::Xor)) {
02314         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
02315                                                  B->getOperand(0);
02316         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
02317         return BinaryOperator::CreateOr(Not, Op0);
02318       }
02319 
02320   // (A & B) | ((~A) ^ B) -> (~A ^ B)
02321   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
02322       match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
02323     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
02324 
02325   // ((~A) ^ B) | (A & B) -> (~A ^ B)
02326   if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
02327       match(Op1, m_And(m_Specific(A), m_Specific(B))))
02328     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
02329 
02330   if (SwappedForXor)
02331     std::swap(Op0, Op1);
02332 
02333   {
02334     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
02335     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
02336     if (LHS && RHS)
02337       if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
02338         return ReplaceInstUsesWith(I, Res);
02339 
02340     // TODO: Make this recursive; it's a little tricky because an arbitrary
02341     // number of 'or' instructions might have to be created.
02342     Value *X, *Y;
02343     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
02344       if (auto *Cmp = dyn_cast<ICmpInst>(X))
02345         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
02346           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
02347       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
02348         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
02349           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
02350     }
02351     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
02352       if (auto *Cmp = dyn_cast<ICmpInst>(X))
02353         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
02354           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
02355       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
02356         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
02357           return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
02358     }
02359   }
02360 
02361   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
02362   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
02363     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
02364       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
02365         return ReplaceInstUsesWith(I, Res);
02366 
02367   // fold (or (cast A), (cast B)) -> (cast (or A, B))
02368   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02369     CastInst *Op1C = dyn_cast<CastInst>(Op1);
02370     if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
02371       Type *SrcTy = Op0C->getOperand(0)->getType();
02372       if (SrcTy == Op1C->getOperand(0)->getType() &&
02373           SrcTy->isIntOrIntVectorTy()) {
02374         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
02375 
02376         if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
02377             // Only do this if the casts both really cause code to be
02378             // generated.
02379             ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
02380             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
02381           Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
02382           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
02383         }
02384 
02385         // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
02386         // cast is otherwise not optimizable.  This happens for vector sexts.
02387         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
02388           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
02389             if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
02390               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
02391 
02392         // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
02393         // cast is otherwise not optimizable.  This happens for vector sexts.
02394         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
02395           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
02396             if (Value *Res = FoldOrOfFCmps(LHS, RHS))
02397               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
02398       }
02399     }
02400   }
02401 
02402   // or(sext(A), B) -> A ? -1 : B where A is an i1
02403   // or(A, sext(B)) -> B ? -1 : A where B is an i1
02404   if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
02405     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
02406   if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
02407     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
02408 
02409   // Note: If we've gotten to the point of visiting the outer OR, then the
02410   // inner one couldn't be simplified.  If it was a constant, then it won't
02411   // be simplified by a later pass either, so we try swapping the inner/outer
02412   // ORs in the hopes that we'll be able to simplify it this way.
02413   // (X|C) | V --> (X|V) | C
02414   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
02415       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
02416     Value *Inner = Builder->CreateOr(A, Op1);
02417     Inner->takeName(Op0);
02418     return BinaryOperator::CreateOr(Inner, C1);
02419   }
02420 
02421   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
02422   // Since this OR statement hasn't been optimized further yet, we hope
02423   // that this transformation will allow the new ORs to be optimized.
02424   {
02425     Value *X = nullptr, *Y = nullptr;
02426     if (Op0->hasOneUse() && Op1->hasOneUse() &&
02427         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
02428         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
02429       Value *orTrue = Builder->CreateOr(A, C);
02430       Value *orFalse = Builder->CreateOr(B, D);
02431       return SelectInst::Create(X, orTrue, orFalse);
02432     }
02433   }
02434 
02435   return Changed ? &I : nullptr;
02436 }
02437 
02438 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
02439   bool Changed = SimplifyAssociativeOrCommutative(I);
02440   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02441 
02442   if (Value *V = SimplifyVectorOp(I))
02443     return ReplaceInstUsesWith(I, V);
02444 
02445   if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
02446     return ReplaceInstUsesWith(I, V);
02447 
02448   // (A&B)^(A&C) -> A&(B^C) etc
02449   if (Value *V = SimplifyUsingDistributiveLaws(I))
02450     return ReplaceInstUsesWith(I, V);
02451 
02452   // See if we can simplify any instructions used by the instruction whose sole
02453   // purpose is to compute bits we don't care about.
02454   if (SimplifyDemandedInstructionBits(I))
02455     return &I;
02456 
02457   if (Value *V = SimplifyBSwap(I))
02458     return ReplaceInstUsesWith(I, V);
02459 
02460   // Is this a ~ operation?
02461   if (Value *NotOp = dyn_castNotVal(&I)) {
02462     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
02463       if (Op0I->getOpcode() == Instruction::And ||
02464           Op0I->getOpcode() == Instruction::Or) {
02465         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
02466         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
02467         if (dyn_castNotVal(Op0I->getOperand(1)))
02468           Op0I->swapOperands();
02469         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
02470           Value *NotY =
02471             Builder->CreateNot(Op0I->getOperand(1),
02472                                Op0I->getOperand(1)->getName()+".not");
02473           if (Op0I->getOpcode() == Instruction::And)
02474             return BinaryOperator::CreateOr(Op0NotVal, NotY);
02475           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
02476         }
02477 
02478         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
02479         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
02480         if (IsFreeToInvert(Op0I->getOperand(0),
02481                            Op0I->getOperand(0)->hasOneUse()) &&
02482             IsFreeToInvert(Op0I->getOperand(1),
02483                            Op0I->getOperand(1)->hasOneUse())) {
02484           Value *NotX =
02485             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
02486           Value *NotY =
02487             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
02488           if (Op0I->getOpcode() == Instruction::And)
02489             return BinaryOperator::CreateOr(NotX, NotY);
02490           return BinaryOperator::CreateAnd(NotX, NotY);
02491         }
02492 
02493       } else if (Op0I->getOpcode() == Instruction::AShr) {
02494         // ~(~X >>s Y) --> (X >>s Y)
02495         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
02496           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
02497       }
02498     }
02499   }
02500 
02501   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
02502     if (RHS->isAllOnesValue() && Op0->hasOneUse())
02503       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
02504       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
02505         return CmpInst::Create(CI->getOpcode(),
02506                                CI->getInversePredicate(),
02507                                CI->getOperand(0), CI->getOperand(1));
02508   }
02509 
02510   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
02511     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
02512     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02513       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
02514         if (CI->hasOneUse() && Op0C->hasOneUse()) {
02515           Instruction::CastOps Opcode = Op0C->getOpcode();
02516           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
02517               (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
02518                                             Op0C->getDestTy()))) {
02519             CI->setPredicate(CI->getInversePredicate());
02520             return CastInst::Create(Opcode, CI, Op0C->getType());
02521           }
02522         }
02523       }
02524     }
02525 
02526     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
02527       // ~(c-X) == X-c-1 == X+(-c-1)
02528       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
02529         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
02530           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
02531           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
02532                                       ConstantInt::get(I.getType(), 1));
02533           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
02534         }
02535 
02536       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
02537         if (Op0I->getOpcode() == Instruction::Add) {
02538           // ~(X-c) --> (-c-1)-X
02539           if (RHS->isAllOnesValue()) {
02540             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
02541             return BinaryOperator::CreateSub(
02542                            ConstantExpr::getSub(NegOp0CI,
02543                                       ConstantInt::get(I.getType(), 1)),
02544                                       Op0I->getOperand(0));
02545           } else if (RHS->getValue().isSignBit()) {
02546             // (X + C) ^ signbit -> (X + C + signbit)
02547             Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
02548             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
02549 
02550           }
02551         } else if (Op0I->getOpcode() == Instruction::Or) {
02552           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
02553           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
02554                                 0, &I)) {
02555             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
02556             // Anything in both C1 and C2 is known to be zero, remove it from
02557             // NewRHS.
02558             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
02559             NewRHS = ConstantExpr::getAnd(NewRHS,
02560                                        ConstantExpr::getNot(CommonBits));
02561             Worklist.Add(Op0I);
02562             I.setOperand(0, Op0I->getOperand(0));
02563             I.setOperand(1, NewRHS);
02564             return &I;
02565           }
02566         } else if (Op0I->getOpcode() == Instruction::LShr) {
02567           // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
02568           // E1 = "X ^ C1"
02569           BinaryOperator *E1;
02570           ConstantInt *C1;
02571           if (Op0I->hasOneUse() &&
02572               (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
02573               E1->getOpcode() == Instruction::Xor &&
02574               (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
02575             // fold (C1 >> C2) ^ C3
02576             ConstantInt *C2 = Op0CI, *C3 = RHS;
02577             APInt FoldConst = C1->getValue().lshr(C2->getValue());
02578             FoldConst ^= C3->getValue();
02579             // Prepare the two operands.
02580             Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
02581             Opnd0->takeName(Op0I);
02582             cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
02583             Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
02584 
02585             return BinaryOperator::CreateXor(Opnd0, FoldVal);
02586           }
02587         }
02588       }
02589     }
02590 
02591     // Try to fold constant and into select arguments.
02592     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
02593       if (Instruction *R = FoldOpIntoSelect(I, SI))
02594         return R;
02595     if (isa<PHINode>(Op0))
02596       if (Instruction *NV = FoldOpIntoPhi(I))
02597         return NV;
02598   }
02599 
02600   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
02601   if (Op1I) {
02602     Value *A, *B;
02603     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
02604       if (A == Op0) {              // B^(B|A) == (A|B)^B
02605         Op1I->swapOperands();
02606         I.swapOperands();
02607         std::swap(Op0, Op1);
02608       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
02609         I.swapOperands();     // Simplified below.
02610         std::swap(Op0, Op1);
02611       }
02612     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
02613                Op1I->hasOneUse()){
02614       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
02615         Op1I->swapOperands();
02616         std::swap(A, B);
02617       }
02618       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
02619         I.swapOperands();     // Simplified below.
02620         std::swap(Op0, Op1);
02621       }
02622     }
02623   }
02624 
02625   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
02626   if (Op0I) {
02627     Value *A, *B;
02628     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02629         Op0I->hasOneUse()) {
02630       if (A == Op1)                                  // (B|A)^B == (A|B)^B
02631         std::swap(A, B);
02632       if (B == Op1)                                  // (A|B)^B == A & ~B
02633         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
02634     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02635                Op0I->hasOneUse()){
02636       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
02637         std::swap(A, B);
02638       if (B == Op1 &&                                      // (B&A)^A == ~B & A
02639           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
02640         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
02641       }
02642     }
02643   }
02644 
02645   if (Op0I && Op1I) {
02646     Value *A, *B, *C, *D;
02647     // (A & B)^(A | B) -> A ^ B
02648     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02649         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
02650       if ((A == C && B == D) || (A == D && B == C))
02651         return BinaryOperator::CreateXor(A, B);
02652     }
02653     // (A | B)^(A & B) -> A ^ B
02654     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02655         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
02656       if ((A == C && B == D) || (A == D && B == C))
02657         return BinaryOperator::CreateXor(A, B);
02658     }
02659     // (A | ~B) ^ (~A | B) -> A ^ B
02660     if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
02661         match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
02662       return BinaryOperator::CreateXor(A, B);
02663     }
02664     // (~A | B) ^ (A | ~B) -> A ^ B
02665     if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
02666         match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
02667       return BinaryOperator::CreateXor(A, B);
02668     }
02669     // (A & ~B) ^ (~A & B) -> A ^ B
02670     if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02671         match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
02672       return BinaryOperator::CreateXor(A, B);
02673     }
02674     // (~A & B) ^ (A & ~B) -> A ^ B
02675     if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
02676         match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
02677       return BinaryOperator::CreateXor(A, B);
02678     }
02679     // (A ^ C)^(A | B) -> ((~A) & B) ^ C
02680     if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
02681         match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
02682       if (D == A)
02683         return BinaryOperator::CreateXor(
02684             Builder->CreateAnd(Builder->CreateNot(A), B), C);
02685       if (D == B)
02686         return BinaryOperator::CreateXor(
02687             Builder->CreateAnd(Builder->CreateNot(B), A), C);
02688     }
02689     // (A | B)^(A ^ C) -> ((~A) & B) ^ C
02690     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
02691         match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
02692       if (D == A)
02693         return BinaryOperator::CreateXor(
02694             Builder->CreateAnd(Builder->CreateNot(A), B), C);
02695       if (D == B)
02696         return BinaryOperator::CreateXor(
02697             Builder->CreateAnd(Builder->CreateNot(B), A), C);
02698     }
02699     // (A & B) ^ (A ^ B) -> (A | B)
02700     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
02701         match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
02702       return BinaryOperator::CreateOr(A, B);
02703     // (A ^ B) ^ (A & B) -> (A | B)
02704     if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
02705         match(Op1I, m_And(m_Specific(A), m_Specific(B))))
02706       return BinaryOperator::CreateOr(A, B);
02707   }
02708 
02709   Value *A = nullptr, *B = nullptr;
02710   // (A & ~B) ^ (~A) -> ~(A & B)
02711   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
02712       match(Op1, m_Not(m_Specific(A))))
02713     return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
02714 
02715   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
02716   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
02717     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
02718       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
02719         if (LHS->getOperand(0) == RHS->getOperand(1) &&
02720             LHS->getOperand(1) == RHS->getOperand(0))
02721           LHS->swapOperands();
02722         if (LHS->getOperand(0) == RHS->getOperand(0) &&
02723             LHS->getOperand(1) == RHS->getOperand(1)) {
02724           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
02725           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
02726           bool isSigned = LHS->isSigned() || RHS->isSigned();
02727           return ReplaceInstUsesWith(I,
02728                                getNewICmpValue(isSigned, Code, Op0, Op1,
02729                                                Builder));
02730         }
02731       }
02732 
02733   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
02734   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
02735     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
02736       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
02737         Type *SrcTy = Op0C->getOperand(0)->getType();
02738         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
02739             // Only do this if the casts both really cause code to be generated.
02740             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
02741                                I.getType()) &&
02742             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
02743                                I.getType())) {
02744           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
02745                                             Op1C->getOperand(0), I.getName());
02746           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
02747         }
02748       }
02749   }
02750 
02751   return Changed ? &I : nullptr;
02752 }