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