OSDN Git Service

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