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