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