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