LLVM API Documentation

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