1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitAnd, visitOr, and visitXor functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/ConstantRange.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 using namespace llvm;
22 using namespace PatternMatch;
23 
24 #define DEBUG_TYPE "instcombine"
25 
26 static inline Value *dyn_castNotVal(Value *V) {
27   // If this is not(not(x)) don't return that this is a not: we want the two
28   // not's to be folded first.
29   if (BinaryOperator::isNot(V)) {
30     Value *Operand = BinaryOperator::getNotArgument(V);
31     if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
32       return Operand;
33   }
34 
35   // Constants can be considered to be not'ed values...
36   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37     return ConstantInt::get(C->getType(), ~C->getValue());
38   return nullptr;
39 }
40 
41 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
42 /// a three bit mask. It also returns whether it is an ordered predicate by
43 /// reference.
44 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
45   isOrdered = false;
46   switch (CC) {
47   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
48   case FCmpInst::FCMP_UNO:                   return 0;  // 000
49   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
50   case FCmpInst::FCMP_UGT:                   return 1;  // 001
51   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
52   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
53   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
54   case FCmpInst::FCMP_UGE:                   return 3;  // 011
55   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
56   case FCmpInst::FCMP_ULT:                   return 4;  // 100
57   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
58   case FCmpInst::FCMP_UNE:                   return 5;  // 101
59   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
60   case FCmpInst::FCMP_ULE:                   return 6;  // 110
61     // True -> 7
62   default:
63     // Not expecting FCMP_FALSE and FCMP_TRUE;
64     llvm_unreachable("Unexpected FCmp predicate!");
65   }
66 }
67 
68 /// This is the complement of getICmpCode, which turns an opcode and two
69 /// operands into either a constant true or false, or a brand new ICmp
70 /// instruction. The sign is passed in to determine which kind of predicate to
71 /// use in the new icmp instruction.
72 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
73                               InstCombiner::BuilderTy *Builder) {
74   ICmpInst::Predicate NewPred;
75   if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
76     return NewConstant;
77   return Builder->CreateICmp(NewPred, LHS, RHS);
78 }
79 
80 /// This is the complement of getFCmpCode, which turns an opcode and two
81 /// operands into either a FCmp instruction. isordered is passed in to determine
82 /// which kind of predicate to use in the new fcmp instruction.
83 static Value *getFCmpValue(bool isordered, unsigned code,
84                            Value *LHS, Value *RHS,
85                            InstCombiner::BuilderTy *Builder) {
86   CmpInst::Predicate Pred;
87   switch (code) {
88   default: llvm_unreachable("Illegal FCmp code!");
89   case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
90   case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
91   case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
92   case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
93   case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
94   case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
95   case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
96   case 7:
97     if (!isordered)
98       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
99     Pred = FCmpInst::FCMP_ORD; break;
100   }
101   return Builder->CreateFCmp(Pred, LHS, RHS);
102 }
103 
104 /// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
105 /// \param I Binary operator to transform.
106 /// \return Pointer to node that must replace the original binary operator, or
107 ///         null pointer if no transformation was made.
108 Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
109   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
110 
111   // Can't do vectors.
112   if (I.getType()->isVectorTy()) return nullptr;
113 
114   // Can only do bitwise ops.
115   unsigned Op = I.getOpcode();
116   if (Op != Instruction::And && Op != Instruction::Or &&
117       Op != Instruction::Xor)
118     return nullptr;
119 
120   Value *OldLHS = I.getOperand(0);
121   Value *OldRHS = I.getOperand(1);
122   ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
123   ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
124   IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
125   IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
126   bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
127   bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
128 
129   if (!IsBswapLHS && !IsBswapRHS)
130     return nullptr;
131 
132   if (!IsBswapLHS && !ConstLHS)
133     return nullptr;
134 
135   if (!IsBswapRHS && !ConstRHS)
136     return nullptr;
137 
138   /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
139   /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
140   Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
141                   Builder->getInt(ConstLHS->getValue().byteSwap());
142 
143   Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
144                   Builder->getInt(ConstRHS->getValue().byteSwap());
145 
146   Value *BinOp = nullptr;
147   if (Op == Instruction::And)
148     BinOp = Builder->CreateAnd(NewLHS, NewRHS);
149   else if (Op == Instruction::Or)
150     BinOp = Builder->CreateOr(NewLHS, NewRHS);
151   else //if (Op == Instruction::Xor)
152     BinOp = Builder->CreateXor(NewLHS, NewRHS);
153 
154   Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
155   return Builder->CreateCall(F, BinOp);
156 }
157 
158 /// This handles expressions of the form ((val OP C1) & C2).  Where
159 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
160 /// guaranteed to be a binary operator.
161 Instruction *InstCombiner::OptAndOp(Instruction *Op,
162                                     ConstantInt *OpRHS,
163                                     ConstantInt *AndRHS,
164                                     BinaryOperator &TheAnd) {
165   Value *X = Op->getOperand(0);
166   Constant *Together = nullptr;
167   if (!Op->isShift())
168     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
169 
170   switch (Op->getOpcode()) {
171   case Instruction::Xor:
172     if (Op->hasOneUse()) {
173       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
174       Value *And = Builder->CreateAnd(X, AndRHS);
175       And->takeName(Op);
176       return BinaryOperator::CreateXor(And, Together);
177     }
178     break;
179   case Instruction::Or:
180     if (Op->hasOneUse()){
181       if (Together != OpRHS) {
182         // (X | C1) & C2 --> (X | (C1&C2)) & C2
183         Value *Or = Builder->CreateOr(X, Together);
184         Or->takeName(Op);
185         return BinaryOperator::CreateAnd(Or, AndRHS);
186       }
187 
188       ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
189       if (TogetherCI && !TogetherCI->isZero()){
190         // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
191         // NOTE: This reduces the number of bits set in the & mask, which
192         // can expose opportunities for store narrowing.
193         Together = ConstantExpr::getXor(AndRHS, Together);
194         Value *And = Builder->CreateAnd(X, Together);
195         And->takeName(Op);
196         return BinaryOperator::CreateOr(And, OpRHS);
197       }
198     }
199 
200     break;
201   case Instruction::Add:
202     if (Op->hasOneUse()) {
203       // Adding a one to a single bit bit-field should be turned into an XOR
204       // of the bit.  First thing to check is to see if this AND is with a
205       // single bit constant.
206       const APInt &AndRHSV = AndRHS->getValue();
207 
208       // If there is only one bit set.
209       if (AndRHSV.isPowerOf2()) {
210         // Ok, at this point, we know that we are masking the result of the
211         // ADD down to exactly one bit.  If the constant we are adding has
212         // no bits set below this bit, then we can eliminate the ADD.
213         const APInt& AddRHS = OpRHS->getValue();
214 
215         // Check to see if any bits below the one bit set in AndRHSV are set.
216         if ((AddRHS & (AndRHSV-1)) == 0) {
217           // If not, the only thing that can effect the output of the AND is
218           // the bit specified by AndRHSV.  If that bit is set, the effect of
219           // the XOR is to toggle the bit.  If it is clear, then the ADD has
220           // no effect.
221           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
222             TheAnd.setOperand(0, X);
223             return &TheAnd;
224           } else {
225             // Pull the XOR out of the AND.
226             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
227             NewAnd->takeName(Op);
228             return BinaryOperator::CreateXor(NewAnd, AndRHS);
229           }
230         }
231       }
232     }
233     break;
234 
235   case Instruction::Shl: {
236     // We know that the AND will not produce any of the bits shifted in, so if
237     // the anded constant includes them, clear them now!
238     //
239     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
240     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
241     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
242     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
243 
244     if (CI->getValue() == ShlMask)
245       // Masking out bits that the shift already masks.
246       return replaceInstUsesWith(TheAnd, Op);   // No need for the and.
247 
248     if (CI != AndRHS) {                  // Reducing bits set in and.
249       TheAnd.setOperand(1, CI);
250       return &TheAnd;
251     }
252     break;
253   }
254   case Instruction::LShr: {
255     // We know that the AND will not produce any of the bits shifted in, so if
256     // the anded constant includes them, clear them now!  This only applies to
257     // unsigned shifts, because a signed shr may bring in set bits!
258     //
259     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
260     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
261     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
262     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
263 
264     if (CI->getValue() == ShrMask)
265       // Masking out bits that the shift already masks.
266       return replaceInstUsesWith(TheAnd, Op);
267 
268     if (CI != AndRHS) {
269       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
270       return &TheAnd;
271     }
272     break;
273   }
274   case Instruction::AShr:
275     // Signed shr.
276     // See if this is shifting in some sign extension, then masking it out
277     // with an and.
278     if (Op->hasOneUse()) {
279       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
280       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
281       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
282       Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
283       if (C == AndRHS) {          // Masking out bits shifted in.
284         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
285         // Make the argument unsigned.
286         Value *ShVal = Op->getOperand(0);
287         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
288         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
289       }
290     }
291     break;
292   }
293   return nullptr;
294 }
295 
296 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
297 /// (V < Lo || V >= Hi).  In practice, we emit the more efficient
298 /// (V-Lo) \<u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
299 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
300 /// insert new instructions.
301 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
302                                      bool isSigned, bool Inside) {
303   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
304             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
305          "Lo is not <= Hi in range emission code!");
306 
307   if (Inside) {
308     if (Lo == Hi)  // Trivially false.
309       return Builder->getFalse();
310 
311     // V >= Min && V < Hi --> V < Hi
312     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
313       ICmpInst::Predicate pred = (isSigned ?
314         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
315       return Builder->CreateICmp(pred, V, Hi);
316     }
317 
318     // Emit V-Lo <u Hi-Lo
319     Constant *NegLo = ConstantExpr::getNeg(Lo);
320     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
321     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
322     return Builder->CreateICmpULT(Add, UpperBound);
323   }
324 
325   if (Lo == Hi)  // Trivially true.
326     return Builder->getTrue();
327 
328   // V < Min || V >= Hi -> V > Hi-1
329   Hi = SubOne(cast<ConstantInt>(Hi));
330   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
331     ICmpInst::Predicate pred = (isSigned ?
332         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
333     return Builder->CreateICmp(pred, V, Hi);
334   }
335 
336   // Emit V-Lo >u Hi-1-Lo
337   // Note that Hi has already had one subtracted from it, above.
338   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
339   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
340   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
341   return Builder->CreateICmpUGT(Add, LowerBound);
342 }
343 
344 /// Returns true iff Val consists of one contiguous run of 1s with any number
345 /// of 0s on either side.  The 1s are allowed to wrap from LSB to MSB,
346 /// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
347 /// not, since all 1s are not contiguous.
348 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
349   const APInt& V = Val->getValue();
350   uint32_t BitWidth = Val->getType()->getBitWidth();
351   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
352 
353   // look for the first zero bit after the run of ones
354   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
355   // look for the first non-zero bit
356   ME = V.getActiveBits();
357   return true;
358 }
359 
360 /// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
361 /// whether the operator is a sub. If we can fold one of the following xforms:
362 ///
363 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
364 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
365 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
366 ///
367 /// return (A +/- B).
368 ///
369 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
370                                         ConstantInt *Mask, bool isSub,
371                                         Instruction &I) {
372   Instruction *LHSI = dyn_cast<Instruction>(LHS);
373   if (!LHSI || LHSI->getNumOperands() != 2 ||
374       !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
375 
376   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
377 
378   switch (LHSI->getOpcode()) {
379   default: return nullptr;
380   case Instruction::And:
381     if (ConstantExpr::getAnd(N, Mask) == Mask) {
382       // If the AndRHS is a power of two minus one (0+1+), this is simple.
383       if ((Mask->getValue().countLeadingZeros() +
384            Mask->getValue().countPopulation()) ==
385           Mask->getValue().getBitWidth())
386         break;
387 
388       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
389       // part, we don't need any explicit masks to take them out of A.  If that
390       // is all N is, ignore it.
391       uint32_t MB = 0, ME = 0;
392       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
393         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
394         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
395         if (MaskedValueIsZero(RHS, Mask, 0, &I))
396           break;
397       }
398     }
399     return nullptr;
400   case Instruction::Or:
401   case Instruction::Xor:
402     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
403     if ((Mask->getValue().countLeadingZeros() +
404          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
405         && ConstantExpr::getAnd(N, Mask)->isNullValue())
406       break;
407     return nullptr;
408   }
409 
410   if (isSub)
411     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
412   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
413 }
414 
415 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
416 /// One of A and B is considered the mask, the other the value. This is
417 /// described as the "AMask" or "BMask" part of the enum. If the enum
418 /// contains only "Mask", then both A and B can be considered masks.
419 /// If A is the mask, then it was proven, that (A & C) == C. This
420 /// is trivial if C == A, or C == 0. If both A and C are constants, this
421 /// proof is also easy.
422 /// For the following explanations we assume that A is the mask.
423 /// The part "AllOnes" declares, that the comparison is true only
424 /// if (A & B) == A, or all bits of A are set in B.
425 ///   Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
426 /// The part "AllZeroes" declares, that the comparison is true only
427 /// if (A & B) == 0, or all bits of A are cleared in B.
428 ///   Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
429 /// The part "Mixed" declares, that (A & B) == C and C might or might not
430 /// contain any number of one bits and zero bits.
431 ///   Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
432 /// The Part "Not" means, that in above descriptions "==" should be replaced
433 /// by "!=".
434 ///   Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
435 /// If the mask A contains a single bit, then the following is equivalent:
436 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
437 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
438 enum MaskedICmpType {
439   FoldMskICmp_AMask_AllOnes           =     1,
440   FoldMskICmp_AMask_NotAllOnes        =     2,
441   FoldMskICmp_BMask_AllOnes           =     4,
442   FoldMskICmp_BMask_NotAllOnes        =     8,
443   FoldMskICmp_Mask_AllZeroes          =    16,
444   FoldMskICmp_Mask_NotAllZeroes       =    32,
445   FoldMskICmp_AMask_Mixed             =    64,
446   FoldMskICmp_AMask_NotMixed          =   128,
447   FoldMskICmp_BMask_Mixed             =   256,
448   FoldMskICmp_BMask_NotMixed          =   512
449 };
450 
451 /// Return the set of pattern classes (from MaskedICmpType)
452 /// that (icmp SCC (A & B), C) satisfies.
453 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
454                                     ICmpInst::Predicate SCC)
455 {
456   ConstantInt *ACst = dyn_cast<ConstantInt>(A);
457   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
458   ConstantInt *CCst = dyn_cast<ConstantInt>(C);
459   bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
460   bool icmp_abit = (ACst && !ACst->isZero() &&
461                     ACst->getValue().isPowerOf2());
462   bool icmp_bbit = (BCst && !BCst->isZero() &&
463                     BCst->getValue().isPowerOf2());
464   unsigned result = 0;
465   if (CCst && CCst->isZero()) {
466     // if C is zero, then both A and B qualify as mask
467     result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
468                           FoldMskICmp_Mask_AllZeroes |
469                           FoldMskICmp_AMask_Mixed |
470                           FoldMskICmp_BMask_Mixed)
471                        : (FoldMskICmp_Mask_NotAllZeroes |
472                           FoldMskICmp_Mask_NotAllZeroes |
473                           FoldMskICmp_AMask_NotMixed |
474                           FoldMskICmp_BMask_NotMixed));
475     if (icmp_abit)
476       result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
477                             FoldMskICmp_AMask_NotMixed)
478                          : (FoldMskICmp_AMask_AllOnes |
479                             FoldMskICmp_AMask_Mixed));
480     if (icmp_bbit)
481       result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
482                             FoldMskICmp_BMask_NotMixed)
483                          : (FoldMskICmp_BMask_AllOnes |
484                             FoldMskICmp_BMask_Mixed));
485     return result;
486   }
487   if (A == C) {
488     result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
489                           FoldMskICmp_AMask_Mixed)
490                        : (FoldMskICmp_AMask_NotAllOnes |
491                           FoldMskICmp_AMask_NotMixed));
492     if (icmp_abit)
493       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
494                             FoldMskICmp_AMask_NotMixed)
495                          : (FoldMskICmp_Mask_AllZeroes |
496                             FoldMskICmp_AMask_Mixed));
497   } else if (ACst && CCst &&
498              ConstantExpr::getAnd(ACst, CCst) == CCst) {
499     result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
500                        : FoldMskICmp_AMask_NotMixed);
501   }
502   if (B == C) {
503     result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
504                           FoldMskICmp_BMask_Mixed)
505                        : (FoldMskICmp_BMask_NotAllOnes |
506                           FoldMskICmp_BMask_NotMixed));
507     if (icmp_bbit)
508       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
509                             FoldMskICmp_BMask_NotMixed)
510                          : (FoldMskICmp_Mask_AllZeroes |
511                             FoldMskICmp_BMask_Mixed));
512   } else if (BCst && CCst &&
513              ConstantExpr::getAnd(BCst, CCst) == CCst) {
514     result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
515                        : FoldMskICmp_BMask_NotMixed);
516   }
517   return result;
518 }
519 
520 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
521 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
522 /// is adjacent to the corresponding normal flag (recording ==), this just
523 /// involves swapping those bits over.
524 static unsigned conjugateICmpMask(unsigned Mask) {
525   unsigned NewMask;
526   NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
527                      FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
528                      FoldMskICmp_BMask_Mixed))
529             << 1;
530 
531   NewMask |=
532       (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
533                FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
534                FoldMskICmp_BMask_NotMixed))
535       >> 1;
536 
537   return NewMask;
538 }
539 
540 /// Decompose an icmp into the form ((X & Y) pred Z) if possible.
541 /// The returned predicate is either == or !=. Returns false if
542 /// decomposition fails.
543 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
544                                  Value *&X, Value *&Y, Value *&Z) {
545   ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
546   if (!C)
547     return false;
548 
549   switch (I->getPredicate()) {
550   default:
551     return false;
552   case ICmpInst::ICMP_SLT:
553     // X < 0 is equivalent to (X & SignBit) != 0.
554     if (!C->isZero())
555       return false;
556     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
557     Pred = ICmpInst::ICMP_NE;
558     break;
559   case ICmpInst::ICMP_SGT:
560     // X > -1 is equivalent to (X & SignBit) == 0.
561     if (!C->isAllOnesValue())
562       return false;
563     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
564     Pred = ICmpInst::ICMP_EQ;
565     break;
566   case ICmpInst::ICMP_ULT:
567     // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
568     if (!C->getValue().isPowerOf2())
569       return false;
570     Y = ConstantInt::get(I->getContext(), -C->getValue());
571     Pred = ICmpInst::ICMP_EQ;
572     break;
573   case ICmpInst::ICMP_UGT:
574     // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
575     if (!(C->getValue() + 1).isPowerOf2())
576       return false;
577     Y = ConstantInt::get(I->getContext(), ~C->getValue());
578     Pred = ICmpInst::ICMP_NE;
579     break;
580   }
581 
582   X = I->getOperand(0);
583   Z = ConstantInt::getNullValue(C->getType());
584   return true;
585 }
586 
587 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
588 /// Return the set of pattern classes (from MaskedICmpType)
589 /// that both LHS and RHS satisfy.
590 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
591                                              Value*& B, Value*& C,
592                                              Value*& D, Value*& E,
593                                              ICmpInst *LHS, ICmpInst *RHS,
594                                              ICmpInst::Predicate &LHSCC,
595                                              ICmpInst::Predicate &RHSCC) {
596   if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
597   // vectors are not (yet?) supported
598   if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
599 
600   // Here comes the tricky part:
601   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
602   // and L11 & L12 == L21 & L22. The same goes for RHS.
603   // Now we must find those components L** and R**, that are equal, so
604   // that we can extract the parameters A, B, C, D, and E for the canonical
605   // above.
606   Value *L1 = LHS->getOperand(0);
607   Value *L2 = LHS->getOperand(1);
608   Value *L11,*L12,*L21,*L22;
609   // Check whether the icmp can be decomposed into a bit test.
610   if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
611     L21 = L22 = L1 = nullptr;
612   } else {
613     // Look for ANDs in the LHS icmp.
614     if (!L1->getType()->isIntegerTy()) {
615       // You can icmp pointers, for example. They really aren't masks.
616       L11 = L12 = nullptr;
617     } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
618       // Any icmp can be viewed as being trivially masked; if it allows us to
619       // remove one, it's worth it.
620       L11 = L1;
621       L12 = Constant::getAllOnesValue(L1->getType());
622     }
623 
624     if (!L2->getType()->isIntegerTy()) {
625       // You can icmp pointers, for example. They really aren't masks.
626       L21 = L22 = nullptr;
627     } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
628       L21 = L2;
629       L22 = Constant::getAllOnesValue(L2->getType());
630     }
631   }
632 
633   // Bail if LHS was a icmp that can't be decomposed into an equality.
634   if (!ICmpInst::isEquality(LHSCC))
635     return 0;
636 
637   Value *R1 = RHS->getOperand(0);
638   Value *R2 = RHS->getOperand(1);
639   Value *R11,*R12;
640   bool ok = false;
641   if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
642     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
643       A = R11; D = R12;
644     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
645       A = R12; D = R11;
646     } else {
647       return 0;
648     }
649     E = R2; R1 = nullptr; ok = true;
650   } else if (R1->getType()->isIntegerTy()) {
651     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
652       // As before, model no mask as a trivial mask if it'll let us do an
653       // optimization.
654       R11 = R1;
655       R12 = Constant::getAllOnesValue(R1->getType());
656     }
657 
658     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
659       A = R11; D = R12; E = R2; ok = true;
660     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
661       A = R12; D = R11; E = R2; ok = true;
662     }
663   }
664 
665   // Bail if RHS was a icmp that can't be decomposed into an equality.
666   if (!ICmpInst::isEquality(RHSCC))
667     return 0;
668 
669   // Look for ANDs in on the right side of the RHS icmp.
670   if (!ok && R2->getType()->isIntegerTy()) {
671     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
672       R11 = R2;
673       R12 = Constant::getAllOnesValue(R2->getType());
674     }
675 
676     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
677       A = R11; D = R12; E = R1; ok = true;
678     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
679       A = R12; D = R11; E = R1; ok = true;
680     } else {
681       return 0;
682     }
683   }
684   if (!ok)
685     return 0;
686 
687   if (L11 == A) {
688     B = L12; C = L2;
689   } else if (L12 == A) {
690     B = L11; C = L2;
691   } else if (L21 == A) {
692     B = L22; C = L1;
693   } else if (L22 == A) {
694     B = L21; C = L1;
695   }
696 
697   unsigned LeftType = getTypeOfMaskedICmp(A, B, C, LHSCC);
698   unsigned RightType = getTypeOfMaskedICmp(A, D, E, RHSCC);
699   return LeftType & RightType;
700 }
701 
702 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
703 /// into a single (icmp(A & X) ==/!= Y).
704 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
705                                      llvm::InstCombiner::BuilderTy *Builder) {
706   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
707   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
708   unsigned Mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
709                                                LHSCC, RHSCC);
710   if (Mask == 0) return nullptr;
711   assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
712          "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
713 
714   // In full generality:
715   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
716   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
717   //
718   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
719   // equivalent to (icmp (A & X) !Op Y).
720   //
721   // Therefore, we can pretend for the rest of this function that we're dealing
722   // with the conjunction, provided we flip the sense of any comparisons (both
723   // input and output).
724 
725   // In most cases we're going to produce an EQ for the "&&" case.
726   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
727   if (!IsAnd) {
728     // Convert the masking analysis into its equivalent with negated
729     // comparisons.
730     Mask = conjugateICmpMask(Mask);
731   }
732 
733   if (Mask & FoldMskICmp_Mask_AllZeroes) {
734     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
735     // -> (icmp eq (A & (B|D)), 0)
736     Value *NewOr = Builder->CreateOr(B, D);
737     Value *NewAnd = Builder->CreateAnd(A, NewOr);
738     // We can't use C as zero because we might actually handle
739     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
740     // with B and D, having a single bit set.
741     Value *Zero = Constant::getNullValue(A->getType());
742     return Builder->CreateICmp(NewCC, NewAnd, Zero);
743   }
744   if (Mask & FoldMskICmp_BMask_AllOnes) {
745     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
746     // -> (icmp eq (A & (B|D)), (B|D))
747     Value *NewOr = Builder->CreateOr(B, D);
748     Value *NewAnd = Builder->CreateAnd(A, NewOr);
749     return Builder->CreateICmp(NewCC, NewAnd, NewOr);
750   }
751   if (Mask & FoldMskICmp_AMask_AllOnes) {
752     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
753     // -> (icmp eq (A & (B&D)), A)
754     Value *NewAnd1 = Builder->CreateAnd(B, D);
755     Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
756     return Builder->CreateICmp(NewCC, NewAnd2, A);
757   }
758 
759   // Remaining cases assume at least that B and D are constant, and depend on
760   // their actual values. This isn't strictly necessary, just a "handle the
761   // easy cases for now" decision.
762   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
763   if (!BCst) return nullptr;
764   ConstantInt *DCst = dyn_cast<ConstantInt>(D);
765   if (!DCst) return nullptr;
766 
767   if (Mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
768     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
769     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
770     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
771     // Only valid if one of the masks is a superset of the other (check "B&D" is
772     // the same as either B or D).
773     APInt NewMask = BCst->getValue() & DCst->getValue();
774 
775     if (NewMask == BCst->getValue())
776       return LHS;
777     else if (NewMask == DCst->getValue())
778       return RHS;
779   }
780   if (Mask & FoldMskICmp_AMask_NotAllOnes) {
781     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
782     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
783     // Only valid if one of the masks is a superset of the other (check "B|D" is
784     // the same as either B or D).
785     APInt NewMask = BCst->getValue() | DCst->getValue();
786 
787     if (NewMask == BCst->getValue())
788       return LHS;
789     else if (NewMask == DCst->getValue())
790       return RHS;
791   }
792   if (Mask & FoldMskICmp_BMask_Mixed) {
793     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
794     // We already know that B & C == C && D & E == E.
795     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
796     // C and E, which are shared by both the mask B and the mask D, don't
797     // contradict, then we can transform to
798     // -> (icmp eq (A & (B|D)), (C|E))
799     // Currently, we only handle the case of B, C, D, and E being constant.
800     // We can't simply use C and E because we might actually handle
801     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
802     // with B and D, having a single bit set.
803     ConstantInt *CCst = dyn_cast<ConstantInt>(C);
804     if (!CCst) return nullptr;
805     ConstantInt *ECst = dyn_cast<ConstantInt>(E);
806     if (!ECst) return nullptr;
807     if (LHSCC != NewCC)
808       CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
809     if (RHSCC != NewCC)
810       ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
811     // If there is a conflict, we should actually return a false for the
812     // whole construct.
813     if (((BCst->getValue() & DCst->getValue()) &
814          (CCst->getValue() ^ ECst->getValue())) != 0)
815       return ConstantInt::get(LHS->getType(), !IsAnd);
816     Value *NewOr1 = Builder->CreateOr(B, D);
817     Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
818     Value *NewAnd = Builder->CreateAnd(A, NewOr1);
819     return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
820   }
821   return nullptr;
822 }
823 
824 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
825 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
826 /// If \p Inverted is true then the check is for the inverted range, e.g.
827 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
828 Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
829                                         bool Inverted) {
830   // Check the lower range comparison, e.g. x >= 0
831   // InstCombine already ensured that if there is a constant it's on the RHS.
832   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
833   if (!RangeStart)
834     return nullptr;
835 
836   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
837                                Cmp0->getPredicate());
838 
839   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
840   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
841         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
842     return nullptr;
843 
844   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
845                                Cmp1->getPredicate());
846 
847   Value *Input = Cmp0->getOperand(0);
848   Value *RangeEnd;
849   if (Cmp1->getOperand(0) == Input) {
850     // For the upper range compare we have: icmp x, n
851     RangeEnd = Cmp1->getOperand(1);
852   } else if (Cmp1->getOperand(1) == Input) {
853     // For the upper range compare we have: icmp n, x
854     RangeEnd = Cmp1->getOperand(0);
855     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
856   } else {
857     return nullptr;
858   }
859 
860   // Check the upper range comparison, e.g. x < n
861   ICmpInst::Predicate NewPred;
862   switch (Pred1) {
863     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
864     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
865     default: return nullptr;
866   }
867 
868   // This simplification is only valid if the upper range is not negative.
869   bool IsNegative, IsNotNegative;
870   ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
871   if (!IsNotNegative)
872     return nullptr;
873 
874   if (Inverted)
875     NewPred = ICmpInst::getInversePredicate(NewPred);
876 
877   return Builder->CreateICmp(NewPred, Input, RangeEnd);
878 }
879 
880 /// Fold (icmp)&(icmp) if possible.
881 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
882   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
883 
884   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
885   if (PredicatesFoldable(LHSCC, RHSCC)) {
886     if (LHS->getOperand(0) == RHS->getOperand(1) &&
887         LHS->getOperand(1) == RHS->getOperand(0))
888       LHS->swapOperands();
889     if (LHS->getOperand(0) == RHS->getOperand(0) &&
890         LHS->getOperand(1) == RHS->getOperand(1)) {
891       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
892       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
893       bool isSigned = LHS->isSigned() || RHS->isSigned();
894       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
895     }
896   }
897 
898   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
899   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
900     return V;
901 
902   // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
903   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
904     return V;
905 
906   // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
907   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
908     return V;
909 
910   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
911   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
912   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
913   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
914   if (!LHSCst || !RHSCst) return nullptr;
915 
916   if (LHSCst == RHSCst && LHSCC == RHSCC) {
917     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
918     // where C is a power of 2 or
919     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
920     if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
921         (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
922       Value *NewOr = Builder->CreateOr(Val, Val2);
923       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
924     }
925   }
926 
927   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
928   // where CMAX is the all ones value for the truncated type,
929   // iff the lower bits of C2 and CA are zero.
930   if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
931       LHS->hasOneUse() && RHS->hasOneUse()) {
932     Value *V;
933     ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
934 
935     // (trunc x) == C1 & (and x, CA) == C2
936     // (and x, CA) == C2 & (trunc x) == C1
937     if (match(Val2, m_Trunc(m_Value(V))) &&
938         match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
939       SmallCst = RHSCst;
940       BigCst = LHSCst;
941     } else if (match(Val, m_Trunc(m_Value(V))) &&
942                match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
943       SmallCst = LHSCst;
944       BigCst = RHSCst;
945     }
946 
947     if (SmallCst && BigCst) {
948       unsigned BigBitSize = BigCst->getType()->getBitWidth();
949       unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
950 
951       // Check that the low bits are zero.
952       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
953       if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
954         Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
955         APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
956         Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
957         return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
958       }
959     }
960   }
961 
962   // From here on, we only handle:
963   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
964   if (Val != Val2) return nullptr;
965 
966   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
967   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
968       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
969       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
970       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
971     return nullptr;
972 
973   // Make a constant range that's the intersection of the two icmp ranges.
974   // If the intersection is empty, we know that the result is false.
975   ConstantRange LHSRange =
976       ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
977   ConstantRange RHSRange =
978       ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
979 
980   if (LHSRange.intersectWith(RHSRange).isEmptySet())
981     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
982 
983   // We can't fold (ugt x, C) & (sgt x, C2).
984   if (!PredicatesFoldable(LHSCC, RHSCC))
985     return nullptr;
986 
987   // Ensure that the larger constant is on the RHS.
988   bool ShouldSwap;
989   if (CmpInst::isSigned(LHSCC) ||
990       (ICmpInst::isEquality(LHSCC) &&
991        CmpInst::isSigned(RHSCC)))
992     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
993   else
994     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
995 
996   if (ShouldSwap) {
997     std::swap(LHS, RHS);
998     std::swap(LHSCst, RHSCst);
999     std::swap(LHSCC, RHSCC);
1000   }
1001 
1002   // At this point, we know we have two icmp instructions
1003   // comparing a value against two constants and and'ing the result
1004   // together.  Because of the above check, we know that we only have
1005   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1006   // (from the icmp folding check above), that the two constants
1007   // are not equal and that the larger constant is on the RHS
1008   assert(LHSCst != RHSCst && "Compares not folded above?");
1009 
1010   switch (LHSCC) {
1011   default: llvm_unreachable("Unknown integer condition code!");
1012   case ICmpInst::ICMP_EQ:
1013     switch (RHSCC) {
1014     default: llvm_unreachable("Unknown integer condition code!");
1015     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
1016     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
1017     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
1018       return LHS;
1019     }
1020   case ICmpInst::ICMP_NE:
1021     switch (RHSCC) {
1022     default: llvm_unreachable("Unknown integer condition code!");
1023     case ICmpInst::ICMP_ULT:
1024       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
1025         return Builder->CreateICmpULT(Val, LHSCst);
1026       if (LHSCst->isNullValue())    // (X !=  0 & X u< 14) -> X-1 u< 13
1027         return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1028       break;                        // (X != 13 & X u< 15) -> no change
1029     case ICmpInst::ICMP_SLT:
1030       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
1031         return Builder->CreateICmpSLT(Val, LHSCst);
1032       break;                        // (X != 13 & X s< 15) -> no change
1033     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
1034     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
1035     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
1036       return RHS;
1037     case ICmpInst::ICMP_NE:
1038       // Special case to get the ordering right when the values wrap around
1039       // zero.
1040       if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
1041         std::swap(LHSCst, RHSCst);
1042       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1043         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1044         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1045         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1046                                       Val->getName()+".cmp");
1047       }
1048       break;                        // (X != 13 & X != 15) -> no change
1049     }
1050     break;
1051   case ICmpInst::ICMP_ULT:
1052     switch (RHSCC) {
1053     default: llvm_unreachable("Unknown integer condition code!");
1054     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
1055     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
1056       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1057     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
1058       break;
1059     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
1060     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
1061       return LHS;
1062     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
1063       break;
1064     }
1065     break;
1066   case ICmpInst::ICMP_SLT:
1067     switch (RHSCC) {
1068     default: llvm_unreachable("Unknown integer condition code!");
1069     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
1070       break;
1071     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
1072     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
1073       return LHS;
1074     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
1075       break;
1076     }
1077     break;
1078   case ICmpInst::ICMP_UGT:
1079     switch (RHSCC) {
1080     default: llvm_unreachable("Unknown integer condition code!");
1081     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
1082     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
1083       return RHS;
1084     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
1085       break;
1086     case ICmpInst::ICMP_NE:
1087       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
1088         return Builder->CreateICmp(LHSCC, Val, RHSCst);
1089       break;                        // (X u> 13 & X != 15) -> no change
1090     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
1091       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1092     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
1093       break;
1094     }
1095     break;
1096   case ICmpInst::ICMP_SGT:
1097     switch (RHSCC) {
1098     default: llvm_unreachable("Unknown integer condition code!");
1099     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
1100     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
1101       return RHS;
1102     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
1103       break;
1104     case ICmpInst::ICMP_NE:
1105       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1106         return Builder->CreateICmp(LHSCC, Val, RHSCst);
1107       break;                        // (X s> 13 & X != 15) -> no change
1108     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
1109       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1110     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
1111       break;
1112     }
1113     break;
1114   }
1115 
1116   return nullptr;
1117 }
1118 
1119 /// Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of instcombine, this returns
1120 /// a Value which should already be inserted into the function.
1121 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1122   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1123       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1124     if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1125       return nullptr;
1126 
1127     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
1128     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1129       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1130         // If either of the constants are nans, then the whole thing returns
1131         // false.
1132         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1133           return Builder->getFalse();
1134         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1135       }
1136 
1137     // Handle vector zeros.  This occurs because the canonical form of
1138     // "fcmp ord x,x" is "fcmp ord x, 0".
1139     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1140         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1141       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1142     return nullptr;
1143   }
1144 
1145   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1146   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1147   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1148 
1149 
1150   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1151     // Swap RHS operands to match LHS.
1152     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1153     std::swap(Op1LHS, Op1RHS);
1154   }
1155 
1156   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1157     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1158     if (Op0CC == Op1CC)
1159       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1160     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1161       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1162     if (Op0CC == FCmpInst::FCMP_TRUE)
1163       return RHS;
1164     if (Op1CC == FCmpInst::FCMP_TRUE)
1165       return LHS;
1166 
1167     bool Op0Ordered;
1168     bool Op1Ordered;
1169     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1170     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1171     // uno && ord -> false
1172     if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1173         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1174     if (Op1Pred == 0) {
1175       std::swap(LHS, RHS);
1176       std::swap(Op0Pred, Op1Pred);
1177       std::swap(Op0Ordered, Op1Ordered);
1178     }
1179     if (Op0Pred == 0) {
1180       // uno && ueq -> uno && (uno || eq) -> uno
1181       // ord && olt -> ord && (ord && lt) -> olt
1182       if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1183         return LHS;
1184       if (Op0Ordered && (Op0Ordered == Op1Ordered))
1185         return RHS;
1186 
1187       // uno && oeq -> uno && (ord && eq) -> false
1188       if (!Op0Ordered)
1189         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1190       // ord && ueq -> ord && (uno || eq) -> oeq
1191       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1192     }
1193   }
1194 
1195   return nullptr;
1196 }
1197 
1198 /// Match De Morgan's Laws:
1199 /// (~A & ~B) == (~(A | B))
1200 /// (~A | ~B) == (~(A & B))
1201 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1202                                        InstCombiner::BuilderTy *Builder) {
1203   auto Opcode = I.getOpcode();
1204   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1205          "Trying to match De Morgan's Laws with something other than and/or");
1206   // Flip the logic operation.
1207   if (Opcode == Instruction::And)
1208     Opcode = Instruction::Or;
1209   else
1210     Opcode = Instruction::And;
1211 
1212   Value *Op0 = I.getOperand(0);
1213   Value *Op1 = I.getOperand(1);
1214   // TODO: Use pattern matchers instead of dyn_cast.
1215   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1216     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1217       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1218         Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1219                                               I.getName() + ".demorgan");
1220         return BinaryOperator::CreateNot(LogicOp);
1221       }
1222 
1223   // De Morgan's Law in disguise:
1224   // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
1225   // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
1226   Value *A = nullptr;
1227   Value *B = nullptr;
1228   ConstantInt *C1 = nullptr;
1229   if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
1230       match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
1231     // TODO: This check could be loosened to handle different type sizes.
1232     // Alternatively, we could fix the definition of m_Not to recognize a not
1233     // operation hidden by a zext?
1234     if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
1235         C1->isOne()) {
1236       Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
1237                                             I.getName() + ".demorgan");
1238       Value *Not = Builder->CreateNot(LogicOp);
1239       return CastInst::CreateZExtOrBitCast(Not, I.getType());
1240     }
1241   }
1242 
1243   return nullptr;
1244 }
1245 
1246 Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
1247   auto LogicOpc = I.getOpcode();
1248   assert((LogicOpc == Instruction::And || LogicOpc == Instruction::Or ||
1249           LogicOpc == Instruction::Xor) &&
1250          "Unexpected opcode for bitwise logic folding");
1251 
1252   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1253   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1254   if (!Cast0)
1255     return nullptr;
1256 
1257   // This must be a cast from an integer or integer vector source type to allow
1258   // transformation of the logic operation to the source type.
1259   Type *DestTy = I.getType();
1260   Type *SrcTy = Cast0->getSrcTy();
1261   if (!SrcTy->isIntOrIntVectorTy())
1262     return nullptr;
1263 
1264   // If one operand is a bitcast and the other is a constant, move the logic
1265   // operation ahead of the bitcast. That is, do the logic operation in the
1266   // original type. This can eliminate useless bitcasts and allow normal
1267   // combines that would otherwise be impeded by the bitcast. Canonicalization
1268   // ensures that if there is a constant operand, it will be the second operand.
1269   Value *BC = nullptr;
1270   Constant *C = nullptr;
1271   if ((match(Op0, m_BitCast(m_Value(BC))) && match(Op1, m_Constant(C)))) {
1272     // A bitcast of a constant will be removed.
1273     Value *NewConstant = Builder->CreateBitCast(C, SrcTy);
1274     Value *NewOp = Builder->CreateBinOp(LogicOpc, BC, NewConstant, I.getName());
1275     return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1276   }
1277 
1278   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1279   if (!Cast1)
1280     return nullptr;
1281 
1282   // Both operands of the logic operation are casts. The casts must be of the
1283   // same type for reduction.
1284   auto CastOpcode = Cast0->getOpcode();
1285   if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
1286     return nullptr;
1287 
1288   Value *Cast0Src = Cast0->getOperand(0);
1289   Value *Cast1Src = Cast1->getOperand(0);
1290 
1291   // fold (logic (cast A), (cast B)) -> (cast (logic A, B))
1292 
1293   // Only do this if the casts both really cause code to be generated.
1294   if ((!isa<ICmpInst>(Cast0Src) || !isa<ICmpInst>(Cast1Src)) &&
1295       ShouldOptimizeCast(CastOpcode, Cast0Src, DestTy) &&
1296       ShouldOptimizeCast(CastOpcode, Cast1Src, DestTy)) {
1297     Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1298                                         I.getName());
1299     return CastInst::Create(CastOpcode, NewOp, DestTy);
1300   }
1301 
1302   // For now, only 'and'/'or' have optimizations after this.
1303   if (LogicOpc == Instruction::Xor)
1304     return nullptr;
1305 
1306   // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1307   // cast is otherwise not optimizable.  This happens for vector sexts.
1308   ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1309   ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1310   if (ICmp0 && ICmp1) {
1311     Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1312                                               : FoldOrOfICmps(ICmp0, ICmp1, &I);
1313     if (Res)
1314       return CastInst::Create(CastOpcode, Res, DestTy);
1315     return nullptr;
1316   }
1317 
1318   // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1319   // cast is otherwise not optimizable.  This happens for vector sexts.
1320   FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1321   FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1322   if (FCmp0 && FCmp1) {
1323     Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1324                                               : FoldOrOfFCmps(FCmp0, FCmp1);
1325     if (Res)
1326       return CastInst::Create(CastOpcode, Res, DestTy);
1327     return nullptr;
1328   }
1329 
1330   return nullptr;
1331 }
1332 
1333 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1334   bool Changed = SimplifyAssociativeOrCommutative(I);
1335   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1336 
1337   if (Value *V = SimplifyVectorOp(I))
1338     return replaceInstUsesWith(I, V);
1339 
1340   if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
1341     return replaceInstUsesWith(I, V);
1342 
1343   // (A|B)&(A|C) -> A|(B&C) etc
1344   if (Value *V = SimplifyUsingDistributiveLaws(I))
1345     return replaceInstUsesWith(I, V);
1346 
1347   // See if we can simplify any instructions used by the instruction whose sole
1348   // purpose is to compute bits we don't care about.
1349   if (SimplifyDemandedInstructionBits(I))
1350     return &I;
1351 
1352   if (Value *V = SimplifyBSwap(I))
1353     return replaceInstUsesWith(I, V);
1354 
1355   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1356     const APInt &AndRHSMask = AndRHS->getValue();
1357 
1358     // Optimize a variety of ((val OP C1) & C2) combinations...
1359     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1360       Value *Op0LHS = Op0I->getOperand(0);
1361       Value *Op0RHS = Op0I->getOperand(1);
1362       switch (Op0I->getOpcode()) {
1363       default: break;
1364       case Instruction::Xor:
1365       case Instruction::Or: {
1366         // If the mask is only needed on one incoming arm, push it up.
1367         if (!Op0I->hasOneUse()) break;
1368 
1369         APInt NotAndRHS(~AndRHSMask);
1370         if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
1371           // Not masking anything out for the LHS, move to RHS.
1372           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1373                                              Op0RHS->getName()+".masked");
1374           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1375         }
1376         if (!isa<Constant>(Op0RHS) &&
1377             MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
1378           // Not masking anything out for the RHS, move to LHS.
1379           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1380                                              Op0LHS->getName()+".masked");
1381           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1382         }
1383 
1384         break;
1385       }
1386       case Instruction::Add:
1387         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1388         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1389         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1390         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1391           return BinaryOperator::CreateAnd(V, AndRHS);
1392         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1393           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
1394         break;
1395 
1396       case Instruction::Sub:
1397         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1398         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1399         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1400         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1401           return BinaryOperator::CreateAnd(V, AndRHS);
1402 
1403         // -x & 1 -> x & 1
1404         if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1405           return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1406 
1407         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1408         // has 1's for all bits that the subtraction with A might affect.
1409         if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1410           uint32_t BitWidth = AndRHSMask.getBitWidth();
1411           uint32_t Zeros = AndRHSMask.countLeadingZeros();
1412           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1413 
1414           if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
1415             Value *NewNeg = Builder->CreateNeg(Op0RHS);
1416             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1417           }
1418         }
1419         break;
1420 
1421       case Instruction::Shl:
1422       case Instruction::LShr:
1423         // (1 << x) & 1 --> zext(x == 0)
1424         // (1 >> x) & 1 --> zext(x == 0)
1425         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1426           Value *NewICmp =
1427             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1428           return new ZExtInst(NewICmp, I.getType());
1429         }
1430         break;
1431       }
1432 
1433       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1434         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1435           return Res;
1436     }
1437 
1438     // If this is an integer truncation, and if the source is an 'and' with
1439     // immediate, transform it.  This frequently occurs for bitfield accesses.
1440     {
1441       Value *X = nullptr; ConstantInt *YC = nullptr;
1442       if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1443         // Change: and (trunc (and X, YC) to T), C2
1444         // into  : and (trunc X to T), trunc(YC) & C2
1445         // This will fold the two constants together, which may allow
1446         // other simplifications.
1447         Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1448         Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1449         C3 = ConstantExpr::getAnd(C3, AndRHS);
1450         return BinaryOperator::CreateAnd(NewCast, C3);
1451       }
1452     }
1453 
1454     // Try to fold constant and into select arguments.
1455     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1456       if (Instruction *R = FoldOpIntoSelect(I, SI))
1457         return R;
1458     if (isa<PHINode>(Op0))
1459       if (Instruction *NV = FoldOpIntoPhi(I))
1460         return NV;
1461   }
1462 
1463   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1464     return DeMorgan;
1465 
1466   {
1467     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
1468     // (A|B) & ~(A&B) -> A^B
1469     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1470         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1471         ((A == C && B == D) || (A == D && B == C)))
1472       return BinaryOperator::CreateXor(A, B);
1473 
1474     // ~(A&B) & (A|B) -> A^B
1475     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1476         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1477         ((A == C && B == D) || (A == D && B == C)))
1478       return BinaryOperator::CreateXor(A, B);
1479 
1480     // A&(A^B) => A & ~B
1481     {
1482       Value *tmpOp0 = Op0;
1483       Value *tmpOp1 = Op1;
1484       if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1485         if (A == Op1 || B == Op1 ) {
1486           tmpOp1 = Op0;
1487           tmpOp0 = Op1;
1488           // Simplify below
1489         }
1490       }
1491 
1492       if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1493         if (B == tmpOp0) {
1494           std::swap(A, B);
1495         }
1496         // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
1497         // A is originally -1 (or a vector of -1 and undefs), then we enter
1498         // an endless loop. By checking that A is non-constant we ensure that
1499         // we will never get to the loop.
1500         if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1501           return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1502       }
1503     }
1504 
1505     // (A&((~A)|B)) -> A&B
1506     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1507         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1508       return BinaryOperator::CreateAnd(A, Op1);
1509     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1510         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1511       return BinaryOperator::CreateAnd(A, Op0);
1512 
1513     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1514     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1515       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1516         if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1517           return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1518 
1519     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1520     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1521       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1522         if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1523           return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1524 
1525     // (A | B) & ((~A) ^ B) -> (A & B)
1526     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1527         match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1528       return BinaryOperator::CreateAnd(A, B);
1529 
1530     // ((~A) ^ B) & (A | B) -> (A & B)
1531     if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1532         match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1533       return BinaryOperator::CreateAnd(A, B);
1534   }
1535 
1536   {
1537     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1538     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1539     if (LHS && RHS)
1540       if (Value *Res = FoldAndOfICmps(LHS, RHS))
1541         return replaceInstUsesWith(I, Res);
1542 
1543     // TODO: Make this recursive; it's a little tricky because an arbitrary
1544     // number of 'and' instructions might have to be created.
1545     Value *X, *Y;
1546     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1547       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1548         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1549           return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1550       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1551         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1552           return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1553     }
1554     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1555       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1556         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1557           return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1558       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1559         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1560           return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1561     }
1562   }
1563 
1564   // If and'ing two fcmp, try combine them into one.
1565   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1566     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1567       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1568         return replaceInstUsesWith(I, Res);
1569 
1570   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1571     return CastedAnd;
1572 
1573   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1574     Value *Op0COp = Op0C->getOperand(0);
1575     Type *SrcTy = Op0COp->getType();
1576 
1577     // If we are masking off the sign bit of a floating-point value, convert
1578     // this to the canonical fabs intrinsic call and cast back to integer.
1579     // The backend should know how to optimize fabs().
1580     // TODO: This transform should also apply to vectors.
1581     ConstantInt *CI;
1582     if (isa<BitCastInst>(Op0C) && SrcTy->isFloatingPointTy() &&
1583         match(Op1, m_ConstantInt(CI)) && CI->isMaxValue(true)) {
1584       Module *M = I.getModule();
1585       Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, SrcTy);
1586       Value *Call = Builder->CreateCall(Fabs, Op0COp, "fabs");
1587       return CastInst::CreateBitOrPointerCast(Call, I.getType());
1588     }
1589   }
1590 
1591   {
1592     Value *X = nullptr;
1593     bool OpsSwapped = false;
1594     // Canonicalize SExt or Not to the LHS
1595     if (match(Op1, m_SExt(m_Value())) ||
1596         match(Op1, m_Not(m_Value()))) {
1597       std::swap(Op0, Op1);
1598       OpsSwapped = true;
1599     }
1600 
1601     // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1602     if (match(Op0, m_SExt(m_Value(X))) &&
1603         X->getType()->getScalarType()->isIntegerTy(1)) {
1604       Value *Zero = Constant::getNullValue(Op1->getType());
1605       return SelectInst::Create(X, Op1, Zero);
1606     }
1607 
1608     // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1609     if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1610         X->getType()->getScalarType()->isIntegerTy(1)) {
1611       Value *Zero = Constant::getNullValue(Op0->getType());
1612       return SelectInst::Create(X, Zero, Op1);
1613     }
1614 
1615     if (OpsSwapped)
1616       std::swap(Op0, Op1);
1617   }
1618 
1619   return Changed ? &I : nullptr;
1620 }
1621 
1622 /// Given an OR instruction, check to see if this is a bswap or bitreverse
1623 /// idiom. If so, insert the new intrinsic and return it.
1624 Instruction *InstCombiner::MatchBSwapOrBitReverse(BinaryOperator &I) {
1625   SmallVector<Instruction*, 4> Insts;
1626   if (!recognizeBitReverseOrBSwapIdiom(&I, true, false, Insts))
1627     return nullptr;
1628   Instruction *LastInst = Insts.pop_back_val();
1629   LastInst->removeFromParent();
1630 
1631   for (auto *Inst : Insts)
1632     Worklist.Add(Inst);
1633   return LastInst;
1634 }
1635 
1636 /// We have an expression of the form (A&C)|(B&D).  Check if A is (cond?-1:0)
1637 /// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
1638 /// expression to "cond ? C : D or B".
1639 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1640                                          Value *C, Value *D) {
1641   // If A is not a select of -1/0, this cannot match.
1642   Value *Cond = nullptr;
1643   if (!match(A, m_SExt(m_Value(Cond))) ||
1644       !Cond->getType()->isIntegerTy(1))
1645     return nullptr;
1646 
1647   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1648   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1649     return SelectInst::Create(Cond, C, B);
1650   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1651     return SelectInst::Create(Cond, C, B);
1652 
1653   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1654   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1655     return SelectInst::Create(Cond, C, D);
1656   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1657     return SelectInst::Create(Cond, C, D);
1658   return nullptr;
1659 }
1660 
1661 /// Fold (icmp)|(icmp) if possible.
1662 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1663                                    Instruction *CxtI) {
1664   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1665 
1666   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
1667   // if K1 and K2 are a one-bit mask.
1668   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1669   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1670 
1671   if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1672       RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1673 
1674     BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1675     BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1676     if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1677         LAnd->getOpcode() == Instruction::And &&
1678         RAnd->getOpcode() == Instruction::And) {
1679 
1680       Value *Mask = nullptr;
1681       Value *Masked = nullptr;
1682       if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1683           isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1684                                  DT) &&
1685           isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1686                                  DT)) {
1687         Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1688         Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1689       } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1690                  isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1691                                         CxtI, DT) &&
1692                  isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1693                                         CxtI, DT)) {
1694         Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1695         Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1696       }
1697 
1698       if (Masked)
1699         return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1700     }
1701   }
1702 
1703   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1704   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1705   // The original condition actually refers to the following two ranges:
1706   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1707   // We can fold these two ranges if:
1708   // 1) C1 and C2 is unsigned greater than C3.
1709   // 2) The two ranges are separated.
1710   // 3) C1 ^ C2 is one-bit mask.
1711   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1712   // This implies all values in the two ranges differ by exactly one bit.
1713 
1714   if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1715       LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1716       RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1717       LHSCst->getValue() == (RHSCst->getValue())) {
1718 
1719     Value *LAdd = LHS->getOperand(0);
1720     Value *RAdd = RHS->getOperand(0);
1721 
1722     Value *LAddOpnd, *RAddOpnd;
1723     ConstantInt *LAddCst, *RAddCst;
1724     if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1725         match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1726         LAddCst->getValue().ugt(LHSCst->getValue()) &&
1727         RAddCst->getValue().ugt(LHSCst->getValue())) {
1728 
1729       APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1730       if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1731         ConstantInt *MaxAddCst = nullptr;
1732         if (LAddCst->getValue().ult(RAddCst->getValue()))
1733           MaxAddCst = RAddCst;
1734         else
1735           MaxAddCst = LAddCst;
1736 
1737         APInt RRangeLow = -RAddCst->getValue();
1738         APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1739         APInt LRangeLow = -LAddCst->getValue();
1740         APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1741         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1742         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1743         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1744                                                    : RRangeLow - LRangeLow;
1745 
1746         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1747             RangeDiff.ugt(LHSCst->getValue())) {
1748           Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1749 
1750           Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1751           Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1752           return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1753         }
1754       }
1755     }
1756   }
1757 
1758   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1759   if (PredicatesFoldable(LHSCC, RHSCC)) {
1760     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1761         LHS->getOperand(1) == RHS->getOperand(0))
1762       LHS->swapOperands();
1763     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1764         LHS->getOperand(1) == RHS->getOperand(1)) {
1765       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1766       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1767       bool isSigned = LHS->isSigned() || RHS->isSigned();
1768       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1769     }
1770   }
1771 
1772   // handle (roughly):
1773   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1774   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1775     return V;
1776 
1777   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1778   if (LHS->hasOneUse() || RHS->hasOneUse()) {
1779     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1780     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1781     Value *A = nullptr, *B = nullptr;
1782     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1783       B = Val;
1784       if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1785         A = Val2;
1786       else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1787         A = RHS->getOperand(1);
1788     }
1789     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1790     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1791     else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1792       B = Val2;
1793       if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1794         A = Val;
1795       else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1796         A = LHS->getOperand(1);
1797     }
1798     if (A && B)
1799       return Builder->CreateICmp(
1800           ICmpInst::ICMP_UGE,
1801           Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1802   }
1803 
1804   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1805   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1806     return V;
1807 
1808   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1809   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1810     return V;
1811 
1812   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1813   if (!LHSCst || !RHSCst) return nullptr;
1814 
1815   if (LHSCst == RHSCst && LHSCC == RHSCC) {
1816     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1817     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1818       Value *NewOr = Builder->CreateOr(Val, Val2);
1819       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1820     }
1821   }
1822 
1823   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1824   //   iff C2 + CA == C1.
1825   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1826     ConstantInt *AddCst;
1827     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1828       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1829         return Builder->CreateICmpULE(Val, LHSCst);
1830   }
1831 
1832   // From here on, we only handle:
1833   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1834   if (Val != Val2) return nullptr;
1835 
1836   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1837   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1838       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1839       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1840       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1841     return nullptr;
1842 
1843   // We can't fold (ugt x, C) | (sgt x, C2).
1844   if (!PredicatesFoldable(LHSCC, RHSCC))
1845     return nullptr;
1846 
1847   // Ensure that the larger constant is on the RHS.
1848   bool ShouldSwap;
1849   if (CmpInst::isSigned(LHSCC) ||
1850       (ICmpInst::isEquality(LHSCC) &&
1851        CmpInst::isSigned(RHSCC)))
1852     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1853   else
1854     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1855 
1856   if (ShouldSwap) {
1857     std::swap(LHS, RHS);
1858     std::swap(LHSCst, RHSCst);
1859     std::swap(LHSCC, RHSCC);
1860   }
1861 
1862   // At this point, we know we have two icmp instructions
1863   // comparing a value against two constants and or'ing the result
1864   // together.  Because of the above check, we know that we only have
1865   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1866   // icmp folding check above), that the two constants are not
1867   // equal.
1868   assert(LHSCst != RHSCst && "Compares not folded above?");
1869 
1870   switch (LHSCC) {
1871   default: llvm_unreachable("Unknown integer condition code!");
1872   case ICmpInst::ICMP_EQ:
1873     switch (RHSCC) {
1874     default: llvm_unreachable("Unknown integer condition code!");
1875     case ICmpInst::ICMP_EQ:
1876       if (LHS->getOperand(0) == RHS->getOperand(0)) {
1877         // if LHSCst and RHSCst differ only by one bit:
1878         // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
1879         assert(LHSCst->getValue().ule(LHSCst->getValue()));
1880 
1881         APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1882         if (Xor.isPowerOf2()) {
1883           Value *Cst = Builder->getInt(Xor);
1884           Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
1885           return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
1886         }
1887       }
1888 
1889       if (LHSCst == SubOne(RHSCst)) {
1890         // (X == 13 | X == 14) -> X-13 <u 2
1891         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1892         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1893         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1894         return Builder->CreateICmpULT(Add, AddCST);
1895       }
1896 
1897       break;                         // (X == 13 | X == 15) -> no change
1898     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1899     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1900       break;
1901     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1902     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1903     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1904       return RHS;
1905     }
1906     break;
1907   case ICmpInst::ICMP_NE:
1908     switch (RHSCC) {
1909     default: llvm_unreachable("Unknown integer condition code!");
1910     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1911     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1912     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1913       return LHS;
1914     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1915     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1916     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1917       return Builder->getTrue();
1918     }
1919   case ICmpInst::ICMP_ULT:
1920     switch (RHSCC) {
1921     default: llvm_unreachable("Unknown integer condition code!");
1922     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1923       break;
1924     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1925       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1926       // this can cause overflow.
1927       if (RHSCst->isMaxValue(false))
1928         return LHS;
1929       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1930     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1931       break;
1932     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1933     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1934       return RHS;
1935     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1936       break;
1937     }
1938     break;
1939   case ICmpInst::ICMP_SLT:
1940     switch (RHSCC) {
1941     default: llvm_unreachable("Unknown integer condition code!");
1942     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1943       break;
1944     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1945       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1946       // this can cause overflow.
1947       if (RHSCst->isMaxValue(true))
1948         return LHS;
1949       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1950     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1951       break;
1952     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1953     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1954       return RHS;
1955     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1956       break;
1957     }
1958     break;
1959   case ICmpInst::ICMP_UGT:
1960     switch (RHSCC) {
1961     default: llvm_unreachable("Unknown integer condition code!");
1962     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1963     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1964       return LHS;
1965     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1966       break;
1967     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1968     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1969       return Builder->getTrue();
1970     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1971       break;
1972     }
1973     break;
1974   case ICmpInst::ICMP_SGT:
1975     switch (RHSCC) {
1976     default: llvm_unreachable("Unknown integer condition code!");
1977     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1978     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1979       return LHS;
1980     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1981       break;
1982     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1983     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1984       return Builder->getTrue();
1985     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1986       break;
1987     }
1988     break;
1989   }
1990   return nullptr;
1991 }
1992 
1993 /// Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of instcombine, this returns
1994 /// a Value which should already be inserted into the function.
1995 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1996   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1997       RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1998       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1999     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2000       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2001         // If either of the constants are nans, then the whole thing returns
2002         // true.
2003         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
2004           return Builder->getTrue();
2005 
2006         // Otherwise, no need to compare the two constants, compare the
2007         // rest.
2008         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2009       }
2010 
2011     // Handle vector zeros.  This occurs because the canonical form of
2012     // "fcmp uno x,x" is "fcmp uno x, 0".
2013     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2014         isa<ConstantAggregateZero>(RHS->getOperand(1)))
2015       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2016 
2017     return nullptr;
2018   }
2019 
2020   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2021   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2022   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2023 
2024   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2025     // Swap RHS operands to match LHS.
2026     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2027     std::swap(Op1LHS, Op1RHS);
2028   }
2029   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2030     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2031     if (Op0CC == Op1CC)
2032       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
2033     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
2034       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
2035     if (Op0CC == FCmpInst::FCMP_FALSE)
2036       return RHS;
2037     if (Op1CC == FCmpInst::FCMP_FALSE)
2038       return LHS;
2039     bool Op0Ordered;
2040     bool Op1Ordered;
2041     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2042     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2043     if (Op0Ordered == Op1Ordered) {
2044       // If both are ordered or unordered, return a new fcmp with
2045       // or'ed predicates.
2046       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
2047     }
2048   }
2049   return nullptr;
2050 }
2051 
2052 /// This helper function folds:
2053 ///
2054 ///     ((A | B) & C1) | (B & C2)
2055 ///
2056 /// into:
2057 ///
2058 ///     (A & C1) | B
2059 ///
2060 /// when the XOR of the two constants is "all ones" (-1).
2061 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2062                                                Value *A, Value *B, Value *C) {
2063   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2064   if (!CI1) return nullptr;
2065 
2066   Value *V1 = nullptr;
2067   ConstantInt *CI2 = nullptr;
2068   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
2069 
2070   APInt Xor = CI1->getValue() ^ CI2->getValue();
2071   if (!Xor.isAllOnesValue()) return nullptr;
2072 
2073   if (V1 == A || V1 == B) {
2074     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2075     return BinaryOperator::CreateOr(NewOp, V1);
2076   }
2077 
2078   return nullptr;
2079 }
2080 
2081 /// \brief This helper function folds:
2082 ///
2083 ///     ((A | B) & C1) ^ (B & C2)
2084 ///
2085 /// into:
2086 ///
2087 ///     (A & C1) ^ B
2088 ///
2089 /// when the XOR of the two constants is "all ones" (-1).
2090 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2091                                                 Value *A, Value *B, Value *C) {
2092   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2093   if (!CI1)
2094     return nullptr;
2095 
2096   Value *V1 = nullptr;
2097   ConstantInt *CI2 = nullptr;
2098   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2099     return nullptr;
2100 
2101   APInt Xor = CI1->getValue() ^ CI2->getValue();
2102   if (!Xor.isAllOnesValue())
2103     return nullptr;
2104 
2105   if (V1 == A || V1 == B) {
2106     Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2107     return BinaryOperator::CreateXor(NewOp, V1);
2108   }
2109 
2110   return nullptr;
2111 }
2112 
2113 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2114   bool Changed = SimplifyAssociativeOrCommutative(I);
2115   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2116 
2117   if (Value *V = SimplifyVectorOp(I))
2118     return replaceInstUsesWith(I, V);
2119 
2120   if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
2121     return replaceInstUsesWith(I, V);
2122 
2123   // (A&B)|(A&C) -> A&(B|C) etc
2124   if (Value *V = SimplifyUsingDistributiveLaws(I))
2125     return replaceInstUsesWith(I, V);
2126 
2127   // See if we can simplify any instructions used by the instruction whose sole
2128   // purpose is to compute bits we don't care about.
2129   if (SimplifyDemandedInstructionBits(I))
2130     return &I;
2131 
2132   if (Value *V = SimplifyBSwap(I))
2133     return replaceInstUsesWith(I, V);
2134 
2135   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2136     ConstantInt *C1 = nullptr; Value *X = nullptr;
2137     // (X & C1) | C2 --> (X | C2) & (C1|C2)
2138     // iff (C1 & C2) == 0.
2139     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
2140         (RHS->getValue() & C1->getValue()) != 0 &&
2141         Op0->hasOneUse()) {
2142       Value *Or = Builder->CreateOr(X, RHS);
2143       Or->takeName(Op0);
2144       return BinaryOperator::CreateAnd(Or,
2145                              Builder->getInt(RHS->getValue() | C1->getValue()));
2146     }
2147 
2148     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2149     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2150         Op0->hasOneUse()) {
2151       Value *Or = Builder->CreateOr(X, RHS);
2152       Or->takeName(Op0);
2153       return BinaryOperator::CreateXor(Or,
2154                             Builder->getInt(C1->getValue() & ~RHS->getValue()));
2155     }
2156 
2157     // Try to fold constant and into select arguments.
2158     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2159       if (Instruction *R = FoldOpIntoSelect(I, SI))
2160         return R;
2161 
2162     if (isa<PHINode>(Op0))
2163       if (Instruction *NV = FoldOpIntoPhi(I))
2164         return NV;
2165   }
2166 
2167   Value *A = nullptr, *B = nullptr;
2168   ConstantInt *C1 = nullptr, *C2 = nullptr;
2169 
2170   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
2171   bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
2172                  match(Op1, m_Or(m_Value(), m_Value()));
2173   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
2174   bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2175                     match(Op1, m_LogicalShift(m_Value(), m_Value()));
2176   // (A & B) | (C & D)                              -> bswap if possible.
2177   bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
2178                   match(Op1, m_And(m_Value(), m_Value()));
2179 
2180   if (OrOfOrs || OrOfShifts || OrOfAnds)
2181     if (Instruction *BSwap = MatchBSwapOrBitReverse(I))
2182       return BSwap;
2183 
2184   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2185   if (Op0->hasOneUse() &&
2186       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2187       MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
2188     Value *NOr = Builder->CreateOr(A, Op1);
2189     NOr->takeName(Op0);
2190     return BinaryOperator::CreateXor(NOr, C1);
2191   }
2192 
2193   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2194   if (Op1->hasOneUse() &&
2195       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2196       MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
2197     Value *NOr = Builder->CreateOr(A, Op0);
2198     NOr->takeName(Op0);
2199     return BinaryOperator::CreateXor(NOr, C1);
2200   }
2201 
2202   // ((~A & B) | A) -> (A | B)
2203   if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2204       match(Op1, m_Specific(A)))
2205     return BinaryOperator::CreateOr(A, B);
2206 
2207   // ((A & B) | ~A) -> (~A | B)
2208   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2209       match(Op1, m_Not(m_Specific(A))))
2210     return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2211 
2212   // (A & (~B)) | (A ^ B) -> (A ^ B)
2213   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2214       match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2215     return BinaryOperator::CreateXor(A, B);
2216 
2217   // (A ^ B) | ( A & (~B)) -> (A ^ B)
2218   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2219       match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2220     return BinaryOperator::CreateXor(A, B);
2221 
2222   // (A & C)|(B & D)
2223   Value *C = nullptr, *D = nullptr;
2224   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2225       match(Op1, m_And(m_Value(B), m_Value(D)))) {
2226     Value *V1 = nullptr, *V2 = nullptr;
2227     C1 = dyn_cast<ConstantInt>(C);
2228     C2 = dyn_cast<ConstantInt>(D);
2229     if (C1 && C2) {  // (A & C1)|(B & C2)
2230       if ((C1->getValue() & C2->getValue()) == 0) {
2231         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2232         // iff (C1&C2) == 0 and (N&~C1) == 0
2233         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2234             ((V1 == B &&
2235               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2236              (V2 == B &&
2237               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
2238           return BinaryOperator::CreateAnd(A,
2239                                 Builder->getInt(C1->getValue()|C2->getValue()));
2240         // Or commutes, try both ways.
2241         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2242             ((V1 == A &&
2243               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2244              (V2 == A &&
2245               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
2246           return BinaryOperator::CreateAnd(B,
2247                                 Builder->getInt(C1->getValue()|C2->getValue()));
2248 
2249         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2250         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2251         ConstantInt *C3 = nullptr, *C4 = nullptr;
2252         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2253             (C3->getValue() & ~C1->getValue()) == 0 &&
2254             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2255             (C4->getValue() & ~C2->getValue()) == 0) {
2256           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2257           return BinaryOperator::CreateAnd(V2,
2258                                 Builder->getInt(C1->getValue()|C2->getValue()));
2259         }
2260       }
2261     }
2262 
2263     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
2264     // Don't do this for vector select idioms, the code generator doesn't handle
2265     // them well yet.
2266     if (!I.getType()->isVectorTy()) {
2267       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2268         return Match;
2269       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2270         return Match;
2271       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2272         return Match;
2273       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2274         return Match;
2275     }
2276 
2277     // ((A&~B)|(~A&B)) -> A^B
2278     if ((match(C, m_Not(m_Specific(D))) &&
2279          match(B, m_Not(m_Specific(A)))))
2280       return BinaryOperator::CreateXor(A, D);
2281     // ((~B&A)|(~A&B)) -> A^B
2282     if ((match(A, m_Not(m_Specific(D))) &&
2283          match(B, m_Not(m_Specific(C)))))
2284       return BinaryOperator::CreateXor(C, D);
2285     // ((A&~B)|(B&~A)) -> A^B
2286     if ((match(C, m_Not(m_Specific(B))) &&
2287          match(D, m_Not(m_Specific(A)))))
2288       return BinaryOperator::CreateXor(A, B);
2289     // ((~B&A)|(B&~A)) -> A^B
2290     if ((match(A, m_Not(m_Specific(B))) &&
2291          match(D, m_Not(m_Specific(C)))))
2292       return BinaryOperator::CreateXor(C, B);
2293 
2294     // ((A|B)&1)|(B&-2) -> (A&1) | B
2295     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2296         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2297       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2298       if (Ret) return Ret;
2299     }
2300     // (B&-2)|((A|B)&1) -> (A&1) | B
2301     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2302         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2303       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2304       if (Ret) return Ret;
2305     }
2306     // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2307     if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2308         match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2309       Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2310       if (Ret) return Ret;
2311     }
2312     // (B&-2)|((A^B)&1) -> (A&1) ^ B
2313     if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2314         match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2315       Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2316       if (Ret) return Ret;
2317     }
2318   }
2319 
2320   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2321   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2322     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2323       if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2324         return BinaryOperator::CreateOr(Op0, C);
2325 
2326   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2327   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2328     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2329       if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2330         return BinaryOperator::CreateOr(Op1, C);
2331 
2332   // ((B | C) & A) | B -> B | (A & C)
2333   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2334     return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2335 
2336   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2337     return DeMorgan;
2338 
2339   // Canonicalize xor to the RHS.
2340   bool SwappedForXor = false;
2341   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2342     std::swap(Op0, Op1);
2343     SwappedForXor = true;
2344   }
2345 
2346   // A | ( A ^ B) -> A |  B
2347   // A | (~A ^ B) -> A | ~B
2348   // (A & B) | (A ^ B)
2349   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2350     if (Op0 == A || Op0 == B)
2351       return BinaryOperator::CreateOr(A, B);
2352 
2353     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2354         match(Op0, m_And(m_Specific(B), m_Specific(A))))
2355       return BinaryOperator::CreateOr(A, B);
2356 
2357     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2358       Value *Not = Builder->CreateNot(B, B->getName()+".not");
2359       return BinaryOperator::CreateOr(Not, Op0);
2360     }
2361     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2362       Value *Not = Builder->CreateNot(A, A->getName()+".not");
2363       return BinaryOperator::CreateOr(Not, Op0);
2364     }
2365   }
2366 
2367   // A | ~(A | B) -> A | ~B
2368   // A | ~(A ^ B) -> A | ~B
2369   if (match(Op1, m_Not(m_Value(A))))
2370     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2371       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2372           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2373                                B->getOpcode() == Instruction::Xor)) {
2374         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2375                                                  B->getOperand(0);
2376         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2377         return BinaryOperator::CreateOr(Not, Op0);
2378       }
2379 
2380   // (A & B) | ((~A) ^ B) -> (~A ^ B)
2381   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2382       match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2383     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2384 
2385   // ((~A) ^ B) | (A & B) -> (~A ^ B)
2386   if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2387       match(Op1, m_And(m_Specific(A), m_Specific(B))))
2388     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2389 
2390   if (SwappedForXor)
2391     std::swap(Op0, Op1);
2392 
2393   {
2394     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2395     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2396     if (LHS && RHS)
2397       if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2398         return replaceInstUsesWith(I, Res);
2399 
2400     // TODO: Make this recursive; it's a little tricky because an arbitrary
2401     // number of 'or' instructions might have to be created.
2402     Value *X, *Y;
2403     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2404       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2405         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2406           return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2407       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2408         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2409           return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2410     }
2411     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2412       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2413         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2414           return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2415       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2416         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2417           return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2418     }
2419   }
2420 
2421   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
2422   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2423     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2424       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2425         return replaceInstUsesWith(I, Res);
2426 
2427   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2428     return CastedOr;
2429 
2430   // or(sext(A), B) -> A ? -1 : B where A is an i1
2431   // or(A, sext(B)) -> B ? -1 : A where B is an i1
2432   if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2433     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2434   if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2435     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2436 
2437   // Note: If we've gotten to the point of visiting the outer OR, then the
2438   // inner one couldn't be simplified.  If it was a constant, then it won't
2439   // be simplified by a later pass either, so we try swapping the inner/outer
2440   // ORs in the hopes that we'll be able to simplify it this way.
2441   // (X|C) | V --> (X|V) | C
2442   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2443       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2444     Value *Inner = Builder->CreateOr(A, Op1);
2445     Inner->takeName(Op0);
2446     return BinaryOperator::CreateOr(Inner, C1);
2447   }
2448 
2449   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2450   // Since this OR statement hasn't been optimized further yet, we hope
2451   // that this transformation will allow the new ORs to be optimized.
2452   {
2453     Value *X = nullptr, *Y = nullptr;
2454     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2455         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2456         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2457       Value *orTrue = Builder->CreateOr(A, C);
2458       Value *orFalse = Builder->CreateOr(B, D);
2459       return SelectInst::Create(X, orTrue, orFalse);
2460     }
2461   }
2462 
2463   return Changed ? &I : nullptr;
2464 }
2465 
2466 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2467   bool Changed = SimplifyAssociativeOrCommutative(I);
2468   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2469 
2470   if (Value *V = SimplifyVectorOp(I))
2471     return replaceInstUsesWith(I, V);
2472 
2473   if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
2474     return replaceInstUsesWith(I, V);
2475 
2476   // (A&B)^(A&C) -> A&(B^C) etc
2477   if (Value *V = SimplifyUsingDistributiveLaws(I))
2478     return replaceInstUsesWith(I, V);
2479 
2480   // See if we can simplify any instructions used by the instruction whose sole
2481   // purpose is to compute bits we don't care about.
2482   if (SimplifyDemandedInstructionBits(I))
2483     return &I;
2484 
2485   if (Value *V = SimplifyBSwap(I))
2486     return replaceInstUsesWith(I, V);
2487 
2488   // Is this a ~ operation?
2489   if (Value *NotOp = dyn_castNotVal(&I)) {
2490     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2491       if (Op0I->getOpcode() == Instruction::And ||
2492           Op0I->getOpcode() == Instruction::Or) {
2493         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2494         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2495         if (dyn_castNotVal(Op0I->getOperand(1)))
2496           Op0I->swapOperands();
2497         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2498           Value *NotY =
2499             Builder->CreateNot(Op0I->getOperand(1),
2500                                Op0I->getOperand(1)->getName()+".not");
2501           if (Op0I->getOpcode() == Instruction::And)
2502             return BinaryOperator::CreateOr(Op0NotVal, NotY);
2503           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2504         }
2505 
2506         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2507         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2508         if (IsFreeToInvert(Op0I->getOperand(0),
2509                            Op0I->getOperand(0)->hasOneUse()) &&
2510             IsFreeToInvert(Op0I->getOperand(1),
2511                            Op0I->getOperand(1)->hasOneUse())) {
2512           Value *NotX =
2513             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2514           Value *NotY =
2515             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2516           if (Op0I->getOpcode() == Instruction::And)
2517             return BinaryOperator::CreateOr(NotX, NotY);
2518           return BinaryOperator::CreateAnd(NotX, NotY);
2519         }
2520 
2521       } else if (Op0I->getOpcode() == Instruction::AShr) {
2522         // ~(~X >>s Y) --> (X >>s Y)
2523         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2524           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2525       }
2526     }
2527   }
2528 
2529   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2530     if (RHS->isAllOnesValue() && Op0->hasOneUse())
2531       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2532       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2533         return CmpInst::Create(CI->getOpcode(),
2534                                CI->getInversePredicate(),
2535                                CI->getOperand(0), CI->getOperand(1));
2536   }
2537 
2538   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2539     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2540     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2541       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2542         if (CI->hasOneUse() && Op0C->hasOneUse()) {
2543           Instruction::CastOps Opcode = Op0C->getOpcode();
2544           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2545               (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2546                                             Op0C->getDestTy()))) {
2547             CI->setPredicate(CI->getInversePredicate());
2548             return CastInst::Create(Opcode, CI, Op0C->getType());
2549           }
2550         }
2551       }
2552     }
2553 
2554     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2555       // ~(c-X) == X-c-1 == X+(-c-1)
2556       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2557         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2558           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2559           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2560                                       ConstantInt::get(I.getType(), 1));
2561           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2562         }
2563 
2564       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2565         if (Op0I->getOpcode() == Instruction::Add) {
2566           // ~(X-c) --> (-c-1)-X
2567           if (RHS->isAllOnesValue()) {
2568             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2569             return BinaryOperator::CreateSub(
2570                            ConstantExpr::getSub(NegOp0CI,
2571                                       ConstantInt::get(I.getType(), 1)),
2572                                       Op0I->getOperand(0));
2573           } else if (RHS->getValue().isSignBit()) {
2574             // (X + C) ^ signbit -> (X + C + signbit)
2575             Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2576             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2577 
2578           }
2579         } else if (Op0I->getOpcode() == Instruction::Or) {
2580           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2581           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2582                                 0, &I)) {
2583             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2584             // Anything in both C1 and C2 is known to be zero, remove it from
2585             // NewRHS.
2586             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2587             NewRHS = ConstantExpr::getAnd(NewRHS,
2588                                        ConstantExpr::getNot(CommonBits));
2589             Worklist.Add(Op0I);
2590             I.setOperand(0, Op0I->getOperand(0));
2591             I.setOperand(1, NewRHS);
2592             return &I;
2593           }
2594         } else if (Op0I->getOpcode() == Instruction::LShr) {
2595           // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2596           // E1 = "X ^ C1"
2597           BinaryOperator *E1;
2598           ConstantInt *C1;
2599           if (Op0I->hasOneUse() &&
2600               (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2601               E1->getOpcode() == Instruction::Xor &&
2602               (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2603             // fold (C1 >> C2) ^ C3
2604             ConstantInt *C2 = Op0CI, *C3 = RHS;
2605             APInt FoldConst = C1->getValue().lshr(C2->getValue());
2606             FoldConst ^= C3->getValue();
2607             // Prepare the two operands.
2608             Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2609             Opnd0->takeName(Op0I);
2610             cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2611             Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2612 
2613             return BinaryOperator::CreateXor(Opnd0, FoldVal);
2614           }
2615         }
2616       }
2617     }
2618 
2619     // Try to fold constant and into select arguments.
2620     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2621       if (Instruction *R = FoldOpIntoSelect(I, SI))
2622         return R;
2623     if (isa<PHINode>(Op0))
2624       if (Instruction *NV = FoldOpIntoPhi(I))
2625         return NV;
2626   }
2627 
2628   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2629   if (Op1I) {
2630     Value *A, *B;
2631     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2632       if (A == Op0) {              // B^(B|A) == (A|B)^B
2633         Op1I->swapOperands();
2634         I.swapOperands();
2635         std::swap(Op0, Op1);
2636       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2637         I.swapOperands();     // Simplified below.
2638         std::swap(Op0, Op1);
2639       }
2640     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2641                Op1I->hasOneUse()){
2642       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2643         Op1I->swapOperands();
2644         std::swap(A, B);
2645       }
2646       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2647         I.swapOperands();     // Simplified below.
2648         std::swap(Op0, Op1);
2649       }
2650     }
2651   }
2652 
2653   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2654   if (Op0I) {
2655     Value *A, *B;
2656     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2657         Op0I->hasOneUse()) {
2658       if (A == Op1)                                  // (B|A)^B == (A|B)^B
2659         std::swap(A, B);
2660       if (B == Op1)                                  // (A|B)^B == A & ~B
2661         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2662     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2663                Op0I->hasOneUse()){
2664       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2665         std::swap(A, B);
2666       if (B == Op1 &&                                      // (B&A)^A == ~B & A
2667           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2668         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2669       }
2670     }
2671   }
2672 
2673   if (Op0I && Op1I) {
2674     Value *A, *B, *C, *D;
2675     // (A & B)^(A | B) -> A ^ B
2676     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2677         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2678       if ((A == C && B == D) || (A == D && B == C))
2679         return BinaryOperator::CreateXor(A, B);
2680     }
2681     // (A | B)^(A & B) -> A ^ B
2682     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2683         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2684       if ((A == C && B == D) || (A == D && B == C))
2685         return BinaryOperator::CreateXor(A, B);
2686     }
2687     // (A | ~B) ^ (~A | B) -> A ^ B
2688     if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2689         match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2690       return BinaryOperator::CreateXor(A, B);
2691     }
2692     // (~A | B) ^ (A | ~B) -> A ^ B
2693     if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2694         match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2695       return BinaryOperator::CreateXor(A, B);
2696     }
2697     // (A & ~B) ^ (~A & B) -> A ^ B
2698     if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2699         match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2700       return BinaryOperator::CreateXor(A, B);
2701     }
2702     // (~A & B) ^ (A & ~B) -> A ^ B
2703     if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2704         match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2705       return BinaryOperator::CreateXor(A, B);
2706     }
2707     // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2708     if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2709         match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2710       if (D == A)
2711         return BinaryOperator::CreateXor(
2712             Builder->CreateAnd(Builder->CreateNot(A), B), C);
2713       if (D == B)
2714         return BinaryOperator::CreateXor(
2715             Builder->CreateAnd(Builder->CreateNot(B), A), C);
2716     }
2717     // (A | B)^(A ^ C) -> ((~A) & B) ^ C
2718     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2719         match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2720       if (D == A)
2721         return BinaryOperator::CreateXor(
2722             Builder->CreateAnd(Builder->CreateNot(A), B), C);
2723       if (D == B)
2724         return BinaryOperator::CreateXor(
2725             Builder->CreateAnd(Builder->CreateNot(B), A), C);
2726     }
2727     // (A & B) ^ (A ^ B) -> (A | B)
2728     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2729         match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2730       return BinaryOperator::CreateOr(A, B);
2731     // (A ^ B) ^ (A & B) -> (A | B)
2732     if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2733         match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2734       return BinaryOperator::CreateOr(A, B);
2735   }
2736 
2737   Value *A = nullptr, *B = nullptr;
2738   // (A & ~B) ^ (~A) -> ~(A & B)
2739   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2740       match(Op1, m_Not(m_Specific(A))))
2741     return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2742 
2743   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2744   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2745     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2746       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2747         if (LHS->getOperand(0) == RHS->getOperand(1) &&
2748             LHS->getOperand(1) == RHS->getOperand(0))
2749           LHS->swapOperands();
2750         if (LHS->getOperand(0) == RHS->getOperand(0) &&
2751             LHS->getOperand(1) == RHS->getOperand(1)) {
2752           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2753           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2754           bool isSigned = LHS->isSigned() || RHS->isSigned();
2755           return replaceInstUsesWith(I,
2756                                getNewICmpValue(isSigned, Code, Op0, Op1,
2757                                                Builder));
2758         }
2759       }
2760 
2761   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2762     return CastedXor;
2763 
2764   return Changed ? &I : nullptr;
2765 }
2766