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