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