Simplify code. No functionality changes, name changes aside.
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineCompares.cpp
1 //===- InstCombineCompares.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 visitICmp and visitFCmp functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/IntrinsicInst.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Support/ConstantRange.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/Support/PatternMatch.h"
22 using namespace llvm;
23 using namespace PatternMatch;
24
25 static ConstantInt *getOne(Constant *C) {
26   return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
27 }
28
29 /// AddOne - Add one to a ConstantInt
30 static Constant *AddOne(Constant *C) {
31   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
32 }
33 /// SubOne - Subtract one from a ConstantInt
34 static Constant *SubOne(Constant *C) {
35   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
36 }
37
38 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
39   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
40 }
41
42 static bool HasAddOverflow(ConstantInt *Result,
43                            ConstantInt *In1, ConstantInt *In2,
44                            bool IsSigned) {
45   if (IsSigned)
46     if (In2->getValue().isNegative())
47       return Result->getValue().sgt(In1->getValue());
48     else
49       return Result->getValue().slt(In1->getValue());
50   else
51     return Result->getValue().ult(In1->getValue());
52 }
53
54 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
55 /// overflowed for this type.
56 static bool AddWithOverflow(Constant *&Result, Constant *In1,
57                             Constant *In2, bool IsSigned = false) {
58   Result = ConstantExpr::getAdd(In1, In2);
59
60   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
61     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
63       if (HasAddOverflow(ExtractElement(Result, Idx),
64                          ExtractElement(In1, Idx),
65                          ExtractElement(In2, Idx),
66                          IsSigned))
67         return true;
68     }
69     return false;
70   }
71
72   return HasAddOverflow(cast<ConstantInt>(Result),
73                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74                         IsSigned);
75 }
76
77 static bool HasSubOverflow(ConstantInt *Result,
78                            ConstantInt *In1, ConstantInt *In2,
79                            bool IsSigned) {
80   if (IsSigned)
81     if (In2->getValue().isNegative())
82       return Result->getValue().slt(In1->getValue());
83     else
84       return Result->getValue().sgt(In1->getValue());
85   else
86     return Result->getValue().ugt(In1->getValue());
87 }
88
89 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
90 /// overflowed for this type.
91 static bool SubWithOverflow(Constant *&Result, Constant *In1,
92                             Constant *In2, bool IsSigned = false) {
93   Result = ConstantExpr::getSub(In1, In2);
94
95   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
96     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
98       if (HasSubOverflow(ExtractElement(Result, Idx),
99                          ExtractElement(In1, Idx),
100                          ExtractElement(In2, Idx),
101                          IsSigned))
102         return true;
103     }
104     return false;
105   }
106
107   return HasSubOverflow(cast<ConstantInt>(Result),
108                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109                         IsSigned);
110 }
111
112 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
113 /// comparison only checks the sign bit.  If it only checks the sign bit, set
114 /// TrueIfSigned if the result of the comparison is true when the input value is
115 /// signed.
116 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
117                            bool &TrueIfSigned) {
118   switch (pred) {
119   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
120     TrueIfSigned = true;
121     return RHS->isZero();
122   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
123     TrueIfSigned = true;
124     return RHS->isAllOnesValue();
125   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
126     TrueIfSigned = false;
127     return RHS->isAllOnesValue();
128   case ICmpInst::ICMP_UGT:
129     // True if LHS u> RHS and RHS == high-bit-mask - 1
130     TrueIfSigned = true;
131     return RHS->getValue() ==
132       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
133   case ICmpInst::ICMP_UGE: 
134     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135     TrueIfSigned = true;
136     return RHS->getValue().isSignBit();
137   default:
138     return false;
139   }
140 }
141
142 // isHighOnes - Return true if the constant is of the form 1+0+.
143 // This is the same as lowones(~X).
144 static bool isHighOnes(const ConstantInt *CI) {
145   return (~CI->getValue() + 1).isPowerOf2();
146 }
147
148 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
149 /// set of known zero and one bits, compute the maximum and minimum values that
150 /// could have the specified known zero and known one bits, returning them in
151 /// min/max.
152 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
153                                                    const APInt& KnownOne,
154                                                    APInt& Min, APInt& Max) {
155   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
156          KnownZero.getBitWidth() == Min.getBitWidth() &&
157          KnownZero.getBitWidth() == Max.getBitWidth() &&
158          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
159   APInt UnknownBits = ~(KnownZero|KnownOne);
160
161   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
162   // bit if it is unknown.
163   Min = KnownOne;
164   Max = KnownOne|UnknownBits;
165   
166   if (UnknownBits.isNegative()) { // Sign bit is unknown
167     Min.setBit(Min.getBitWidth()-1);
168     Max.clearBit(Max.getBitWidth()-1);
169   }
170 }
171
172 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
173 // a set of known zero and one bits, compute the maximum and minimum values that
174 // could have the specified known zero and known one bits, returning them in
175 // min/max.
176 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
177                                                      const APInt &KnownOne,
178                                                      APInt &Min, APInt &Max) {
179   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
180          KnownZero.getBitWidth() == Min.getBitWidth() &&
181          KnownZero.getBitWidth() == Max.getBitWidth() &&
182          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
183   APInt UnknownBits = ~(KnownZero|KnownOne);
184   
185   // The minimum value is when the unknown bits are all zeros.
186   Min = KnownOne;
187   // The maximum value is when the unknown bits are all ones.
188   Max = KnownOne|UnknownBits;
189 }
190
191
192
193 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
194 ///   cmp pred (load (gep GV, ...)), cmpcst
195 /// where GV is a global variable with a constant initializer.  Try to simplify
196 /// this into some simple computation that does not need the load.  For example
197 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
198 ///
199 /// If AndCst is non-null, then the loaded value is masked with that constant
200 /// before doing the comparison.  This handles cases like "A[i]&4 == 0".
201 Instruction *InstCombiner::
202 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
203                              CmpInst &ICI, ConstantInt *AndCst) {
204   // We need TD information to know the pointer size unless this is inbounds.
205   if (!GEP->isInBounds() && TD == 0) return 0;
206   
207   ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
208   if (Init == 0 || Init->getNumOperands() > 1024) return 0;
209   
210   // There are many forms of this optimization we can handle, for now, just do
211   // the simple index into a single-dimensional array.
212   //
213   // Require: GEP GV, 0, i {{, constant indices}}
214   if (GEP->getNumOperands() < 3 ||
215       !isa<ConstantInt>(GEP->getOperand(1)) ||
216       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
217       isa<Constant>(GEP->getOperand(2)))
218     return 0;
219
220   // Check that indices after the variable are constants and in-range for the
221   // type they index.  Collect the indices.  This is typically for arrays of
222   // structs.
223   SmallVector<unsigned, 4> LaterIndices;
224   
225   const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
226   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
227     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
228     if (Idx == 0) return 0;  // Variable index.
229     
230     uint64_t IdxVal = Idx->getZExtValue();
231     if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
232     
233     if (const StructType *STy = dyn_cast<StructType>(EltTy))
234       EltTy = STy->getElementType(IdxVal);
235     else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
236       if (IdxVal >= ATy->getNumElements()) return 0;
237       EltTy = ATy->getElementType();
238     } else {
239       return 0; // Unknown type.
240     }
241     
242     LaterIndices.push_back(IdxVal);
243   }
244   
245   enum { Overdefined = -3, Undefined = -2 };
246
247   // Variables for our state machines.
248   
249   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
250   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
251   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
252   // undefined, otherwise set to the first true element.  SecondTrueElement is
253   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
254   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
255
256   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
257   // form "i != 47 & i != 87".  Same state transitions as for true elements.
258   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
259   
260   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
261   /// define a state machine that triggers for ranges of values that the index
262   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
263   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
264   /// index in the range (inclusive).  We use -2 for undefined here because we
265   /// use relative comparisons and don't want 0-1 to match -1.
266   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
267   
268   // MagicBitvector - This is a magic bitvector where we set a bit if the
269   // comparison is true for element 'i'.  If there are 64 elements or less in
270   // the array, this will fully represent all the comparison results.
271   uint64_t MagicBitvector = 0;
272   
273   
274   // Scan the array and see if one of our patterns matches.
275   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
276   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
277     Constant *Elt = Init->getOperand(i);
278     
279     // If this is indexing an array of structures, get the structure element.
280     if (!LaterIndices.empty())
281       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
282                                           LaterIndices.size());
283     
284     // If the element is masked, handle it.
285     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
286     
287     // Find out if the comparison would be true or false for the i'th element.
288     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
289                                                   CompareRHS, TD);
290     // If the result is undef for this element, ignore it.
291     if (isa<UndefValue>(C)) {
292       // Extend range state machines to cover this element in case there is an
293       // undef in the middle of the range.
294       if (TrueRangeEnd == (int)i-1)
295         TrueRangeEnd = i;
296       if (FalseRangeEnd == (int)i-1)
297         FalseRangeEnd = i;
298       continue;
299     }
300     
301     // If we can't compute the result for any of the elements, we have to give
302     // up evaluating the entire conditional.
303     if (!isa<ConstantInt>(C)) return 0;
304     
305     // Otherwise, we know if the comparison is true or false for this element,
306     // update our state machines.
307     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
308     
309     // State machine for single/double/range index comparison.
310     if (IsTrueForElt) {
311       // Update the TrueElement state machine.
312       if (FirstTrueElement == Undefined)
313         FirstTrueElement = TrueRangeEnd = i;  // First true element.
314       else {
315         // Update double-compare state machine.
316         if (SecondTrueElement == Undefined)
317           SecondTrueElement = i;
318         else
319           SecondTrueElement = Overdefined;
320         
321         // Update range state machine.
322         if (TrueRangeEnd == (int)i-1)
323           TrueRangeEnd = i;
324         else
325           TrueRangeEnd = Overdefined;
326       }
327     } else {
328       // Update the FalseElement state machine.
329       if (FirstFalseElement == Undefined)
330         FirstFalseElement = FalseRangeEnd = i; // First false element.
331       else {
332         // Update double-compare state machine.
333         if (SecondFalseElement == Undefined)
334           SecondFalseElement = i;
335         else
336           SecondFalseElement = Overdefined;
337         
338         // Update range state machine.
339         if (FalseRangeEnd == (int)i-1)
340           FalseRangeEnd = i;
341         else
342           FalseRangeEnd = Overdefined;
343       }
344     }
345     
346     
347     // If this element is in range, update our magic bitvector.
348     if (i < 64 && IsTrueForElt)
349       MagicBitvector |= 1ULL << i;
350     
351     // If all of our states become overdefined, bail out early.  Since the
352     // predicate is expensive, only check it every 8 elements.  This is only
353     // really useful for really huge arrays.
354     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
355         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
356         FalseRangeEnd == Overdefined)
357       return 0;
358   }
359
360   // Now that we've scanned the entire array, emit our new comparison(s).  We
361   // order the state machines in complexity of the generated code.
362   Value *Idx = GEP->getOperand(2);
363
364   // If the index is larger than the pointer size of the target, truncate the
365   // index down like the GEP would do implicitly.  We don't have to do this for
366   // an inbounds GEP because the index can't be out of range.
367   if (!GEP->isInBounds() &&
368       Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
369     Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
370   
371   // If the comparison is only true for one or two elements, emit direct
372   // comparisons.
373   if (SecondTrueElement != Overdefined) {
374     // None true -> false.
375     if (FirstTrueElement == Undefined)
376       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
377     
378     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
379     
380     // True for one element -> 'i == 47'.
381     if (SecondTrueElement == Undefined)
382       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
383     
384     // True for two elements -> 'i == 47 | i == 72'.
385     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
386     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
387     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
388     return BinaryOperator::CreateOr(C1, C2);
389   }
390
391   // If the comparison is only false for one or two elements, emit direct
392   // comparisons.
393   if (SecondFalseElement != Overdefined) {
394     // None false -> true.
395     if (FirstFalseElement == Undefined)
396       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
397     
398     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
399
400     // False for one element -> 'i != 47'.
401     if (SecondFalseElement == Undefined)
402       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
403      
404     // False for two elements -> 'i != 47 & i != 72'.
405     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
406     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
407     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
408     return BinaryOperator::CreateAnd(C1, C2);
409   }
410   
411   // If the comparison can be replaced with a range comparison for the elements
412   // where it is true, emit the range check.
413   if (TrueRangeEnd != Overdefined) {
414     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
415     
416     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
417     if (FirstTrueElement) {
418       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
419       Idx = Builder->CreateAdd(Idx, Offs);
420     }
421     
422     Value *End = ConstantInt::get(Idx->getType(),
423                                   TrueRangeEnd-FirstTrueElement+1);
424     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
425   }
426   
427   // False range check.
428   if (FalseRangeEnd != Overdefined) {
429     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
430     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
431     if (FirstFalseElement) {
432       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
433       Idx = Builder->CreateAdd(Idx, Offs);
434     }
435     
436     Value *End = ConstantInt::get(Idx->getType(),
437                                   FalseRangeEnd-FirstFalseElement);
438     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
439   }
440   
441   
442   // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
443   // of this load, replace it with computation that does:
444   //   ((magic_cst >> i) & 1) != 0
445   if (Init->getNumOperands() <= 32 ||
446       (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
447     const Type *Ty;
448     if (Init->getNumOperands() <= 32)
449       Ty = Type::getInt32Ty(Init->getContext());
450     else
451       Ty = Type::getInt64Ty(Init->getContext());
452     Value *V = Builder->CreateIntCast(Idx, Ty, false);
453     V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
454     V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
455     return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
456   }
457   
458   return 0;
459 }
460
461
462 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
463 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
464 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
465 /// be complex, and scales are involved.  The above expression would also be
466 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
467 /// This later form is less amenable to optimization though, and we are allowed
468 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
469 ///
470 /// If we can't emit an optimized form for this expression, this returns null.
471 /// 
472 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
473   TargetData &TD = *IC.getTargetData();
474   gep_type_iterator GTI = gep_type_begin(GEP);
475   
476   // Check to see if this gep only has a single variable index.  If so, and if
477   // any constant indices are a multiple of its scale, then we can compute this
478   // in terms of the scale of the variable index.  For example, if the GEP
479   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
480   // because the expression will cross zero at the same point.
481   unsigned i, e = GEP->getNumOperands();
482   int64_t Offset = 0;
483   for (i = 1; i != e; ++i, ++GTI) {
484     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
485       // Compute the aggregate offset of constant indices.
486       if (CI->isZero()) continue;
487       
488       // Handle a struct index, which adds its field offset to the pointer.
489       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
490         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
491       } else {
492         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
493         Offset += Size*CI->getSExtValue();
494       }
495     } else {
496       // Found our variable index.
497       break;
498     }
499   }
500   
501   // If there are no variable indices, we must have a constant offset, just
502   // evaluate it the general way.
503   if (i == e) return 0;
504   
505   Value *VariableIdx = GEP->getOperand(i);
506   // Determine the scale factor of the variable element.  For example, this is
507   // 4 if the variable index is into an array of i32.
508   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
509   
510   // Verify that there are no other variable indices.  If so, emit the hard way.
511   for (++i, ++GTI; i != e; ++i, ++GTI) {
512     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
513     if (!CI) return 0;
514     
515     // Compute the aggregate offset of constant indices.
516     if (CI->isZero()) continue;
517     
518     // Handle a struct index, which adds its field offset to the pointer.
519     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
520       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
521     } else {
522       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
523       Offset += Size*CI->getSExtValue();
524     }
525   }
526   
527   // Okay, we know we have a single variable index, which must be a
528   // pointer/array/vector index.  If there is no offset, life is simple, return
529   // the index.
530   unsigned IntPtrWidth = TD.getPointerSizeInBits();
531   if (Offset == 0) {
532     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
533     // we don't need to bother extending: the extension won't affect where the
534     // computation crosses zero.
535     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
536       const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
537       VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
538     }
539     return VariableIdx;
540   }
541   
542   // Otherwise, there is an index.  The computation we will do will be modulo
543   // the pointer size, so get it.
544   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
545   
546   Offset &= PtrSizeMask;
547   VariableScale &= PtrSizeMask;
548   
549   // To do this transformation, any constant index must be a multiple of the
550   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
551   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
552   // multiple of the variable scale.
553   int64_t NewOffs = Offset / (int64_t)VariableScale;
554   if (Offset != NewOffs*(int64_t)VariableScale)
555     return 0;
556   
557   // Okay, we can do this evaluation.  Start by converting the index to intptr.
558   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
559   if (VariableIdx->getType() != IntPtrTy)
560     VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
561                                             true /*Signed*/);
562   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
563   return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
564 }
565
566 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
567 /// else.  At this point we know that the GEP is on the LHS of the comparison.
568 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
569                                        ICmpInst::Predicate Cond,
570                                        Instruction &I) {
571   // Look through bitcasts.
572   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
573     RHS = BCI->getOperand(0);
574
575   Value *PtrBase = GEPLHS->getOperand(0);
576   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
577     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
578     // This transformation (ignoring the base and scales) is valid because we
579     // know pointers can't overflow since the gep is inbounds.  See if we can
580     // output an optimized form.
581     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
582     
583     // If not, synthesize the offset the hard way.
584     if (Offset == 0)
585       Offset = EmitGEPOffset(GEPLHS);
586     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
587                         Constant::getNullValue(Offset->getType()));
588   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
589     // If the base pointers are different, but the indices are the same, just
590     // compare the base pointer.
591     if (PtrBase != GEPRHS->getOperand(0)) {
592       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
593       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
594                         GEPRHS->getOperand(0)->getType();
595       if (IndicesTheSame)
596         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
597           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
598             IndicesTheSame = false;
599             break;
600           }
601
602       // If all indices are the same, just compare the base pointers.
603       if (IndicesTheSame)
604         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
605                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
606
607       // Otherwise, the base pointers are different and the indices are
608       // different, bail out.
609       return 0;
610     }
611
612     // If one of the GEPs has all zero indices, recurse.
613     bool AllZeros = true;
614     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
615       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
616           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
617         AllZeros = false;
618         break;
619       }
620     if (AllZeros)
621       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
622                           ICmpInst::getSwappedPredicate(Cond), I);
623
624     // If the other GEP has all zero indices, recurse.
625     AllZeros = true;
626     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
627       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
628           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
629         AllZeros = false;
630         break;
631       }
632     if (AllZeros)
633       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
634
635     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
636     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
637       // If the GEPs only differ by one index, compare it.
638       unsigned NumDifferences = 0;  // Keep track of # differences.
639       unsigned DiffOperand = 0;     // The operand that differs.
640       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
641         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
642           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
643                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
644             // Irreconcilable differences.
645             NumDifferences = 2;
646             break;
647           } else {
648             if (NumDifferences++) break;
649             DiffOperand = i;
650           }
651         }
652
653       if (NumDifferences == 0)   // SAME GEP?
654         return ReplaceInstUsesWith(I, // No comparison is needed here.
655                                ConstantInt::get(Type::getInt1Ty(I.getContext()),
656                                              ICmpInst::isTrueWhenEqual(Cond)));
657
658       else if (NumDifferences == 1 && GEPsInBounds) {
659         Value *LHSV = GEPLHS->getOperand(DiffOperand);
660         Value *RHSV = GEPRHS->getOperand(DiffOperand);
661         // Make sure we do a signed comparison here.
662         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
663       }
664     }
665
666     // Only lower this if the icmp is the only user of the GEP or if we expect
667     // the result to fold to a constant!
668     if (TD &&
669         GEPsInBounds &&
670         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
671         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
672       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
673       Value *L = EmitGEPOffset(GEPLHS);
674       Value *R = EmitGEPOffset(GEPRHS);
675       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
676     }
677   }
678   return 0;
679 }
680
681 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
682 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
683                                             Value *X, ConstantInt *CI,
684                                             ICmpInst::Predicate Pred,
685                                             Value *TheAdd) {
686   // If we have X+0, exit early (simplifying logic below) and let it get folded
687   // elsewhere.   icmp X+0, X  -> icmp X, X
688   if (CI->isZero()) {
689     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
690     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
691   }
692   
693   // (X+4) == X -> false.
694   if (Pred == ICmpInst::ICMP_EQ)
695     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
696
697   // (X+4) != X -> true.
698   if (Pred == ICmpInst::ICMP_NE)
699     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
700
701   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
702   // so the values can never be equal.  Similarly for all other "or equals"
703   // operators.
704   
705   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
706   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
707   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
708   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
709     Value *R = 
710       ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
711     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
712   }
713   
714   // (X+1) >u X        --> X <u (0-1)        --> X != 255
715   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
716   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
717   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
718     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
719   
720   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
721   ConstantInt *SMax = ConstantInt::get(X->getContext(),
722                                        APInt::getSignedMaxValue(BitWidth));
723
724   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
725   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
726   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
727   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
728   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
729   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
730   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
731     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
732   
733   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
734   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
735   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
736   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
737   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
738   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
739   
740   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
741   Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
742   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
743 }
744
745 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
746 /// and CmpRHS are both known to be integer constants.
747 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
748                                           ConstantInt *DivRHS) {
749   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
750   const APInt &CmpRHSV = CmpRHS->getValue();
751   
752   // FIXME: If the operand types don't match the type of the divide 
753   // then don't attempt this transform. The code below doesn't have the
754   // logic to deal with a signed divide and an unsigned compare (and
755   // vice versa). This is because (x /s C1) <s C2  produces different 
756   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
757   // (x /u C1) <u C2.  Simply casting the operands and result won't 
758   // work. :(  The if statement below tests that condition and bails 
759   // if it finds it.
760   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
761   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
762     return 0;
763   if (DivRHS->isZero())
764     return 0; // The ProdOV computation fails on divide by zero.
765   if (DivIsSigned && DivRHS->isAllOnesValue())
766     return 0; // The overflow computation also screws up here
767   if (DivRHS->isOne()) {
768     // This eliminates some funny cases with INT_MIN.
769     ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
770     return &ICI;
771   }
772
773   // Compute Prod = CI * DivRHS. We are essentially solving an equation
774   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
775   // C2 (CI). By solving for X we can turn this into a range check 
776   // instead of computing a divide. 
777   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
778
779   // Determine if the product overflows by seeing if the product is
780   // not equal to the divide. Make sure we do the same kind of divide
781   // as in the LHS instruction that we're folding. 
782   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
783                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
784
785   // Get the ICmp opcode
786   ICmpInst::Predicate Pred = ICI.getPredicate();
787
788   /// If the division is known to be exact, then there is no remainder from the
789   /// divide, so the covered range size is unit, otherwise it is the divisor.
790   ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
791   
792   // Figure out the interval that is being checked.  For example, a comparison
793   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
794   // Compute this interval based on the constants involved and the signedness of
795   // the compare/divide.  This computes a half-open interval, keeping track of
796   // whether either value in the interval overflows.  After analysis each
797   // overflow variable is set to 0 if it's corresponding bound variable is valid
798   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
799   int LoOverflow = 0, HiOverflow = 0;
800   Constant *LoBound = 0, *HiBound = 0;
801
802   if (!DivIsSigned) {  // udiv
803     // e.g. X/5 op 3  --> [15, 20)
804     LoBound = Prod;
805     HiOverflow = LoOverflow = ProdOV;
806     if (!HiOverflow) {
807       // If this is not an exact divide, then many values in the range collapse
808       // to the same result value.
809       HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
810     }
811     
812   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
813     if (CmpRHSV == 0) {       // (X / pos) op 0
814       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
815       LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
816       HiBound = RangeSize;
817     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
818       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
819       HiOverflow = LoOverflow = ProdOV;
820       if (!HiOverflow)
821         HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
822     } else {                       // (X / pos) op neg
823       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
824       HiBound = AddOne(Prod);
825       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
826       if (!LoOverflow) {
827         ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
828         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
829       }
830     }
831   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
832     if (DivI->isExact())
833       RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
834     if (CmpRHSV == 0) {       // (X / neg) op 0
835       // e.g. X/-5 op 0  --> [-4, 5)
836       LoBound = AddOne(RangeSize);
837       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
838       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
839         HiOverflow = 1;            // [INTMIN+1, overflow)
840         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
841       }
842     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
843       // e.g. X/-5 op 3  --> [-19, -14)
844       HiBound = AddOne(Prod);
845       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
846       if (!LoOverflow)
847         LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
848     } else {                       // (X / neg) op neg
849       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
850       LoOverflow = HiOverflow = ProdOV;
851       if (!HiOverflow)
852         HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
853     }
854     
855     // Dividing by a negative swaps the condition.  LT <-> GT
856     Pred = ICmpInst::getSwappedPredicate(Pred);
857   }
858
859   Value *X = DivI->getOperand(0);
860   switch (Pred) {
861   default: llvm_unreachable("Unhandled icmp opcode!");
862   case ICmpInst::ICMP_EQ:
863     if (LoOverflow && HiOverflow)
864       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
865     if (HiOverflow)
866       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
867                           ICmpInst::ICMP_UGE, X, LoBound);
868     if (LoOverflow)
869       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
870                           ICmpInst::ICMP_ULT, X, HiBound);
871     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
872                                                     DivIsSigned, true));
873   case ICmpInst::ICMP_NE:
874     if (LoOverflow && HiOverflow)
875       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
876     if (HiOverflow)
877       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
878                           ICmpInst::ICMP_ULT, X, LoBound);
879     if (LoOverflow)
880       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
881                           ICmpInst::ICMP_UGE, X, HiBound);
882     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
883                                                     DivIsSigned, false));
884   case ICmpInst::ICMP_ULT:
885   case ICmpInst::ICMP_SLT:
886     if (LoOverflow == +1)   // Low bound is greater than input range.
887       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
888     if (LoOverflow == -1)   // Low bound is less than input range.
889       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
890     return new ICmpInst(Pred, X, LoBound);
891   case ICmpInst::ICMP_UGT:
892   case ICmpInst::ICMP_SGT:
893     if (HiOverflow == +1)       // High bound greater than input range.
894       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
895     if (HiOverflow == -1)       // High bound less than input range.
896       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
897     if (Pred == ICmpInst::ICMP_UGT)
898       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
899     return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
900   }
901 }
902
903 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
904 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
905                                           ConstantInt *ShAmt) {
906   const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
907   
908   // Check that the shift amount is in range.  If not, don't perform
909   // undefined shifts.  When the shift is visited it will be
910   // simplified.
911   uint32_t TypeBits = CmpRHSV.getBitWidth();
912   uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
913   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
914     return 0;
915   
916   if (!ICI.isEquality()) {
917     // If we have an unsigned comparison and an ashr, we can't simplify this.
918     // Similarly for signed comparisons with lshr.
919     if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
920       return 0;
921     
922     // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
923     // by a power of 2.  Since we already have logic to simplify these,
924     // transform to div and then simplify the resultant comparison.
925     if (Shr->getOpcode() == Instruction::AShr &&
926         (!Shr->isExact() || ShAmtVal == TypeBits - 1))
927       return 0;
928     
929     // Revisit the shift (to delete it).
930     Worklist.Add(Shr);
931     
932     Constant *DivCst =
933       ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
934     
935     Value *Tmp =
936       Shr->getOpcode() == Instruction::AShr ?
937       Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
938       Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
939     
940     ICI.setOperand(0, Tmp);
941     
942     // If the builder folded the binop, just return it.
943     BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
944     if (TheDiv == 0)
945       return &ICI;
946     
947     // Otherwise, fold this div/compare.
948     assert(TheDiv->getOpcode() == Instruction::SDiv ||
949            TheDiv->getOpcode() == Instruction::UDiv);
950     
951     Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
952     assert(Res && "This div/cst should have folded!");
953     return Res;
954   }
955   
956   
957   // If we are comparing against bits always shifted out, the
958   // comparison cannot succeed.
959   APInt Comp = CmpRHSV << ShAmtVal;
960   ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
961   if (Shr->getOpcode() == Instruction::LShr)
962     Comp = Comp.lshr(ShAmtVal);
963   else
964     Comp = Comp.ashr(ShAmtVal);
965   
966   if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
967     bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
968     Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
969                                      IsICMP_NE);
970     return ReplaceInstUsesWith(ICI, Cst);
971   }
972   
973   // Otherwise, check to see if the bits shifted out are known to be zero.
974   // If so, we can compare against the unshifted value:
975   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
976   if (Shr->hasOneUse() && Shr->isExact())
977     return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
978   
979   if (Shr->hasOneUse()) {
980     // Otherwise strength reduce the shift into an and.
981     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
982     Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
983     
984     Value *And = Builder->CreateAnd(Shr->getOperand(0),
985                                     Mask, Shr->getName()+".mask");
986     return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
987   }
988   return 0;
989 }
990
991
992 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
993 ///
994 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
995                                                           Instruction *LHSI,
996                                                           ConstantInt *RHS) {
997   const APInt &RHSV = RHS->getValue();
998   
999   switch (LHSI->getOpcode()) {
1000   case Instruction::Trunc:
1001     if (ICI.isEquality() && LHSI->hasOneUse()) {
1002       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1003       // of the high bits truncated out of x are known.
1004       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1005              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1006       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
1007       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1008       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
1009       
1010       // If all the high bits are known, we can do this xform.
1011       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1012         // Pull in the high bits from known-ones set.
1013         APInt NewRHS = RHS->getValue().zext(SrcBits);
1014         NewRHS |= KnownOne;
1015         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1016                             ConstantInt::get(ICI.getContext(), NewRHS));
1017       }
1018     }
1019     break;
1020       
1021   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
1022     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1023       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1024       // fold the xor.
1025       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1026           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1027         Value *CompareVal = LHSI->getOperand(0);
1028         
1029         // If the sign bit of the XorCST is not set, there is no change to
1030         // the operation, just stop using the Xor.
1031         if (!XorCST->getValue().isNegative()) {
1032           ICI.setOperand(0, CompareVal);
1033           Worklist.Add(LHSI);
1034           return &ICI;
1035         }
1036         
1037         // Was the old condition true if the operand is positive?
1038         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1039         
1040         // If so, the new one isn't.
1041         isTrueIfPositive ^= true;
1042         
1043         if (isTrueIfPositive)
1044           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1045                               SubOne(RHS));
1046         else
1047           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1048                               AddOne(RHS));
1049       }
1050
1051       if (LHSI->hasOneUse()) {
1052         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1053         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1054           const APInt &SignBit = XorCST->getValue();
1055           ICmpInst::Predicate Pred = ICI.isSigned()
1056                                          ? ICI.getUnsignedPredicate()
1057                                          : ICI.getSignedPredicate();
1058           return new ICmpInst(Pred, LHSI->getOperand(0),
1059                               ConstantInt::get(ICI.getContext(),
1060                                                RHSV ^ SignBit));
1061         }
1062
1063         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1064         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
1065           const APInt &NotSignBit = XorCST->getValue();
1066           ICmpInst::Predicate Pred = ICI.isSigned()
1067                                          ? ICI.getUnsignedPredicate()
1068                                          : ICI.getSignedPredicate();
1069           Pred = ICI.getSwappedPredicate(Pred);
1070           return new ICmpInst(Pred, LHSI->getOperand(0),
1071                               ConstantInt::get(ICI.getContext(),
1072                                                RHSV ^ NotSignBit));
1073         }
1074       }
1075     }
1076     break;
1077   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
1078     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1079         LHSI->getOperand(0)->hasOneUse()) {
1080       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1081       
1082       // If the LHS is an AND of a truncating cast, we can widen the
1083       // and/compare to be the input width without changing the value
1084       // produced, eliminating a cast.
1085       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1086         // We can do this transformation if either the AND constant does not
1087         // have its sign bit set or if it is an equality comparison. 
1088         // Extending a relational comparison when we're checking the sign
1089         // bit would not work.
1090         if (ICI.isEquality() ||
1091             (AndCST->getValue().isNonNegative() && RHSV.isNonNegative())) {
1092           Value *NewAnd =
1093             Builder->CreateAnd(Cast->getOperand(0),
1094                                ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1095           NewAnd->takeName(LHSI);
1096           return new ICmpInst(ICI.getPredicate(), NewAnd,
1097                               ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1098         }
1099       }
1100       
1101       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1102       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1103       // happens a LOT in code produced by the C front-end, for bitfield
1104       // access.
1105       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1106       if (Shift && !Shift->isShift())
1107         Shift = 0;
1108       
1109       ConstantInt *ShAmt;
1110       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1111       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
1112       const Type *AndTy = AndCST->getType();          // Type of the and.
1113       
1114       // We can fold this as long as we can't shift unknown bits
1115       // into the mask.  This can only happen with signed shift
1116       // rights, as they sign-extend.
1117       if (ShAmt) {
1118         bool CanFold = Shift->isLogicalShift();
1119         if (!CanFold) {
1120           // To test for the bad case of the signed shr, see if any
1121           // of the bits shifted in could be tested after the mask.
1122           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1123           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1124           
1125           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1126           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
1127                AndCST->getValue()) == 0)
1128             CanFold = true;
1129         }
1130         
1131         if (CanFold) {
1132           Constant *NewCst;
1133           if (Shift->getOpcode() == Instruction::Shl)
1134             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1135           else
1136             NewCst = ConstantExpr::getShl(RHS, ShAmt);
1137           
1138           // Check to see if we are shifting out any of the bits being
1139           // compared.
1140           if (ConstantExpr::get(Shift->getOpcode(),
1141                                        NewCst, ShAmt) != RHS) {
1142             // If we shifted bits out, the fold is not going to work out.
1143             // As a special case, check to see if this means that the
1144             // result is always true or false now.
1145             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1146               return ReplaceInstUsesWith(ICI,
1147                                        ConstantInt::getFalse(ICI.getContext()));
1148             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1149               return ReplaceInstUsesWith(ICI,
1150                                        ConstantInt::getTrue(ICI.getContext()));
1151           } else {
1152             ICI.setOperand(1, NewCst);
1153             Constant *NewAndCST;
1154             if (Shift->getOpcode() == Instruction::Shl)
1155               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1156             else
1157               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1158             LHSI->setOperand(1, NewAndCST);
1159             LHSI->setOperand(0, Shift->getOperand(0));
1160             Worklist.Add(Shift); // Shift is dead.
1161             return &ICI;
1162           }
1163         }
1164       }
1165       
1166       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1167       // preferable because it allows the C<<Y expression to be hoisted out
1168       // of a loop if Y is invariant and X is not.
1169       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1170           ICI.isEquality() && !Shift->isArithmeticShift() &&
1171           !isa<Constant>(Shift->getOperand(0))) {
1172         // Compute C << Y.
1173         Value *NS;
1174         if (Shift->getOpcode() == Instruction::LShr) {
1175           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
1176         } else {
1177           // Insert a logical shift.
1178           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
1179         }
1180         
1181         // Compute X & (C << Y).
1182         Value *NewAnd = 
1183           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1184         
1185         ICI.setOperand(0, NewAnd);
1186         return &ICI;
1187       }
1188     }
1189       
1190     // Try to optimize things like "A[i]&42 == 0" to index computations.
1191     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1192       if (GetElementPtrInst *GEP =
1193           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1194         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1195           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1196               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1197             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1198             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1199               return Res;
1200           }
1201     }
1202     break;
1203
1204   case Instruction::Or: {
1205     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1206       break;
1207     Value *P, *Q;
1208     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1209       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1210       // -> and (icmp eq P, null), (icmp eq Q, null).
1211       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1212                                         Constant::getNullValue(P->getType()));
1213       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1214                                         Constant::getNullValue(Q->getType()));
1215       Instruction *Op;
1216       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1217         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1218       else
1219         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1220       return Op;
1221     }
1222     break;
1223   }
1224     
1225   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1226     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1227     if (!ShAmt) break;
1228     
1229     uint32_t TypeBits = RHSV.getBitWidth();
1230     
1231     // Check that the shift amount is in range.  If not, don't perform
1232     // undefined shifts.  When the shift is visited it will be
1233     // simplified.
1234     if (ShAmt->uge(TypeBits))
1235       break;
1236     
1237     if (ICI.isEquality()) {
1238       // If we are comparing against bits always shifted out, the
1239       // comparison cannot succeed.
1240       Constant *Comp =
1241         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1242                                                                  ShAmt);
1243       if (Comp != RHS) {// Comparing against a bit that we know is zero.
1244         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1245         Constant *Cst =
1246           ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1247         return ReplaceInstUsesWith(ICI, Cst);
1248       }
1249       
1250       // If the shift is NUW, then it is just shifting out zeros, no need for an
1251       // AND.
1252       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1253         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1254                             ConstantExpr::getLShr(RHS, ShAmt));
1255       
1256       if (LHSI->hasOneUse()) {
1257         // Otherwise strength reduce the shift into an and.
1258         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1259         Constant *Mask =
1260           ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits, 
1261                                                        TypeBits-ShAmtVal));
1262         
1263         Value *And =
1264           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1265         return new ICmpInst(ICI.getPredicate(), And,
1266                             ConstantExpr::getLShr(RHS, ShAmt));
1267       }
1268     }
1269     
1270     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1271     bool TrueIfSigned = false;
1272     if (LHSI->hasOneUse() &&
1273         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1274       // (X << 31) <s 0  --> (X&1) != 0
1275       Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1276                                         APInt::getOneBitSet(TypeBits, 
1277                                             TypeBits-ShAmt->getZExtValue()-1));
1278       Value *And =
1279         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1280       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1281                           And, Constant::getNullValue(And->getType()));
1282     }
1283     break;
1284   }
1285     
1286   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1287   case Instruction::AShr: {
1288     // Handle equality comparisons of shift-by-constant.
1289     BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1290     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1291       if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1292         return Res;
1293     }
1294
1295     // Handle exact shr's.
1296     if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1297       if (RHSV.isMinValue())
1298         return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1299     }
1300     break;
1301   }
1302     
1303   case Instruction::SDiv:
1304   case Instruction::UDiv:
1305     // Fold: icmp pred ([us]div X, C1), C2 -> range test
1306     // Fold this div into the comparison, producing a range check. 
1307     // Determine, based on the divide type, what the range is being 
1308     // checked.  If there is an overflow on the low or high side, remember 
1309     // it, otherwise compute the range [low, hi) bounding the new value.
1310     // See: InsertRangeTest above for the kinds of replacements possible.
1311     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1312       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1313                                           DivRHS))
1314         return R;
1315     break;
1316
1317   case Instruction::Add:
1318     // Fold: icmp pred (add X, C1), C2
1319     if (!ICI.isEquality()) {
1320       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1321       if (!LHSC) break;
1322       const APInt &LHSV = LHSC->getValue();
1323
1324       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1325                             .subtract(LHSV);
1326
1327       if (ICI.isSigned()) {
1328         if (CR.getLower().isSignBit()) {
1329           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1330                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1331         } else if (CR.getUpper().isSignBit()) {
1332           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1333                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1334         }
1335       } else {
1336         if (CR.getLower().isMinValue()) {
1337           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1338                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1339         } else if (CR.getUpper().isMinValue()) {
1340           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1341                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1342         }
1343       }
1344     }
1345     break;
1346   }
1347   
1348   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1349   if (ICI.isEquality()) {
1350     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1351     
1352     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
1353     // the second operand is a constant, simplify a bit.
1354     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1355       switch (BO->getOpcode()) {
1356       case Instruction::SRem:
1357         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1358         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1359           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1360           if (V.sgt(1) && V.isPowerOf2()) {
1361             Value *NewRem =
1362               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1363                                   BO->getName());
1364             return new ICmpInst(ICI.getPredicate(), NewRem,
1365                                 Constant::getNullValue(BO->getType()));
1366           }
1367         }
1368         break;
1369       case Instruction::Add:
1370         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1371         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1372           if (BO->hasOneUse())
1373             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1374                                 ConstantExpr::getSub(RHS, BOp1C));
1375         } else if (RHSV == 0) {
1376           // Replace ((add A, B) != 0) with (A != -B) if A or B is
1377           // efficiently invertible, or if the add has just this one use.
1378           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1379           
1380           if (Value *NegVal = dyn_castNegVal(BOp1))
1381             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1382           if (Value *NegVal = dyn_castNegVal(BOp0))
1383             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1384           if (BO->hasOneUse()) {
1385             Value *Neg = Builder->CreateNeg(BOp1);
1386             Neg->takeName(BO);
1387             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1388           }
1389         }
1390         break;
1391       case Instruction::Xor:
1392         // For the xor case, we can xor two constants together, eliminating
1393         // the explicit xor.
1394         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1395           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
1396                               ConstantExpr::getXor(RHS, BOC));
1397         
1398         // FALLTHROUGH
1399       case Instruction::Sub:
1400         // Replace (([sub|xor] A, B) != 0) with (A != B)
1401         if (RHSV == 0)
1402           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1403                               BO->getOperand(1));
1404         break;
1405         
1406       case Instruction::Or:
1407         // If bits are being or'd in that are not present in the constant we
1408         // are comparing against, then the comparison could never succeed!
1409         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1410           Constant *NotCI = ConstantExpr::getNot(RHS);
1411           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1412             return ReplaceInstUsesWith(ICI,
1413                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 
1414                                        isICMP_NE));
1415         }
1416         break;
1417         
1418       case Instruction::And:
1419         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1420           // If bits are being compared against that are and'd out, then the
1421           // comparison can never succeed!
1422           if ((RHSV & ~BOC->getValue()) != 0)
1423             return ReplaceInstUsesWith(ICI,
1424                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1425                                        isICMP_NE));
1426           
1427           // If we have ((X & C) == C), turn it into ((X & C) != 0).
1428           if (RHS == BOC && RHSV.isPowerOf2())
1429             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1430                                 ICmpInst::ICMP_NE, LHSI,
1431                                 Constant::getNullValue(RHS->getType()));
1432           
1433           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1434           if (BOC->getValue().isSignBit()) {
1435             Value *X = BO->getOperand(0);
1436             Constant *Zero = Constant::getNullValue(X->getType());
1437             ICmpInst::Predicate pred = isICMP_NE ? 
1438               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1439             return new ICmpInst(pred, X, Zero);
1440           }
1441           
1442           // ((X & ~7) == 0) --> X < 8
1443           if (RHSV == 0 && isHighOnes(BOC)) {
1444             Value *X = BO->getOperand(0);
1445             Constant *NegX = ConstantExpr::getNeg(BOC);
1446             ICmpInst::Predicate pred = isICMP_NE ? 
1447               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1448             return new ICmpInst(pred, X, NegX);
1449           }
1450         }
1451       default: break;
1452       }
1453     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1454       // Handle icmp {eq|ne} <intrinsic>, intcst.
1455       switch (II->getIntrinsicID()) {
1456       case Intrinsic::bswap:
1457         Worklist.Add(II);
1458         ICI.setOperand(0, II->getArgOperand(0));
1459         ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1460         return &ICI;
1461       case Intrinsic::ctlz:
1462       case Intrinsic::cttz:
1463         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1464         if (RHSV == RHS->getType()->getBitWidth()) {
1465           Worklist.Add(II);
1466           ICI.setOperand(0, II->getArgOperand(0));
1467           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1468           return &ICI;
1469         }
1470         break;
1471       case Intrinsic::ctpop:
1472         // popcount(A) == 0  ->  A == 0 and likewise for !=
1473         if (RHS->isZero()) {
1474           Worklist.Add(II);
1475           ICI.setOperand(0, II->getArgOperand(0));
1476           ICI.setOperand(1, RHS);
1477           return &ICI;
1478         }
1479         break;
1480       default:
1481         break;
1482       }
1483     }
1484   }
1485   return 0;
1486 }
1487
1488 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1489 /// We only handle extending casts so far.
1490 ///
1491 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1492   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1493   Value *LHSCIOp        = LHSCI->getOperand(0);
1494   const Type *SrcTy     = LHSCIOp->getType();
1495   const Type *DestTy    = LHSCI->getType();
1496   Value *RHSCIOp;
1497
1498   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
1499   // integer type is the same size as the pointer type.
1500   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1501       TD->getPointerSizeInBits() ==
1502          cast<IntegerType>(DestTy)->getBitWidth()) {
1503     Value *RHSOp = 0;
1504     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1505       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1506     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1507       RHSOp = RHSC->getOperand(0);
1508       // If the pointer types don't match, insert a bitcast.
1509       if (LHSCIOp->getType() != RHSOp->getType())
1510         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1511     }
1512
1513     if (RHSOp)
1514       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1515   }
1516   
1517   // The code below only handles extension cast instructions, so far.
1518   // Enforce this.
1519   if (LHSCI->getOpcode() != Instruction::ZExt &&
1520       LHSCI->getOpcode() != Instruction::SExt)
1521     return 0;
1522
1523   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1524   bool isSignedCmp = ICI.isSigned();
1525
1526   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1527     // Not an extension from the same type?
1528     RHSCIOp = CI->getOperand(0);
1529     if (RHSCIOp->getType() != LHSCIOp->getType()) 
1530       return 0;
1531     
1532     // If the signedness of the two casts doesn't agree (i.e. one is a sext
1533     // and the other is a zext), then we can't handle this.
1534     if (CI->getOpcode() != LHSCI->getOpcode())
1535       return 0;
1536
1537     // Deal with equality cases early.
1538     if (ICI.isEquality())
1539       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1540
1541     // A signed comparison of sign extended values simplifies into a
1542     // signed comparison.
1543     if (isSignedCmp && isSignedExt)
1544       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1545
1546     // The other three cases all fold into an unsigned comparison.
1547     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1548   }
1549
1550   // If we aren't dealing with a constant on the RHS, exit early
1551   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1552   if (!CI)
1553     return 0;
1554
1555   // Compute the constant that would happen if we truncated to SrcTy then
1556   // reextended to DestTy.
1557   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1558   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1559                                                 Res1, DestTy);
1560
1561   // If the re-extended constant didn't change...
1562   if (Res2 == CI) {
1563     // Deal with equality cases early.
1564     if (ICI.isEquality())
1565       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1566
1567     // A signed comparison of sign extended values simplifies into a
1568     // signed comparison.
1569     if (isSignedExt && isSignedCmp)
1570       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1571
1572     // The other three cases all fold into an unsigned comparison.
1573     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1574   }
1575
1576   // The re-extended constant changed so the constant cannot be represented 
1577   // in the shorter type. Consequently, we cannot emit a simple comparison.
1578   // All the cases that fold to true or false will have already been handled
1579   // by SimplifyICmpInst, so only deal with the tricky case.
1580
1581   if (isSignedCmp || !isSignedExt)
1582     return 0;
1583
1584   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1585   // should have been folded away previously and not enter in here.
1586
1587   // We're performing an unsigned comp with a sign extended value.
1588   // This is true if the input is >= 0. [aka >s -1]
1589   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1590   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1591
1592   // Finally, return the value computed.
1593   if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1594     return ReplaceInstUsesWith(ICI, Result);
1595
1596   assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1597   return BinaryOperator::CreateNot(Result);
1598 }
1599
1600 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1601 ///   I = icmp ugt (add (add A, B), CI2), CI1
1602 /// If this is of the form:
1603 ///   sum = a + b
1604 ///   if (sum+128 >u 255)
1605 /// Then replace it with llvm.sadd.with.overflow.i8.
1606 ///
1607 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1608                                           ConstantInt *CI2, ConstantInt *CI1,
1609                                           InstCombiner &IC) {
1610   // The transformation we're trying to do here is to transform this into an
1611   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1612   // with a narrower add, and discard the add-with-constant that is part of the
1613   // range check (if we can't eliminate it, this isn't profitable).
1614   
1615   // In order to eliminate the add-with-constant, the compare can be its only
1616   // use.
1617   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1618   if (!AddWithCst->hasOneUse()) return 0;
1619   
1620   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1621   if (!CI2->getValue().isPowerOf2()) return 0;
1622   unsigned NewWidth = CI2->getValue().countTrailingZeros();
1623   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1624     
1625   // The width of the new add formed is 1 more than the bias.
1626   ++NewWidth;
1627   
1628   // Check to see that CI1 is an all-ones value with NewWidth bits.
1629   if (CI1->getBitWidth() == NewWidth ||
1630       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1631     return 0;
1632   
1633   // In order to replace the original add with a narrower 
1634   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1635   // and truncates that discard the high bits of the add.  Verify that this is
1636   // the case.
1637   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1638   for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1639        UI != E; ++UI) {
1640     if (*UI == AddWithCst) continue;
1641     
1642     // Only accept truncates for now.  We would really like a nice recursive
1643     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1644     // chain to see which bits of a value are actually demanded.  If the
1645     // original add had another add which was then immediately truncated, we
1646     // could still do the transformation.
1647     TruncInst *TI = dyn_cast<TruncInst>(*UI);
1648     if (TI == 0 ||
1649         TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1650   }
1651   
1652   // If the pattern matches, truncate the inputs to the narrower type and
1653   // use the sadd_with_overflow intrinsic to efficiently compute both the
1654   // result and the overflow bit.
1655   Module *M = I.getParent()->getParent()->getParent();
1656   
1657   const Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1658   Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1659                                        &NewType, 1);
1660
1661   InstCombiner::BuilderTy *Builder = IC.Builder;
1662   
1663   // Put the new code above the original add, in case there are any uses of the
1664   // add between the add and the compare.
1665   Builder->SetInsertPoint(OrigAdd);
1666   
1667   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1668   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1669   CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1670   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1671   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1672   
1673   // The inner add was the result of the narrow add, zero extended to the
1674   // wider type.  Replace it with the result computed by the intrinsic.
1675   IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1676   
1677   // The original icmp gets replaced with the overflow value.
1678   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1679 }
1680
1681 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1682                                      InstCombiner &IC) {
1683   // Don't bother doing this transformation for pointers, don't do it for
1684   // vectors.
1685   if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1686   
1687   // If the add is a constant expr, then we don't bother transforming it.
1688   Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1689   if (OrigAdd == 0) return 0;
1690   
1691   Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1692   
1693   // Put the new code above the original add, in case there are any uses of the
1694   // add between the add and the compare.
1695   InstCombiner::BuilderTy *Builder = IC.Builder;
1696   Builder->SetInsertPoint(OrigAdd);
1697
1698   Module *M = I.getParent()->getParent()->getParent();
1699   const Type *Ty = LHS->getType();
1700   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, &Ty,1);
1701   CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1702   Value *Add = Builder->CreateExtractValue(Call, 0);
1703
1704   IC.ReplaceInstUsesWith(*OrigAdd, Add);
1705
1706   // The original icmp gets replaced with the overflow value.
1707   return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1708 }
1709
1710 // DemandedBitsLHSMask - When performing a comparison against a constant,
1711 // it is possible that not all the bits in the LHS are demanded.  This helper
1712 // method computes the mask that IS demanded.
1713 static APInt DemandedBitsLHSMask(ICmpInst &I,
1714                                  unsigned BitWidth, bool isSignCheck) {
1715   if (isSignCheck)
1716     return APInt::getSignBit(BitWidth);
1717   
1718   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1719   if (!CI) return APInt::getAllOnesValue(BitWidth);
1720   const APInt &RHS = CI->getValue();
1721   
1722   switch (I.getPredicate()) {
1723   // For a UGT comparison, we don't care about any bits that 
1724   // correspond to the trailing ones of the comparand.  The value of these
1725   // bits doesn't impact the outcome of the comparison, because any value
1726   // greater than the RHS must differ in a bit higher than these due to carry.
1727   case ICmpInst::ICMP_UGT: {
1728     unsigned trailingOnes = RHS.countTrailingOnes();
1729     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1730     return ~lowBitsSet;
1731   }
1732   
1733   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1734   // Any value less than the RHS must differ in a higher bit because of carries.
1735   case ICmpInst::ICMP_ULT: {
1736     unsigned trailingZeros = RHS.countTrailingZeros();
1737     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1738     return ~lowBitsSet;
1739   }
1740   
1741   default:
1742     return APInt::getAllOnesValue(BitWidth);
1743   }
1744   
1745 }
1746
1747 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1748   bool Changed = false;
1749   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1750   
1751   /// Orders the operands of the compare so that they are listed from most
1752   /// complex to least complex.  This puts constants before unary operators,
1753   /// before binary operators.
1754   if (getComplexity(Op0) < getComplexity(Op1)) {
1755     I.swapOperands();
1756     std::swap(Op0, Op1);
1757     Changed = true;
1758   }
1759   
1760   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1761     return ReplaceInstUsesWith(I, V);
1762   
1763   const Type *Ty = Op0->getType();
1764
1765   // icmp's with boolean values can always be turned into bitwise operations
1766   if (Ty->isIntegerTy(1)) {
1767     switch (I.getPredicate()) {
1768     default: llvm_unreachable("Invalid icmp instruction!");
1769     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
1770       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1771       return BinaryOperator::CreateNot(Xor);
1772     }
1773     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
1774       return BinaryOperator::CreateXor(Op0, Op1);
1775
1776     case ICmpInst::ICMP_UGT:
1777       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
1778       // FALL THROUGH
1779     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
1780       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1781       return BinaryOperator::CreateAnd(Not, Op1);
1782     }
1783     case ICmpInst::ICMP_SGT:
1784       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
1785       // FALL THROUGH
1786     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
1787       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1788       return BinaryOperator::CreateAnd(Not, Op0);
1789     }
1790     case ICmpInst::ICMP_UGE:
1791       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
1792       // FALL THROUGH
1793     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
1794       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1795       return BinaryOperator::CreateOr(Not, Op1);
1796     }
1797     case ICmpInst::ICMP_SGE:
1798       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
1799       // FALL THROUGH
1800     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
1801       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1802       return BinaryOperator::CreateOr(Not, Op0);
1803     }
1804     }
1805   }
1806
1807   unsigned BitWidth = 0;
1808   if (Ty->isIntOrIntVectorTy())
1809     BitWidth = Ty->getScalarSizeInBits();
1810   else if (TD)  // Pointers require TD info to get their size.
1811     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
1812   
1813   bool isSignBit = false;
1814
1815   // See if we are doing a comparison with a constant.
1816   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1817     Value *A = 0, *B = 0;
1818     
1819     // Match the following pattern, which is a common idiom when writing
1820     // overflow-safe integer arithmetic function.  The source performs an
1821     // addition in wider type, and explicitly checks for overflow using
1822     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
1823     // sadd_with_overflow intrinsic.
1824     //
1825     // TODO: This could probably be generalized to handle other overflow-safe
1826     // operations if we worked out the formulas to compute the appropriate 
1827     // magic constants.
1828     // 
1829     // sum = a + b
1830     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
1831     {
1832     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
1833     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
1834         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1835       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
1836         return Res;
1837     }
1838     
1839     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1840     if (I.isEquality() && CI->isZero() &&
1841         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1842       // (icmp cond A B) if cond is equality
1843       return new ICmpInst(I.getPredicate(), A, B);
1844     }
1845     
1846     // If we have an icmp le or icmp ge instruction, turn it into the
1847     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
1848     // them being folded in the code below.  The SimplifyICmpInst code has
1849     // already handled the edge cases for us, so we just assert on them.
1850     switch (I.getPredicate()) {
1851     default: break;
1852     case ICmpInst::ICMP_ULE:
1853       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
1854       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1855                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1856     case ICmpInst::ICMP_SLE:
1857       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
1858       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1859                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1860     case ICmpInst::ICMP_UGE:
1861       assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
1862       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1863                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1864     case ICmpInst::ICMP_SGE:
1865       assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
1866       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1867                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1868     }
1869     
1870     // If this comparison is a normal comparison, it demands all
1871     // bits, if it is a sign bit comparison, it only demands the sign bit.
1872     bool UnusedBit;
1873     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1874   }
1875
1876   // See if we can fold the comparison based on range information we can get
1877   // by checking whether bits are known to be zero or one in the input.
1878   if (BitWidth != 0) {
1879     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1880     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1881
1882     if (SimplifyDemandedBits(I.getOperandUse(0),
1883                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
1884                              Op0KnownZero, Op0KnownOne, 0))
1885       return &I;
1886     if (SimplifyDemandedBits(I.getOperandUse(1),
1887                              APInt::getAllOnesValue(BitWidth),
1888                              Op1KnownZero, Op1KnownOne, 0))
1889       return &I;
1890
1891     // Given the known and unknown bits, compute a range that the LHS could be
1892     // in.  Compute the Min, Max and RHS values based on the known bits. For the
1893     // EQ and NE we use unsigned values.
1894     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1895     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1896     if (I.isSigned()) {
1897       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1898                                              Op0Min, Op0Max);
1899       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1900                                              Op1Min, Op1Max);
1901     } else {
1902       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1903                                                Op0Min, Op0Max);
1904       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1905                                                Op1Min, Op1Max);
1906     }
1907
1908     // If Min and Max are known to be the same, then SimplifyDemandedBits
1909     // figured out that the LHS is a constant.  Just constant fold this now so
1910     // that code below can assume that Min != Max.
1911     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1912       return new ICmpInst(I.getPredicate(),
1913                           ConstantInt::get(Op0->getType(), Op0Min), Op1);
1914     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1915       return new ICmpInst(I.getPredicate(), Op0,
1916                           ConstantInt::get(Op1->getType(), Op1Min));
1917
1918     // Based on the range information we know about the LHS, see if we can
1919     // simplify this comparison.  For example, (x&4) < 8 is always true.
1920     switch (I.getPredicate()) {
1921     default: llvm_unreachable("Unknown icmp opcode!");
1922     case ICmpInst::ICMP_EQ: {
1923       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1924         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
1925         
1926       // If all bits are known zero except for one, then we know at most one
1927       // bit is set.   If the comparison is against zero, then this is a check
1928       // to see if *that* bit is set.
1929       APInt Op0KnownZeroInverted = ~Op0KnownZero;
1930       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1931         // If the LHS is an AND with the same constant, look through it.
1932         Value *LHS = 0;
1933         ConstantInt *LHSC = 0;
1934         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1935             LHSC->getValue() != Op0KnownZeroInverted)
1936           LHS = Op0;
1937         
1938         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
1939         // then turn "((1 << x)&8) == 0" into "x != 3".
1940         Value *X = 0;
1941         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1942           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
1943           return new ICmpInst(ICmpInst::ICMP_NE, X,
1944                               ConstantInt::get(X->getType(), CmpVal));
1945         }
1946         
1947         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
1948         // then turn "((8 >>u x)&1) == 0" into "x != 3".
1949         const APInt *CI;
1950         if (Op0KnownZeroInverted == 1 &&
1951             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
1952           return new ICmpInst(ICmpInst::ICMP_NE, X,
1953                               ConstantInt::get(X->getType(),
1954                                                CI->countTrailingZeros()));
1955       }
1956         
1957       break;
1958     }
1959     case ICmpInst::ICMP_NE: {
1960       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1961         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
1962       
1963       // If all bits are known zero except for one, then we know at most one
1964       // bit is set.   If the comparison is against zero, then this is a check
1965       // to see if *that* bit is set.
1966       APInt Op0KnownZeroInverted = ~Op0KnownZero;
1967       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1968         // If the LHS is an AND with the same constant, look through it.
1969         Value *LHS = 0;
1970         ConstantInt *LHSC = 0;
1971         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1972             LHSC->getValue() != Op0KnownZeroInverted)
1973           LHS = Op0;
1974         
1975         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
1976         // then turn "((1 << x)&8) != 0" into "x == 3".
1977         Value *X = 0;
1978         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1979           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
1980           return new ICmpInst(ICmpInst::ICMP_EQ, X,
1981                               ConstantInt::get(X->getType(), CmpVal));
1982         }
1983         
1984         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
1985         // then turn "((8 >>u x)&1) != 0" into "x == 3".
1986         const APInt *CI;
1987         if (Op0KnownZeroInverted == 1 &&
1988             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
1989           return new ICmpInst(ICmpInst::ICMP_EQ, X,
1990                               ConstantInt::get(X->getType(),
1991                                                CI->countTrailingZeros()));
1992       }
1993       
1994       break;
1995     }
1996     case ICmpInst::ICMP_ULT:
1997       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
1998         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
1999       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
2000         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2001       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
2002         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2003       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2004         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
2005           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2006                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
2007
2008         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
2009         if (CI->isMinValue(true))
2010           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2011                            Constant::getAllOnesValue(Op0->getType()));
2012       }
2013       break;
2014     case ICmpInst::ICMP_UGT:
2015       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2016         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2017       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2018         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2019
2020       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2021         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2022       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2023         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2024           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2025                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2026
2027         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2028         if (CI->isMaxValue(true))
2029           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2030                               Constant::getNullValue(Op0->getType()));
2031       }
2032       break;
2033     case ICmpInst::ICMP_SLT:
2034       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2035         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2036       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2037         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2038       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2039         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2040       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2041         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2042           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2043                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
2044       }
2045       break;
2046     case ICmpInst::ICMP_SGT:
2047       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2048         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2049       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2050         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2051
2052       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2053         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2054       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2055         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2056           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2057                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2058       }
2059       break;
2060     case ICmpInst::ICMP_SGE:
2061       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2062       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2063         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2064       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2065         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2066       break;
2067     case ICmpInst::ICMP_SLE:
2068       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2069       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2070         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2071       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2072         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2073       break;
2074     case ICmpInst::ICMP_UGE:
2075       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2076       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2077         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2078       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2079         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2080       break;
2081     case ICmpInst::ICMP_ULE:
2082       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2083       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2084         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2085       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2086         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2087       break;
2088     }
2089
2090     // Turn a signed comparison into an unsigned one if both operands
2091     // are known to have the same sign.
2092     if (I.isSigned() &&
2093         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2094          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2095       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2096   }
2097
2098   // Test if the ICmpInst instruction is used exclusively by a select as
2099   // part of a minimum or maximum operation. If so, refrain from doing
2100   // any other folding. This helps out other analyses which understand
2101   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2102   // and CodeGen. And in this case, at least one of the comparison
2103   // operands has at least one user besides the compare (the select),
2104   // which would often largely negate the benefit of folding anyway.
2105   if (I.hasOneUse())
2106     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2107       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2108           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2109         return 0;
2110
2111   // See if we are doing a comparison between a constant and an instruction that
2112   // can be folded into the comparison.
2113   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2114     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
2115     // instruction, see if that instruction also has constants so that the 
2116     // instruction can be folded into the icmp 
2117     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2118       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2119         return Res;
2120   }
2121
2122   // Handle icmp with constant (but not simple integer constant) RHS
2123   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2124     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2125       switch (LHSI->getOpcode()) {
2126       case Instruction::GetElementPtr:
2127           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2128         if (RHSC->isNullValue() &&
2129             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2130           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2131                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
2132         break;
2133       case Instruction::PHI:
2134         // Only fold icmp into the PHI if the phi and icmp are in the same
2135         // block.  If in the same block, we're encouraging jump threading.  If
2136         // not, we are just pessimizing the code by making an i1 phi.
2137         if (LHSI->getParent() == I.getParent())
2138           if (Instruction *NV = FoldOpIntoPhi(I))
2139             return NV;
2140         break;
2141       case Instruction::Select: {
2142         // If either operand of the select is a constant, we can fold the
2143         // comparison into the select arms, which will cause one to be
2144         // constant folded and the select turned into a bitwise or.
2145         Value *Op1 = 0, *Op2 = 0;
2146         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2147           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2148         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2149           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2150
2151         // We only want to perform this transformation if it will not lead to
2152         // additional code. This is true if either both sides of the select
2153         // fold to a constant (in which case the icmp is replaced with a select
2154         // which will usually simplify) or this is the only user of the
2155         // select (in which case we are trading a select+icmp for a simpler
2156         // select+icmp).
2157         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2158           if (!Op1)
2159             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2160                                       RHSC, I.getName());
2161           if (!Op2)
2162             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2163                                       RHSC, I.getName());
2164           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2165         }
2166         break;
2167       }
2168       case Instruction::IntToPtr:
2169         // icmp pred inttoptr(X), null -> icmp pred X, 0
2170         if (RHSC->isNullValue() && TD &&
2171             TD->getIntPtrType(RHSC->getContext()) == 
2172                LHSI->getOperand(0)->getType())
2173           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2174                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
2175         break;
2176
2177       case Instruction::Load:
2178         // Try to optimize things like "A[i] > 4" to index computations.
2179         if (GetElementPtrInst *GEP =
2180               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2181           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2182             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2183                 !cast<LoadInst>(LHSI)->isVolatile())
2184               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2185                 return Res;
2186         }
2187         break;
2188       }
2189   }
2190
2191   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2192   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2193     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2194       return NI;
2195   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2196     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2197                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2198       return NI;
2199
2200   // Test to see if the operands of the icmp are casted versions of other
2201   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2202   // now.
2203   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2204     if (Op0->getType()->isPointerTy() && 
2205         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
2206       // We keep moving the cast from the left operand over to the right
2207       // operand, where it can often be eliminated completely.
2208       Op0 = CI->getOperand(0);
2209
2210       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2211       // so eliminate it as well.
2212       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2213         Op1 = CI2->getOperand(0);
2214
2215       // If Op1 is a constant, we can fold the cast into the constant.
2216       if (Op0->getType() != Op1->getType()) {
2217         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2218           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2219         } else {
2220           // Otherwise, cast the RHS right before the icmp
2221           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2222         }
2223       }
2224       return new ICmpInst(I.getPredicate(), Op0, Op1);
2225     }
2226   }
2227   
2228   if (isa<CastInst>(Op0)) {
2229     // Handle the special case of: icmp (cast bool to X), <cst>
2230     // This comes up when you have code like
2231     //   int X = A < B;
2232     //   if (X) ...
2233     // For generality, we handle any zero-extension of any operand comparison
2234     // with a constant or another cast from the same type.
2235     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2236       if (Instruction *R = visitICmpInstWithCastAndCast(I))
2237         return R;
2238   }
2239
2240   // Special logic for binary operators.
2241   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2242   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2243   if (BO0 || BO1) {
2244     CmpInst::Predicate Pred = I.getPredicate();
2245     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2246     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2247       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2248         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2249         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2250     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2251       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2252         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2253         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2254
2255     // Analyze the case when either Op0 or Op1 is an add instruction.
2256     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2257     Value *A = 0, *B = 0, *C = 0, *D = 0;
2258     if (BO0 && BO0->getOpcode() == Instruction::Add)
2259       A = BO0->getOperand(0), B = BO0->getOperand(1);
2260     if (BO1 && BO1->getOpcode() == Instruction::Add)
2261       C = BO1->getOperand(0), D = BO1->getOperand(1);
2262
2263     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2264     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2265       return new ICmpInst(Pred, A == Op1 ? B : A,
2266                           Constant::getNullValue(Op1->getType()));
2267
2268     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2269     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2270       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2271                           C == Op0 ? D : C);
2272
2273     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2274     if (A && C && (A == C || A == D || B == C || B == D) &&
2275         NoOp0WrapProblem && NoOp1WrapProblem &&
2276         // Try not to increase register pressure.
2277         BO0->hasOneUse() && BO1->hasOneUse()) {
2278       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2279       Value *Y = (A == C || A == D) ? B : A;
2280       Value *Z = (C == A || C == B) ? D : C;
2281       return new ICmpInst(Pred, Y, Z);
2282     }
2283
2284     // Analyze the case when either Op0 or Op1 is a sub instruction.
2285     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2286     A = 0; B = 0; C = 0; D = 0;
2287     if (BO0 && BO0->getOpcode() == Instruction::Sub)
2288       A = BO0->getOperand(0), B = BO0->getOperand(1);
2289     if (BO1 && BO1->getOpcode() == Instruction::Sub)
2290       C = BO1->getOperand(0), D = BO1->getOperand(1);
2291
2292     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2293     if (A == Op1 && NoOp0WrapProblem)
2294       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2295
2296     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2297     if (C == Op0 && NoOp1WrapProblem)
2298       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2299
2300     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2301     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2302         // Try not to increase register pressure.
2303         BO0->hasOneUse() && BO1->hasOneUse())
2304       return new ICmpInst(Pred, A, C);
2305
2306     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2307     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2308         // Try not to increase register pressure.
2309         BO0->hasOneUse() && BO1->hasOneUse())
2310       return new ICmpInst(Pred, D, B);
2311
2312     BinaryOperator *SRem = NULL;
2313     // icmp (srem X, Y), Y
2314     if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2315         Op1 == BO0->getOperand(1))
2316       SRem = BO0;
2317     // icmp Y, (srem X, Y)
2318     else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2319              Op0 == BO1->getOperand(1))
2320       SRem = BO1;
2321     if (SRem) {
2322       // We don't check hasOneUse to avoid increasing register pressure because
2323       // the value we use is the same value this instruction was already using.
2324       switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2325         default: break;
2326         case ICmpInst::ICMP_EQ:
2327           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2328         case ICmpInst::ICMP_NE:
2329           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2330         case ICmpInst::ICMP_SGT:
2331         case ICmpInst::ICMP_SGE:
2332           return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2333                               Constant::getAllOnesValue(SRem->getType()));
2334         case ICmpInst::ICMP_SLT:
2335         case ICmpInst::ICMP_SLE:
2336           return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2337                               Constant::getNullValue(SRem->getType()));
2338       }
2339     }
2340
2341     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2342         BO0->hasOneUse() && BO1->hasOneUse() &&
2343         BO0->getOperand(1) == BO1->getOperand(1)) {
2344       switch (BO0->getOpcode()) {
2345       default: break;
2346       case Instruction::Add:
2347       case Instruction::Sub:
2348       case Instruction::Xor:
2349         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2350           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2351                               BO1->getOperand(0));
2352         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2353         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2354           if (CI->getValue().isSignBit()) {
2355             ICmpInst::Predicate Pred = I.isSigned()
2356                                            ? I.getUnsignedPredicate()
2357                                            : I.getSignedPredicate();
2358             return new ICmpInst(Pred, BO0->getOperand(0),
2359                                 BO1->getOperand(0));
2360           }
2361           
2362           if (CI->getValue().isMaxSignedValue()) {
2363             ICmpInst::Predicate Pred = I.isSigned()
2364                                            ? I.getUnsignedPredicate()
2365                                            : I.getSignedPredicate();
2366             Pred = I.getSwappedPredicate(Pred);
2367             return new ICmpInst(Pred, BO0->getOperand(0),
2368                                 BO1->getOperand(0));
2369           }
2370         }
2371         break;
2372       case Instruction::Mul:
2373         if (!I.isEquality())
2374           break;
2375
2376         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2377           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2378           // Mask = -1 >> count-trailing-zeros(Cst).
2379           if (!CI->isZero() && !CI->isOne()) {
2380             const APInt &AP = CI->getValue();
2381             ConstantInt *Mask = ConstantInt::get(I.getContext(), 
2382                                     APInt::getLowBitsSet(AP.getBitWidth(),
2383                                                          AP.getBitWidth() -
2384                                                     AP.countTrailingZeros()));
2385             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2386             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2387             return new ICmpInst(I.getPredicate(), And1, And2);
2388           }
2389         }
2390         break;
2391       case Instruction::UDiv:
2392       case Instruction::LShr:
2393         if (I.isSigned())
2394           break;
2395         // fall-through
2396       case Instruction::SDiv:
2397       case Instruction::AShr:
2398         if (!BO0->isExact() || !BO1->isExact())
2399           break;
2400         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2401                             BO1->getOperand(0));
2402       case Instruction::Shl: {
2403         bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2404         bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2405         if (!NUW && !NSW)
2406           break;
2407         if (!NSW && I.isSigned())
2408           break;
2409         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2410                             BO1->getOperand(0));
2411       }
2412       }
2413     }
2414   }
2415   
2416   { Value *A, *B;
2417     // ~x < ~y --> y < x
2418     // ~x < cst --> ~cst < x
2419     if (match(Op0, m_Not(m_Value(A)))) {
2420       if (match(Op1, m_Not(m_Value(B))))
2421         return new ICmpInst(I.getPredicate(), B, A);
2422       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2423         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2424     }
2425
2426     // (a+b) <u a  --> llvm.uadd.with.overflow.
2427     // (a+b) <u b  --> llvm.uadd.with.overflow.
2428     if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2429         match(Op0, m_Add(m_Value(A), m_Value(B))) && 
2430         (Op1 == A || Op1 == B))
2431       if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2432         return R;
2433                                  
2434     // a >u (a+b)  --> llvm.uadd.with.overflow.
2435     // b >u (a+b)  --> llvm.uadd.with.overflow.
2436     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2437         match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2438         (Op0 == A || Op0 == B))
2439       if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2440         return R;
2441   }
2442   
2443   if (I.isEquality()) {
2444     Value *A, *B, *C, *D;
2445
2446     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2447       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2448         Value *OtherVal = A == Op1 ? B : A;
2449         return new ICmpInst(I.getPredicate(), OtherVal,
2450                             Constant::getNullValue(A->getType()));
2451       }
2452
2453       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2454         // A^c1 == C^c2 --> A == C^(c1^c2)
2455         ConstantInt *C1, *C2;
2456         if (match(B, m_ConstantInt(C1)) &&
2457             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2458           Constant *NC = ConstantInt::get(I.getContext(),
2459                                           C1->getValue() ^ C2->getValue());
2460           Value *Xor = Builder->CreateXor(C, NC, "tmp");
2461           return new ICmpInst(I.getPredicate(), A, Xor);
2462         }
2463         
2464         // A^B == A^D -> B == D
2465         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2466         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2467         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2468         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2469       }
2470     }
2471     
2472     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2473         (A == Op0 || B == Op0)) {
2474       // A == (A^B)  ->  B == 0
2475       Value *OtherVal = A == Op0 ? B : A;
2476       return new ICmpInst(I.getPredicate(), OtherVal,
2477                           Constant::getNullValue(A->getType()));
2478     }
2479
2480     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2481     if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) && 
2482         match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2483       Value *X = 0, *Y = 0, *Z = 0;
2484       
2485       if (A == C) {
2486         X = B; Y = D; Z = A;
2487       } else if (A == D) {
2488         X = B; Y = C; Z = A;
2489       } else if (B == C) {
2490         X = A; Y = D; Z = B;
2491       } else if (B == D) {
2492         X = A; Y = C; Z = B;
2493       }
2494       
2495       if (X) {   // Build (X^Y) & Z
2496         Op1 = Builder->CreateXor(X, Y, "tmp");
2497         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
2498         I.setOperand(0, Op1);
2499         I.setOperand(1, Constant::getNullValue(Op1->getType()));
2500         return &I;
2501       }
2502     }
2503     
2504     // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2505     // "icmp (and X, mask), cst"
2506     uint64_t ShAmt = 0;
2507     ConstantInt *Cst1;
2508     if (Op0->hasOneUse() &&
2509         match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2510                                            m_ConstantInt(ShAmt))))) &&
2511         match(Op1, m_ConstantInt(Cst1)) &&
2512         // Only do this when A has multiple uses.  This is most important to do
2513         // when it exposes other optimizations.
2514         !A->hasOneUse()) {
2515       unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2516       
2517       if (ShAmt < ASize) {
2518         APInt MaskV =
2519           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2520         MaskV <<= ShAmt;
2521         
2522         APInt CmpV = Cst1->getValue().zext(ASize);
2523         CmpV <<= ShAmt;
2524         
2525         Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2526         return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2527       }
2528     }
2529   }
2530   
2531   {
2532     Value *X; ConstantInt *Cst;
2533     // icmp X+Cst, X
2534     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2535       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2536
2537     // icmp X, X+Cst
2538     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2539       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2540   }
2541   return Changed ? &I : 0;
2542 }
2543
2544
2545
2546
2547
2548
2549 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2550 ///
2551 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2552                                                 Instruction *LHSI,
2553                                                 Constant *RHSC) {
2554   if (!isa<ConstantFP>(RHSC)) return 0;
2555   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2556   
2557   // Get the width of the mantissa.  We don't want to hack on conversions that
2558   // might lose information from the integer, e.g. "i64 -> float"
2559   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2560   if (MantissaWidth == -1) return 0;  // Unknown.
2561   
2562   // Check to see that the input is converted from an integer type that is small
2563   // enough that preserves all bits.  TODO: check here for "known" sign bits.
2564   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2565   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2566   
2567   // If this is a uitofp instruction, we need an extra bit to hold the sign.
2568   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2569   if (LHSUnsigned)
2570     ++InputSize;
2571   
2572   // If the conversion would lose info, don't hack on this.
2573   if ((int)InputSize > MantissaWidth)
2574     return 0;
2575   
2576   // Otherwise, we can potentially simplify the comparison.  We know that it
2577   // will always come through as an integer value and we know the constant is
2578   // not a NAN (it would have been previously simplified).
2579   assert(!RHS.isNaN() && "NaN comparison not already folded!");
2580   
2581   ICmpInst::Predicate Pred;
2582   switch (I.getPredicate()) {
2583   default: llvm_unreachable("Unexpected predicate!");
2584   case FCmpInst::FCMP_UEQ:
2585   case FCmpInst::FCMP_OEQ:
2586     Pred = ICmpInst::ICMP_EQ;
2587     break;
2588   case FCmpInst::FCMP_UGT:
2589   case FCmpInst::FCMP_OGT:
2590     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2591     break;
2592   case FCmpInst::FCMP_UGE:
2593   case FCmpInst::FCMP_OGE:
2594     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2595     break;
2596   case FCmpInst::FCMP_ULT:
2597   case FCmpInst::FCMP_OLT:
2598     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2599     break;
2600   case FCmpInst::FCMP_ULE:
2601   case FCmpInst::FCMP_OLE:
2602     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2603     break;
2604   case FCmpInst::FCMP_UNE:
2605   case FCmpInst::FCMP_ONE:
2606     Pred = ICmpInst::ICMP_NE;
2607     break;
2608   case FCmpInst::FCMP_ORD:
2609     return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2610   case FCmpInst::FCMP_UNO:
2611     return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2612   }
2613   
2614   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2615   
2616   // Now we know that the APFloat is a normal number, zero or inf.
2617   
2618   // See if the FP constant is too large for the integer.  For example,
2619   // comparing an i8 to 300.0.
2620   unsigned IntWidth = IntTy->getScalarSizeInBits();
2621   
2622   if (!LHSUnsigned) {
2623     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
2624     // and large values.
2625     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2626     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2627                           APFloat::rmNearestTiesToEven);
2628     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
2629       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
2630           Pred == ICmpInst::ICMP_SLE)
2631         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2632       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2633     }
2634   } else {
2635     // If the RHS value is > UnsignedMax, fold the comparison. This handles
2636     // +INF and large values.
2637     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2638     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2639                           APFloat::rmNearestTiesToEven);
2640     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
2641       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
2642           Pred == ICmpInst::ICMP_ULE)
2643         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2644       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2645     }
2646   }
2647   
2648   if (!LHSUnsigned) {
2649     // See if the RHS value is < SignedMin.
2650     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2651     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2652                           APFloat::rmNearestTiesToEven);
2653     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2654       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2655           Pred == ICmpInst::ICMP_SGE)
2656         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2657       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2658     }
2659   }
2660
2661   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2662   // [0, UMAX], but it may still be fractional.  See if it is fractional by
2663   // casting the FP value to the integer value and back, checking for equality.
2664   // Don't do this for zero, because -0.0 is not fractional.
2665   Constant *RHSInt = LHSUnsigned
2666     ? ConstantExpr::getFPToUI(RHSC, IntTy)
2667     : ConstantExpr::getFPToSI(RHSC, IntTy);
2668   if (!RHS.isZero()) {
2669     bool Equal = LHSUnsigned
2670       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2671       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2672     if (!Equal) {
2673       // If we had a comparison against a fractional value, we have to adjust
2674       // the compare predicate and sometimes the value.  RHSC is rounded towards
2675       // zero at this point.
2676       switch (Pred) {
2677       default: llvm_unreachable("Unexpected integer comparison!");
2678       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
2679         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2680       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
2681         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2682       case ICmpInst::ICMP_ULE:
2683         // (float)int <= 4.4   --> int <= 4
2684         // (float)int <= -4.4  --> false
2685         if (RHS.isNegative())
2686           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2687         break;
2688       case ICmpInst::ICMP_SLE:
2689         // (float)int <= 4.4   --> int <= 4
2690         // (float)int <= -4.4  --> int < -4
2691         if (RHS.isNegative())
2692           Pred = ICmpInst::ICMP_SLT;
2693         break;
2694       case ICmpInst::ICMP_ULT:
2695         // (float)int < -4.4   --> false
2696         // (float)int < 4.4    --> int <= 4
2697         if (RHS.isNegative())
2698           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2699         Pred = ICmpInst::ICMP_ULE;
2700         break;
2701       case ICmpInst::ICMP_SLT:
2702         // (float)int < -4.4   --> int < -4
2703         // (float)int < 4.4    --> int <= 4
2704         if (!RHS.isNegative())
2705           Pred = ICmpInst::ICMP_SLE;
2706         break;
2707       case ICmpInst::ICMP_UGT:
2708         // (float)int > 4.4    --> int > 4
2709         // (float)int > -4.4   --> true
2710         if (RHS.isNegative())
2711           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2712         break;
2713       case ICmpInst::ICMP_SGT:
2714         // (float)int > 4.4    --> int > 4
2715         // (float)int > -4.4   --> int >= -4
2716         if (RHS.isNegative())
2717           Pred = ICmpInst::ICMP_SGE;
2718         break;
2719       case ICmpInst::ICMP_UGE:
2720         // (float)int >= -4.4   --> true
2721         // (float)int >= 4.4    --> int > 4
2722         if (!RHS.isNegative())
2723           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2724         Pred = ICmpInst::ICMP_UGT;
2725         break;
2726       case ICmpInst::ICMP_SGE:
2727         // (float)int >= -4.4   --> int >= -4
2728         // (float)int >= 4.4    --> int > 4
2729         if (!RHS.isNegative())
2730           Pred = ICmpInst::ICMP_SGT;
2731         break;
2732       }
2733     }
2734   }
2735
2736   // Lower this FP comparison into an appropriate integer version of the
2737   // comparison.
2738   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2739 }
2740
2741 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2742   bool Changed = false;
2743   
2744   /// Orders the operands of the compare so that they are listed from most
2745   /// complex to least complex.  This puts constants before unary operators,
2746   /// before binary operators.
2747   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2748     I.swapOperands();
2749     Changed = true;
2750   }
2751
2752   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2753   
2754   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2755     return ReplaceInstUsesWith(I, V);
2756
2757   // Simplify 'fcmp pred X, X'
2758   if (Op0 == Op1) {
2759     switch (I.getPredicate()) {
2760     default: llvm_unreachable("Unknown predicate!");
2761     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
2762     case FCmpInst::FCMP_ULT:    // True if unordered or less than
2763     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
2764     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
2765       // Canonicalize these to be 'fcmp uno %X, 0.0'.
2766       I.setPredicate(FCmpInst::FCMP_UNO);
2767       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2768       return &I;
2769       
2770     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
2771     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
2772     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
2773     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
2774       // Canonicalize these to be 'fcmp ord %X, 0.0'.
2775       I.setPredicate(FCmpInst::FCMP_ORD);
2776       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2777       return &I;
2778     }
2779   }
2780     
2781   // Handle fcmp with constant RHS
2782   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2783     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2784       switch (LHSI->getOpcode()) {
2785       case Instruction::FPExt: {
2786         // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2787         FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2788         ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2789         if (!RHSF)
2790           break;
2791
2792         // We can't convert a PPC double double.
2793         if (RHSF->getType()->isPPC_FP128Ty())
2794           break;
2795
2796         const fltSemantics *Sem;
2797         // FIXME: This shouldn't be here.
2798         if (LHSExt->getSrcTy()->isFloatTy())
2799           Sem = &APFloat::IEEEsingle;
2800         else if (LHSExt->getSrcTy()->isDoubleTy())
2801           Sem = &APFloat::IEEEdouble;
2802         else if (LHSExt->getSrcTy()->isFP128Ty())
2803           Sem = &APFloat::IEEEquad;
2804         else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2805           Sem = &APFloat::x87DoubleExtended;
2806         else
2807           break;
2808
2809         bool Lossy;
2810         APFloat F = RHSF->getValueAPF();
2811         F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2812
2813         // Avoid lossy conversions and denormals.
2814         if (!Lossy &&
2815             F.compare(APFloat::getSmallestNormalized(*Sem)) !=
2816                                                            APFloat::cmpLessThan)
2817           return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2818                               ConstantFP::get(RHSC->getContext(), F));
2819         break;
2820       }
2821       case Instruction::PHI:
2822         // Only fold fcmp into the PHI if the phi and fcmp are in the same
2823         // block.  If in the same block, we're encouraging jump threading.  If
2824         // not, we are just pessimizing the code by making an i1 phi.
2825         if (LHSI->getParent() == I.getParent())
2826           if (Instruction *NV = FoldOpIntoPhi(I))
2827             return NV;
2828         break;
2829       case Instruction::SIToFP:
2830       case Instruction::UIToFP:
2831         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2832           return NV;
2833         break;
2834       case Instruction::Select: {
2835         // If either operand of the select is a constant, we can fold the
2836         // comparison into the select arms, which will cause one to be
2837         // constant folded and the select turned into a bitwise or.
2838         Value *Op1 = 0, *Op2 = 0;
2839         if (LHSI->hasOneUse()) {
2840           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2841             // Fold the known value into the constant operand.
2842             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2843             // Insert a new FCmp of the other select operand.
2844             Op2 = Builder->CreateFCmp(I.getPredicate(),
2845                                       LHSI->getOperand(2), RHSC, I.getName());
2846           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2847             // Fold the known value into the constant operand.
2848             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2849             // Insert a new FCmp of the other select operand.
2850             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2851                                       RHSC, I.getName());
2852           }
2853         }
2854
2855         if (Op1)
2856           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2857         break;
2858       }
2859       case Instruction::FSub: {
2860         // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
2861         Value *Op;
2862         if (match(LHSI, m_FNeg(m_Value(Op))))
2863           return new FCmpInst(I.getSwappedPredicate(), Op,
2864                               ConstantExpr::getFNeg(RHSC));
2865         break;
2866       }
2867       case Instruction::Load:
2868         if (GetElementPtrInst *GEP =
2869             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2870           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2871             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2872                 !cast<LoadInst>(LHSI)->isVolatile())
2873               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2874                 return Res;
2875         }
2876         break;
2877       }
2878   }
2879
2880   // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
2881   Value *X, *Y;
2882   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
2883     return new FCmpInst(I.getSwappedPredicate(), X, Y);
2884
2885   // fcmp (fpext x), (fpext y) -> fcmp x, y
2886   if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
2887     if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
2888       if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
2889         return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2890                             RHSExt->getOperand(0));
2891
2892   return Changed ? &I : 0;
2893 }