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