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