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