refactor some code out into a helper method.
[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   // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
702   bool isNUW = false, isNSW = false;
703   if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
704     isNUW = Add->hasNoUnsignedWrap();
705     isNSW = Add->hasNoSignedWrap();
706   }      
707   
708   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
709   // so the values can never be equal.  Similiarly for all other "or equals"
710   // operators.
711   
712   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
713   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
714   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
715   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
716     // If this is an NUW add, then this is always false.
717     if (isNUW)
718       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 
719     
720     Value *R = 
721       ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
722     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
723   }
724   
725   // (X+1) >u X        --> X <u (0-1)        --> X != 255
726   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
727   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
728   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
729     // If this is an NUW add, then this is always true.
730     if (isNUW)
731       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 
732     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
733   }
734   
735   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
736   ConstantInt *SMax = ConstantInt::get(X->getContext(),
737                                        APInt::getSignedMaxValue(BitWidth));
738
739   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
740   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
741   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
742   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
743   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
744   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
745   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
746     // If this is an NSW add, then we have two cases: if the constant is
747     // positive, then this is always false, if negative, this is always true.
748     if (isNSW) {
749       bool isTrue = CI->getValue().isNegative();
750       return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
751     }
752     
753     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
754   }
755   
756   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
757   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
758   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
759   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
760   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
761   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
762   
763   // If this is an NSW add, then we have two cases: if the constant is
764   // positive, then this is always true, if negative, this is always false.
765   if (isNSW) {
766     bool isTrue = !CI->getValue().isNegative();
767     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
768   }
769   
770   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
771   Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
772   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
773 }
774
775 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
776 /// and CmpRHS are both known to be integer constants.
777 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
778                                           ConstantInt *DivRHS) {
779   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
780   const APInt &CmpRHSV = CmpRHS->getValue();
781   
782   // FIXME: If the operand types don't match the type of the divide 
783   // then don't attempt this transform. The code below doesn't have the
784   // logic to deal with a signed divide and an unsigned compare (and
785   // vice versa). This is because (x /s C1) <s C2  produces different 
786   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
787   // (x /u C1) <u C2.  Simply casting the operands and result won't 
788   // work. :(  The if statement below tests that condition and bails 
789   // if it finds it.
790   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
791   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
792     return 0;
793   if (DivRHS->isZero())
794     return 0; // The ProdOV computation fails on divide by zero.
795   if (DivIsSigned && DivRHS->isAllOnesValue())
796     return 0; // The overflow computation also screws up here
797   if (DivRHS->isOne())
798     return 0; // Not worth bothering, and eliminates some funny cases
799               // with INT_MIN.
800
801   // Compute Prod = CI * DivRHS. We are essentially solving an equation
802   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
803   // C2 (CI). By solving for X we can turn this into a range check 
804   // instead of computing a divide. 
805   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
806
807   // Determine if the product overflows by seeing if the product is
808   // not equal to the divide. Make sure we do the same kind of divide
809   // as in the LHS instruction that we're folding. 
810   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
811                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
812
813   // Get the ICmp opcode
814   ICmpInst::Predicate Pred = ICI.getPredicate();
815
816   /// If the division is known to be exact, then there is no remainder from the
817   /// divide, so the covered range size is unit, otherwise it is the divisor.
818   ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
819   
820   // Figure out the interval that is being checked.  For example, a comparison
821   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
822   // Compute this interval based on the constants involved and the signedness of
823   // the compare/divide.  This computes a half-open interval, keeping track of
824   // whether either value in the interval overflows.  After analysis each
825   // overflow variable is set to 0 if it's corresponding bound variable is valid
826   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
827   int LoOverflow = 0, HiOverflow = 0;
828   Constant *LoBound = 0, *HiBound = 0;
829
830   if (!DivIsSigned) {  // udiv
831     // e.g. X/5 op 3  --> [15, 20)
832     LoBound = Prod;
833     HiOverflow = LoOverflow = ProdOV;
834     if (!HiOverflow) {
835       // If this is not an exact divide, then many values in the range collapse
836       // to the same result value.
837       HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
838     }
839     
840   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
841     if (CmpRHSV == 0) {       // (X / pos) op 0
842       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
843       LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
844       HiBound = RangeSize;
845     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
846       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
847       HiOverflow = LoOverflow = ProdOV;
848       if (!HiOverflow)
849         HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
850     } else {                       // (X / pos) op neg
851       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
852       HiBound = AddOne(Prod);
853       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
854       if (!LoOverflow) {
855         ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
856         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
857       }
858     }
859   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
860     if (DivI->isExact())
861       RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
862     if (CmpRHSV == 0) {       // (X / neg) op 0
863       // e.g. X/-5 op 0  --> [-4, 5)
864       LoBound = AddOne(RangeSize);
865       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
866       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
867         HiOverflow = 1;            // [INTMIN+1, overflow)
868         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
869       }
870     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
871       // e.g. X/-5 op 3  --> [-19, -14)
872       HiBound = AddOne(Prod);
873       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
874       if (!LoOverflow)
875         LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
876     } else {                       // (X / neg) op neg
877       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
878       LoOverflow = HiOverflow = ProdOV;
879       if (!HiOverflow)
880         HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
881     }
882     
883     // Dividing by a negative swaps the condition.  LT <-> GT
884     Pred = ICmpInst::getSwappedPredicate(Pred);
885   }
886
887   Value *X = DivI->getOperand(0);
888   switch (Pred) {
889   default: llvm_unreachable("Unhandled icmp opcode!");
890   case ICmpInst::ICMP_EQ:
891     if (LoOverflow && HiOverflow)
892       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
893     if (HiOverflow)
894       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
895                           ICmpInst::ICMP_UGE, X, LoBound);
896     if (LoOverflow)
897       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
898                           ICmpInst::ICMP_ULT, X, HiBound);
899     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
900                                                     DivIsSigned, true));
901   case ICmpInst::ICMP_NE:
902     if (LoOverflow && HiOverflow)
903       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
904     if (HiOverflow)
905       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
906                           ICmpInst::ICMP_ULT, X, LoBound);
907     if (LoOverflow)
908       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
909                           ICmpInst::ICMP_UGE, X, HiBound);
910     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
911                                                     DivIsSigned, false));
912   case ICmpInst::ICMP_ULT:
913   case ICmpInst::ICMP_SLT:
914     if (LoOverflow == +1)   // Low bound is greater than input range.
915       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
916     if (LoOverflow == -1)   // Low bound is less than input range.
917       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
918     return new ICmpInst(Pred, X, LoBound);
919   case ICmpInst::ICMP_UGT:
920   case ICmpInst::ICMP_SGT:
921     if (HiOverflow == +1)       // High bound greater than input range.
922       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
923     if (HiOverflow == -1)       // High bound less than input range.
924       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
925     if (Pred == ICmpInst::ICMP_UGT)
926       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
927     return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
928   }
929 }
930
931 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
932 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
933                                           ConstantInt *ShAmt) {
934   if (!ICI.isEquality()) return 0;
935
936   const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
937   
938   // Check that the shift amount is in range.  If not, don't perform
939   // undefined shifts.  When the shift is visited it will be
940   // simplified.
941   uint32_t TypeBits = CmpRHSV.getBitWidth();
942   uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
943   if (ShAmtVal >= TypeBits)
944     return 0;
945   
946   // If we are comparing against bits always shifted out, the
947   // comparison cannot succeed.
948   APInt Comp = CmpRHSV << ShAmtVal;
949   ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
950   if (Shr->getOpcode() == Instruction::LShr)
951     Comp = Comp.lshr(ShAmtVal);
952   else
953     Comp = Comp.ashr(ShAmtVal);
954   
955   if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
956     bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
957     Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
958                                      IsICMP_NE);
959     return ReplaceInstUsesWith(ICI, Cst);
960   }
961   
962   // Otherwise, check to see if the bits shifted out are known to be zero.
963   // If so, we can compare against the unshifted value:
964   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
965   if (Shr->hasOneUse() && cast<BinaryOperator>(Shr)->isExact())
966     return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
967   
968   if (Shr->hasOneUse()) {
969     // Otherwise strength reduce the shift into an and.
970     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
971     Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
972     
973     Value *And = Builder->CreateAnd(Shr->getOperand(0),
974                                     Mask, Shr->getName()+".mask");
975     return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
976   }
977   return 0;
978 }
979
980
981 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
982 ///
983 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
984                                                           Instruction *LHSI,
985                                                           ConstantInt *RHS) {
986   const APInt &RHSV = RHS->getValue();
987   
988   switch (LHSI->getOpcode()) {
989   case Instruction::Trunc:
990     if (ICI.isEquality() && LHSI->hasOneUse()) {
991       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
992       // of the high bits truncated out of x are known.
993       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
994              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
995       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
996       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
997       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
998       
999       // If all the high bits are known, we can do this xform.
1000       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1001         // Pull in the high bits from known-ones set.
1002         APInt NewRHS = RHS->getValue().zext(SrcBits);
1003         NewRHS |= KnownOne;
1004         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1005                             ConstantInt::get(ICI.getContext(), NewRHS));
1006       }
1007     }
1008     break;
1009       
1010   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
1011     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1012       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1013       // fold the xor.
1014       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1015           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1016         Value *CompareVal = LHSI->getOperand(0);
1017         
1018         // If the sign bit of the XorCST is not set, there is no change to
1019         // the operation, just stop using the Xor.
1020         if (!XorCST->getValue().isNegative()) {
1021           ICI.setOperand(0, CompareVal);
1022           Worklist.Add(LHSI);
1023           return &ICI;
1024         }
1025         
1026         // Was the old condition true if the operand is positive?
1027         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1028         
1029         // If so, the new one isn't.
1030         isTrueIfPositive ^= true;
1031         
1032         if (isTrueIfPositive)
1033           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1034                               SubOne(RHS));
1035         else
1036           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1037                               AddOne(RHS));
1038       }
1039
1040       if (LHSI->hasOneUse()) {
1041         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1042         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1043           const APInt &SignBit = XorCST->getValue();
1044           ICmpInst::Predicate Pred = ICI.isSigned()
1045                                          ? ICI.getUnsignedPredicate()
1046                                          : ICI.getSignedPredicate();
1047           return new ICmpInst(Pred, LHSI->getOperand(0),
1048                               ConstantInt::get(ICI.getContext(),
1049                                                RHSV ^ SignBit));
1050         }
1051
1052         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1053         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
1054           const APInt &NotSignBit = XorCST->getValue();
1055           ICmpInst::Predicate Pred = ICI.isSigned()
1056                                          ? ICI.getUnsignedPredicate()
1057                                          : ICI.getSignedPredicate();
1058           Pred = ICI.getSwappedPredicate(Pred);
1059           return new ICmpInst(Pred, LHSI->getOperand(0),
1060                               ConstantInt::get(ICI.getContext(),
1061                                                RHSV ^ NotSignBit));
1062         }
1063       }
1064     }
1065     break;
1066   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
1067     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1068         LHSI->getOperand(0)->hasOneUse()) {
1069       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1070       
1071       // If the LHS is an AND of a truncating cast, we can widen the
1072       // and/compare to be the input width without changing the value
1073       // produced, eliminating a cast.
1074       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1075         // We can do this transformation if either the AND constant does not
1076         // have its sign bit set or if it is an equality comparison. 
1077         // Extending a relational comparison when we're checking the sign
1078         // bit would not work.
1079         if (Cast->hasOneUse() &&
1080             (ICI.isEquality() ||
1081              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
1082           uint32_t BitWidth = 
1083             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
1084           APInt NewCST = AndCST->getValue().zext(BitWidth);
1085           APInt NewCI = RHSV.zext(BitWidth);
1086           Value *NewAnd = 
1087             Builder->CreateAnd(Cast->getOperand(0),
1088                            ConstantInt::get(ICI.getContext(), NewCST),
1089                                LHSI->getName());
1090           return new ICmpInst(ICI.getPredicate(), NewAnd,
1091                               ConstantInt::get(ICI.getContext(), NewCI));
1092         }
1093       }
1094       
1095       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1096       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1097       // happens a LOT in code produced by the C front-end, for bitfield
1098       // access.
1099       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1100       if (Shift && !Shift->isShift())
1101         Shift = 0;
1102       
1103       ConstantInt *ShAmt;
1104       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1105       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
1106       const Type *AndTy = AndCST->getType();          // Type of the and.
1107       
1108       // We can fold this as long as we can't shift unknown bits
1109       // into the mask.  This can only happen with signed shift
1110       // rights, as they sign-extend.
1111       if (ShAmt) {
1112         bool CanFold = Shift->isLogicalShift();
1113         if (!CanFold) {
1114           // To test for the bad case of the signed shr, see if any
1115           // of the bits shifted in could be tested after the mask.
1116           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1117           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1118           
1119           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1120           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
1121                AndCST->getValue()) == 0)
1122             CanFold = true;
1123         }
1124         
1125         if (CanFold) {
1126           Constant *NewCst;
1127           if (Shift->getOpcode() == Instruction::Shl)
1128             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1129           else
1130             NewCst = ConstantExpr::getShl(RHS, ShAmt);
1131           
1132           // Check to see if we are shifting out any of the bits being
1133           // compared.
1134           if (ConstantExpr::get(Shift->getOpcode(),
1135                                        NewCst, ShAmt) != RHS) {
1136             // If we shifted bits out, the fold is not going to work out.
1137             // As a special case, check to see if this means that the
1138             // result is always true or false now.
1139             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1140               return ReplaceInstUsesWith(ICI,
1141                                        ConstantInt::getFalse(ICI.getContext()));
1142             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1143               return ReplaceInstUsesWith(ICI,
1144                                        ConstantInt::getTrue(ICI.getContext()));
1145           } else {
1146             ICI.setOperand(1, NewCst);
1147             Constant *NewAndCST;
1148             if (Shift->getOpcode() == Instruction::Shl)
1149               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1150             else
1151               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1152             LHSI->setOperand(1, NewAndCST);
1153             LHSI->setOperand(0, Shift->getOperand(0));
1154             Worklist.Add(Shift); // Shift is dead.
1155             return &ICI;
1156           }
1157         }
1158       }
1159       
1160       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1161       // preferable because it allows the C<<Y expression to be hoisted out
1162       // of a loop if Y is invariant and X is not.
1163       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1164           ICI.isEquality() && !Shift->isArithmeticShift() &&
1165           !isa<Constant>(Shift->getOperand(0))) {
1166         // Compute C << Y.
1167         Value *NS;
1168         if (Shift->getOpcode() == Instruction::LShr) {
1169           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
1170         } else {
1171           // Insert a logical shift.
1172           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
1173         }
1174         
1175         // Compute X & (C << Y).
1176         Value *NewAnd = 
1177           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1178         
1179         ICI.setOperand(0, NewAnd);
1180         return &ICI;
1181       }
1182     }
1183       
1184     // Try to optimize things like "A[i]&42 == 0" to index computations.
1185     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1186       if (GetElementPtrInst *GEP =
1187           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1188         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1189           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1190               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1191             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1192             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1193               return Res;
1194           }
1195     }
1196     break;
1197
1198   case Instruction::Or: {
1199     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1200       break;
1201     Value *P, *Q;
1202     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1203       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1204       // -> and (icmp eq P, null), (icmp eq Q, null).
1205       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1206                                         Constant::getNullValue(P->getType()));
1207       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1208                                         Constant::getNullValue(Q->getType()));
1209       Instruction *Op;
1210       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1211         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1212       else
1213         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1214       return Op;
1215     }
1216     break;
1217   }
1218     
1219   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1220     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1221     if (!ShAmt) break;
1222     
1223     uint32_t TypeBits = RHSV.getBitWidth();
1224     
1225     // Check that the shift amount is in range.  If not, don't perform
1226     // undefined shifts.  When the shift is visited it will be
1227     // simplified.
1228     if (ShAmt->uge(TypeBits))
1229       break;
1230     
1231     if (ICI.isEquality()) {
1232       // If we are comparing against bits always shifted out, the
1233       // comparison cannot succeed.
1234       Constant *Comp =
1235         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1236                                                                  ShAmt);
1237       if (Comp != RHS) {// Comparing against a bit that we know is zero.
1238         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1239         Constant *Cst =
1240           ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1241         return ReplaceInstUsesWith(ICI, Cst);
1242       }
1243       
1244       // If the shift is NUW, then it is just shifting out zeros, no need for an
1245       // AND.
1246       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1247         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1248                             ConstantExpr::getLShr(RHS, ShAmt));
1249       
1250       if (LHSI->hasOneUse()) {
1251         // Otherwise strength reduce the shift into an and.
1252         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1253         Constant *Mask =
1254           ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits, 
1255                                                        TypeBits-ShAmtVal));
1256         
1257         Value *And =
1258           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1259         return new ICmpInst(ICI.getPredicate(), And,
1260                             ConstantExpr::getLShr(RHS, ShAmt));
1261       }
1262     }
1263     
1264     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1265     bool TrueIfSigned = false;
1266     if (LHSI->hasOneUse() &&
1267         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1268       // (X << 31) <s 0  --> (X&1) != 0
1269       Constant *Mask = ConstantInt::get(ICI.getContext(), APInt(TypeBits, 1) <<
1270                                            (TypeBits-ShAmt->getZExtValue()-1));
1271       Value *And =
1272         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1273       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1274                           And, Constant::getNullValue(And->getType()));
1275     }
1276     break;
1277   }
1278     
1279   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1280   case Instruction::AShr:
1281     // Only handle equality comparisons of shift-by-constant.
1282     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1283       if (Instruction *Res = FoldICmpShrCst(ICI, cast<BinaryOperator>(LHSI),
1284                                             ShAmt))
1285         return Res;
1286     break;
1287     
1288   case Instruction::SDiv:
1289   case Instruction::UDiv:
1290     // Fold: icmp pred ([us]div X, C1), C2 -> range test
1291     // Fold this div into the comparison, producing a range check. 
1292     // Determine, based on the divide type, what the range is being 
1293     // checked.  If there is an overflow on the low or high side, remember 
1294     // it, otherwise compute the range [low, hi) bounding the new value.
1295     // See: InsertRangeTest above for the kinds of replacements possible.
1296     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1297       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1298                                           DivRHS))
1299         return R;
1300     break;
1301
1302   case Instruction::Add:
1303     // Fold: icmp pred (add X, C1), C2
1304     if (!ICI.isEquality()) {
1305       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1306       if (!LHSC) break;
1307       const APInt &LHSV = LHSC->getValue();
1308
1309       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1310                             .subtract(LHSV);
1311
1312       if (ICI.isSigned()) {
1313         if (CR.getLower().isSignBit()) {
1314           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1315                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1316         } else if (CR.getUpper().isSignBit()) {
1317           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1318                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1319         }
1320       } else {
1321         if (CR.getLower().isMinValue()) {
1322           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1323                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1324         } else if (CR.getUpper().isMinValue()) {
1325           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1326                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1327         }
1328       }
1329     }
1330     break;
1331   }
1332   
1333   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1334   if (ICI.isEquality()) {
1335     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1336     
1337     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
1338     // the second operand is a constant, simplify a bit.
1339     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1340       switch (BO->getOpcode()) {
1341       case Instruction::SRem:
1342         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1343         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1344           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1345           if (V.sgt(1) && V.isPowerOf2()) {
1346             Value *NewRem =
1347               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1348                                   BO->getName());
1349             return new ICmpInst(ICI.getPredicate(), NewRem,
1350                                 Constant::getNullValue(BO->getType()));
1351           }
1352         }
1353         break;
1354       case Instruction::Add:
1355         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1356         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1357           if (BO->hasOneUse())
1358             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1359                                 ConstantExpr::getSub(RHS, BOp1C));
1360         } else if (RHSV == 0) {
1361           // Replace ((add A, B) != 0) with (A != -B) if A or B is
1362           // efficiently invertible, or if the add has just this one use.
1363           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1364           
1365           if (Value *NegVal = dyn_castNegVal(BOp1))
1366             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1367           else if (Value *NegVal = dyn_castNegVal(BOp0))
1368             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1369           else if (BO->hasOneUse()) {
1370             Value *Neg = Builder->CreateNeg(BOp1);
1371             Neg->takeName(BO);
1372             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1373           }
1374         }
1375         break;
1376       case Instruction::Xor:
1377         // For the xor case, we can xor two constants together, eliminating
1378         // the explicit xor.
1379         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1380           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
1381                               ConstantExpr::getXor(RHS, BOC));
1382         
1383         // FALLTHROUGH
1384       case Instruction::Sub:
1385         // Replace (([sub|xor] A, B) != 0) with (A != B)
1386         if (RHSV == 0)
1387           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1388                               BO->getOperand(1));
1389         break;
1390         
1391       case Instruction::Or:
1392         // If bits are being or'd in that are not present in the constant we
1393         // are comparing against, then the comparison could never succeed!
1394         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1395           Constant *NotCI = ConstantExpr::getNot(RHS);
1396           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1397             return ReplaceInstUsesWith(ICI,
1398                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 
1399                                        isICMP_NE));
1400         }
1401         break;
1402         
1403       case Instruction::And:
1404         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1405           // If bits are being compared against that are and'd out, then the
1406           // comparison can never succeed!
1407           if ((RHSV & ~BOC->getValue()) != 0)
1408             return ReplaceInstUsesWith(ICI,
1409                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1410                                        isICMP_NE));
1411           
1412           // If we have ((X & C) == C), turn it into ((X & C) != 0).
1413           if (RHS == BOC && RHSV.isPowerOf2())
1414             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1415                                 ICmpInst::ICMP_NE, LHSI,
1416                                 Constant::getNullValue(RHS->getType()));
1417           
1418           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1419           if (BOC->getValue().isSignBit()) {
1420             Value *X = BO->getOperand(0);
1421             Constant *Zero = Constant::getNullValue(X->getType());
1422             ICmpInst::Predicate pred = isICMP_NE ? 
1423               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1424             return new ICmpInst(pred, X, Zero);
1425           }
1426           
1427           // ((X & ~7) == 0) --> X < 8
1428           if (RHSV == 0 && isHighOnes(BOC)) {
1429             Value *X = BO->getOperand(0);
1430             Constant *NegX = ConstantExpr::getNeg(BOC);
1431             ICmpInst::Predicate pred = isICMP_NE ? 
1432               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1433             return new ICmpInst(pred, X, NegX);
1434           }
1435         }
1436       default: break;
1437       }
1438     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1439       // Handle icmp {eq|ne} <intrinsic>, intcst.
1440       switch (II->getIntrinsicID()) {
1441       case Intrinsic::bswap:
1442         Worklist.Add(II);
1443         ICI.setOperand(0, II->getArgOperand(0));
1444         ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1445         return &ICI;
1446       case Intrinsic::ctlz:
1447       case Intrinsic::cttz:
1448         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1449         if (RHSV == RHS->getType()->getBitWidth()) {
1450           Worklist.Add(II);
1451           ICI.setOperand(0, II->getArgOperand(0));
1452           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1453           return &ICI;
1454         }
1455         break;
1456       case Intrinsic::ctpop:
1457         // popcount(A) == 0  ->  A == 0 and likewise for !=
1458         if (RHS->isZero()) {
1459           Worklist.Add(II);
1460           ICI.setOperand(0, II->getArgOperand(0));
1461           ICI.setOperand(1, RHS);
1462           return &ICI;
1463         }
1464         break;
1465       default:
1466         break;
1467       }
1468     }
1469   }
1470   return 0;
1471 }
1472
1473 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1474 /// We only handle extending casts so far.
1475 ///
1476 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1477   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1478   Value *LHSCIOp        = LHSCI->getOperand(0);
1479   const Type *SrcTy     = LHSCIOp->getType();
1480   const Type *DestTy    = LHSCI->getType();
1481   Value *RHSCIOp;
1482
1483   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
1484   // integer type is the same size as the pointer type.
1485   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1486       TD->getPointerSizeInBits() ==
1487          cast<IntegerType>(DestTy)->getBitWidth()) {
1488     Value *RHSOp = 0;
1489     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1490       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1491     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1492       RHSOp = RHSC->getOperand(0);
1493       // If the pointer types don't match, insert a bitcast.
1494       if (LHSCIOp->getType() != RHSOp->getType())
1495         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1496     }
1497
1498     if (RHSOp)
1499       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1500   }
1501   
1502   // The code below only handles extension cast instructions, so far.
1503   // Enforce this.
1504   if (LHSCI->getOpcode() != Instruction::ZExt &&
1505       LHSCI->getOpcode() != Instruction::SExt)
1506     return 0;
1507
1508   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1509   bool isSignedCmp = ICI.isSigned();
1510
1511   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1512     // Not an extension from the same type?
1513     RHSCIOp = CI->getOperand(0);
1514     if (RHSCIOp->getType() != LHSCIOp->getType()) 
1515       return 0;
1516     
1517     // If the signedness of the two casts doesn't agree (i.e. one is a sext
1518     // and the other is a zext), then we can't handle this.
1519     if (CI->getOpcode() != LHSCI->getOpcode())
1520       return 0;
1521
1522     // Deal with equality cases early.
1523     if (ICI.isEquality())
1524       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1525
1526     // A signed comparison of sign extended values simplifies into a
1527     // signed comparison.
1528     if (isSignedCmp && isSignedExt)
1529       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1530
1531     // The other three cases all fold into an unsigned comparison.
1532     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1533   }
1534
1535   // If we aren't dealing with a constant on the RHS, exit early
1536   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1537   if (!CI)
1538     return 0;
1539
1540   // Compute the constant that would happen if we truncated to SrcTy then
1541   // reextended to DestTy.
1542   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1543   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1544                                                 Res1, DestTy);
1545
1546   // If the re-extended constant didn't change...
1547   if (Res2 == CI) {
1548     // Deal with equality cases early.
1549     if (ICI.isEquality())
1550       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1551
1552     // A signed comparison of sign extended values simplifies into a
1553     // signed comparison.
1554     if (isSignedExt && isSignedCmp)
1555       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1556
1557     // The other three cases all fold into an unsigned comparison.
1558     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1559   }
1560
1561   // The re-extended constant changed so the constant cannot be represented 
1562   // in the shorter type. Consequently, we cannot emit a simple comparison.
1563   // All the cases that fold to true or false will have already been handled
1564   // by SimplifyICmpInst, so only deal with the tricky case.
1565
1566   if (isSignedCmp || !isSignedExt)
1567     return 0;
1568
1569   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1570   // should have been folded away previously and not enter in here.
1571
1572   // We're performing an unsigned comp with a sign extended value.
1573   // This is true if the input is >= 0. [aka >s -1]
1574   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1575   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1576
1577   // Finally, return the value computed.
1578   if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1579     return ReplaceInstUsesWith(ICI, Result);
1580
1581   assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1582   return BinaryOperator::CreateNot(Result);
1583 }
1584
1585 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1586 ///   I = icmp ugt (add (add A, B), CI2), CI1
1587 /// If this is of the form:
1588 ///   sum = a + b
1589 ///   if (sum+128 >u 255)
1590 /// Then replace it with llvm.sadd.with.overflow.i8.
1591 ///
1592 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1593                                           ConstantInt *CI2, ConstantInt *CI1,
1594                                           InstCombiner &IC) {
1595   // The transformation we're trying to do here is to transform this into an
1596   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1597   // with a narrower add, and discard the add-with-constant that is part of the
1598   // range check (if we can't eliminate it, this isn't profitable).
1599   
1600   // In order to eliminate the add-with-constant, the compare can be its only
1601   // use.
1602   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1603   if (!AddWithCst->hasOneUse()) return 0;
1604   
1605   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1606   if (!CI2->getValue().isPowerOf2()) return 0;
1607   unsigned NewWidth = CI2->getValue().countTrailingZeros();
1608   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1609     
1610   // The width of the new add formed is 1 more than the bias.
1611   ++NewWidth;
1612   
1613   // Check to see that CI1 is an all-ones value with NewWidth bits.
1614   if (CI1->getBitWidth() == NewWidth ||
1615       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1616     return 0;
1617   
1618   // In order to replace the original add with a narrower 
1619   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1620   // and truncates that discard the high bits of the add.  Verify that this is
1621   // the case.
1622   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1623   for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1624        UI != E; ++UI) {
1625     if (*UI == AddWithCst) continue;
1626     
1627     // Only accept truncates for now.  We would really like a nice recursive
1628     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1629     // chain to see which bits of a value are actually demanded.  If the
1630     // original add had another add which was then immediately truncated, we
1631     // could still do the transformation.
1632     TruncInst *TI = dyn_cast<TruncInst>(*UI);
1633     if (TI == 0 ||
1634         TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1635   }
1636   
1637   // If the pattern matches, truncate the inputs to the narrower type and
1638   // use the sadd_with_overflow intrinsic to efficiently compute both the
1639   // result and the overflow bit.
1640   Module *M = I.getParent()->getParent()->getParent();
1641   
1642   const Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1643   Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1644                                        &NewType, 1);
1645
1646   InstCombiner::BuilderTy *Builder = IC.Builder;
1647   
1648   // Put the new code above the original add, in case there are any uses of the
1649   // add between the add and the compare.
1650   Builder->SetInsertPoint(OrigAdd);
1651   
1652   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1653   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1654   CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1655   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1656   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1657   
1658   // The inner add was the result of the narrow add, zero extended to the
1659   // wider type.  Replace it with the result computed by the intrinsic.
1660   IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1661   
1662   // The original icmp gets replaced with the overflow value.
1663   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1664 }
1665
1666 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1667                                      InstCombiner &IC) {
1668   // Don't bother doing this transformation for pointers, don't do it for
1669   // vectors.
1670   if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1671   
1672   // If the add is a constant expr, then we don't bother transforming it.
1673   Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1674   if (OrigAdd == 0) return 0;
1675   
1676   Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1677   
1678   // Put the new code above the original add, in case there are any uses of the
1679   // add between the add and the compare.
1680   InstCombiner::BuilderTy *Builder = IC.Builder;
1681   Builder->SetInsertPoint(OrigAdd);
1682
1683   Module *M = I.getParent()->getParent()->getParent();
1684   const Type *Ty = LHS->getType();
1685   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, &Ty,1);
1686   CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1687   Value *Add = Builder->CreateExtractValue(Call, 0);
1688
1689   IC.ReplaceInstUsesWith(*OrigAdd, Add);
1690
1691   // The original icmp gets replaced with the overflow value.
1692   return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1693 }
1694
1695 // DemandedBitsLHSMask - When performing a comparison against a constant,
1696 // it is possible that not all the bits in the LHS are demanded.  This helper
1697 // method computes the mask that IS demanded.
1698 static APInt DemandedBitsLHSMask(ICmpInst &I,
1699                                  unsigned BitWidth, bool isSignCheck) {
1700   if (isSignCheck)
1701     return APInt::getSignBit(BitWidth);
1702   
1703   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1704   if (!CI) return APInt::getAllOnesValue(BitWidth);
1705   const APInt &RHS = CI->getValue();
1706   
1707   switch (I.getPredicate()) {
1708   // For a UGT comparison, we don't care about any bits that 
1709   // correspond to the trailing ones of the comparand.  The value of these
1710   // bits doesn't impact the outcome of the comparison, because any value
1711   // greater than the RHS must differ in a bit higher than these due to carry.
1712   case ICmpInst::ICMP_UGT: {
1713     unsigned trailingOnes = RHS.countTrailingOnes();
1714     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1715     return ~lowBitsSet;
1716   }
1717   
1718   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1719   // Any value less than the RHS must differ in a higher bit because of carries.
1720   case ICmpInst::ICMP_ULT: {
1721     unsigned trailingZeros = RHS.countTrailingZeros();
1722     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1723     return ~lowBitsSet;
1724   }
1725   
1726   default:
1727     return APInt::getAllOnesValue(BitWidth);
1728   }
1729   
1730 }
1731
1732 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1733   bool Changed = false;
1734   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1735   
1736   /// Orders the operands of the compare so that they are listed from most
1737   /// complex to least complex.  This puts constants before unary operators,
1738   /// before binary operators.
1739   if (getComplexity(Op0) < getComplexity(Op1)) {
1740     I.swapOperands();
1741     std::swap(Op0, Op1);
1742     Changed = true;
1743   }
1744   
1745   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1746     return ReplaceInstUsesWith(I, V);
1747   
1748   const Type *Ty = Op0->getType();
1749
1750   // icmp's with boolean values can always be turned into bitwise operations
1751   if (Ty->isIntegerTy(1)) {
1752     switch (I.getPredicate()) {
1753     default: llvm_unreachable("Invalid icmp instruction!");
1754     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
1755       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1756       return BinaryOperator::CreateNot(Xor);
1757     }
1758     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
1759       return BinaryOperator::CreateXor(Op0, Op1);
1760
1761     case ICmpInst::ICMP_UGT:
1762       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
1763       // FALL THROUGH
1764     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
1765       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1766       return BinaryOperator::CreateAnd(Not, Op1);
1767     }
1768     case ICmpInst::ICMP_SGT:
1769       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
1770       // FALL THROUGH
1771     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
1772       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1773       return BinaryOperator::CreateAnd(Not, Op0);
1774     }
1775     case ICmpInst::ICMP_UGE:
1776       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
1777       // FALL THROUGH
1778     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
1779       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1780       return BinaryOperator::CreateOr(Not, Op1);
1781     }
1782     case ICmpInst::ICMP_SGE:
1783       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
1784       // FALL THROUGH
1785     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
1786       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1787       return BinaryOperator::CreateOr(Not, Op0);
1788     }
1789     }
1790   }
1791
1792   unsigned BitWidth = 0;
1793   if (Ty->isIntOrIntVectorTy())
1794     BitWidth = Ty->getScalarSizeInBits();
1795   else if (TD)  // Pointers require TD info to get their size.
1796     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
1797   
1798   bool isSignBit = false;
1799
1800   // See if we are doing a comparison with a constant.
1801   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1802     Value *A = 0, *B = 0;
1803     
1804     // Match the following pattern, which is a common idiom when writing
1805     // overflow-safe integer arithmetic function.  The source performs an
1806     // addition in wider type, and explicitly checks for overflow using
1807     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
1808     // sadd_with_overflow intrinsic.
1809     //
1810     // TODO: This could probably be generalized to handle other overflow-safe
1811     // operations if we worked out the formulas to compute the appropriate 
1812     // magic constants.
1813     // 
1814     // sum = a + b
1815     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
1816     {
1817     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
1818     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
1819         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1820       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
1821         return Res;
1822     }
1823     
1824     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1825     if (I.isEquality() && CI->isZero() &&
1826         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1827       // (icmp cond A B) if cond is equality
1828       return new ICmpInst(I.getPredicate(), A, B);
1829     }
1830     
1831     // If we have an icmp le or icmp ge instruction, turn it into the
1832     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
1833     // them being folded in the code below.  The SimplifyICmpInst code has
1834     // already handled the edge cases for us, so we just assert on them.
1835     switch (I.getPredicate()) {
1836     default: break;
1837     case ICmpInst::ICMP_ULE:
1838       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
1839       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1840                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1841     case ICmpInst::ICMP_SLE:
1842       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
1843       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1844                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1845     case ICmpInst::ICMP_UGE:
1846       assert(!CI->isMinValue(false));                  // A >=u MIN -> TRUE
1847       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1848                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1849     case ICmpInst::ICMP_SGE:
1850       assert(!CI->isMinValue(true));                   // A >=s MIN -> TRUE
1851       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1852                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1853     }
1854     
1855     // If this comparison is a normal comparison, it demands all
1856     // bits, if it is a sign bit comparison, it only demands the sign bit.
1857     bool UnusedBit;
1858     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1859   }
1860
1861   // See if we can fold the comparison based on range information we can get
1862   // by checking whether bits are known to be zero or one in the input.
1863   if (BitWidth != 0) {
1864     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1865     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1866
1867     if (SimplifyDemandedBits(I.getOperandUse(0),
1868                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
1869                              Op0KnownZero, Op0KnownOne, 0))
1870       return &I;
1871     if (SimplifyDemandedBits(I.getOperandUse(1),
1872                              APInt::getAllOnesValue(BitWidth),
1873                              Op1KnownZero, Op1KnownOne, 0))
1874       return &I;
1875
1876     // Given the known and unknown bits, compute a range that the LHS could be
1877     // in.  Compute the Min, Max and RHS values based on the known bits. For the
1878     // EQ and NE we use unsigned values.
1879     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1880     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1881     if (I.isSigned()) {
1882       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1883                                              Op0Min, Op0Max);
1884       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1885                                              Op1Min, Op1Max);
1886     } else {
1887       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1888                                                Op0Min, Op0Max);
1889       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1890                                                Op1Min, Op1Max);
1891     }
1892
1893     // If Min and Max are known to be the same, then SimplifyDemandedBits
1894     // figured out that the LHS is a constant.  Just constant fold this now so
1895     // that code below can assume that Min != Max.
1896     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1897       return new ICmpInst(I.getPredicate(),
1898                           ConstantInt::get(I.getContext(), Op0Min), Op1);
1899     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1900       return new ICmpInst(I.getPredicate(), Op0,
1901                           ConstantInt::get(I.getContext(), Op1Min));
1902
1903     // Based on the range information we know about the LHS, see if we can
1904     // simplify this comparison.  For example, (x&4) < 8  is always true.
1905     switch (I.getPredicate()) {
1906     default: llvm_unreachable("Unknown icmp opcode!");
1907     case ICmpInst::ICMP_EQ: {
1908       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1909         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1910         
1911       // If all bits are known zero except for one, then we know at most one
1912       // bit is set.   If the comparison is against zero, then this is a check
1913       // to see if *that* bit is set.
1914       APInt Op0KnownZeroInverted = ~Op0KnownZero;
1915       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1916         // If the LHS is an AND with the same constant, look through it.
1917         Value *LHS = 0;
1918         ConstantInt *LHSC = 0;
1919         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1920             LHSC->getValue() != Op0KnownZeroInverted)
1921           LHS = Op0;
1922         
1923         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
1924         // then turn "((1 << x)&8) == 0" into "x != 3".
1925         Value *X = 0;
1926         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1927           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
1928           return new ICmpInst(ICmpInst::ICMP_NE, X,
1929                               ConstantInt::get(X->getType(), CmpVal));
1930         }
1931         
1932         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
1933         // then turn "((8 >>u x)&1) == 0" into "x != 3".
1934         const APInt *CI;
1935         if (Op0KnownZeroInverted == 1 &&
1936             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
1937           return new ICmpInst(ICmpInst::ICMP_NE, X,
1938                               ConstantInt::get(X->getType(),
1939                                                CI->countTrailingZeros()));
1940       }
1941         
1942       break;
1943     }
1944     case ICmpInst::ICMP_NE: {
1945       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1946         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1947       
1948       // If all bits are known zero except for one, then we know at most one
1949       // bit is set.   If the comparison is against zero, then this is a check
1950       // to see if *that* bit is set.
1951       APInt Op0KnownZeroInverted = ~Op0KnownZero;
1952       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1953         // If the LHS is an AND with the same constant, look through it.
1954         Value *LHS = 0;
1955         ConstantInt *LHSC = 0;
1956         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1957             LHSC->getValue() != Op0KnownZeroInverted)
1958           LHS = Op0;
1959         
1960         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
1961         // then turn "((1 << x)&8) != 0" into "x == 3".
1962         Value *X = 0;
1963         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1964           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
1965           return new ICmpInst(ICmpInst::ICMP_EQ, X,
1966                               ConstantInt::get(X->getType(), CmpVal));
1967         }
1968         
1969         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
1970         // then turn "((8 >>u x)&1) != 0" into "x == 3".
1971         const APInt *CI;
1972         if (Op0KnownZeroInverted == 1 &&
1973             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
1974           return new ICmpInst(ICmpInst::ICMP_EQ, X,
1975                               ConstantInt::get(X->getType(),
1976                                                CI->countTrailingZeros()));
1977       }
1978       
1979       break;
1980     }
1981     case ICmpInst::ICMP_ULT:
1982       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
1983         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1984       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
1985         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1986       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
1987         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
1988       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1989         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
1990           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
1991                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1992
1993         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
1994         if (CI->isMinValue(true))
1995           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1996                            Constant::getAllOnesValue(Op0->getType()));
1997       }
1998       break;
1999     case ICmpInst::ICMP_UGT:
2000       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2001         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2002       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2003         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2004
2005       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2006         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2007       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2008         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2009           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2010                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2011
2012         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2013         if (CI->isMaxValue(true))
2014           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2015                               Constant::getNullValue(Op0->getType()));
2016       }
2017       break;
2018     case ICmpInst::ICMP_SLT:
2019       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2020         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2021       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2022         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2023       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2024         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2025       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2026         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2027           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2028                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
2029       }
2030       break;
2031     case ICmpInst::ICMP_SGT:
2032       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2033         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2034       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2035         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2036
2037       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2038         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2039       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2040         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2041           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2042                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2043       }
2044       break;
2045     case ICmpInst::ICMP_SGE:
2046       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2047       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2048         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2049       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2050         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2051       break;
2052     case ICmpInst::ICMP_SLE:
2053       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2054       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2055         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2056       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2057         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2058       break;
2059     case ICmpInst::ICMP_UGE:
2060       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2061       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2062         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2063       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2064         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2065       break;
2066     case ICmpInst::ICMP_ULE:
2067       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2068       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2069         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2070       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2071         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2072       break;
2073     }
2074
2075     // Turn a signed comparison into an unsigned one if both operands
2076     // are known to have the same sign.
2077     if (I.isSigned() &&
2078         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2079          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2080       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2081   }
2082
2083   // Test if the ICmpInst instruction is used exclusively by a select as
2084   // part of a minimum or maximum operation. If so, refrain from doing
2085   // any other folding. This helps out other analyses which understand
2086   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2087   // and CodeGen. And in this case, at least one of the comparison
2088   // operands has at least one user besides the compare (the select),
2089   // which would often largely negate the benefit of folding anyway.
2090   if (I.hasOneUse())
2091     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2092       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2093           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2094         return 0;
2095
2096   // See if we are doing a comparison between a constant and an instruction that
2097   // can be folded into the comparison.
2098   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2099     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
2100     // instruction, see if that instruction also has constants so that the 
2101     // instruction can be folded into the icmp 
2102     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2103       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2104         return Res;
2105   }
2106
2107   // Handle icmp with constant (but not simple integer constant) RHS
2108   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2109     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2110       switch (LHSI->getOpcode()) {
2111       case Instruction::GetElementPtr:
2112           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2113         if (RHSC->isNullValue() &&
2114             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2115           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2116                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
2117         break;
2118       case Instruction::PHI:
2119         // Only fold icmp into the PHI if the phi and icmp are in the same
2120         // block.  If in the same block, we're encouraging jump threading.  If
2121         // not, we are just pessimizing the code by making an i1 phi.
2122         if (LHSI->getParent() == I.getParent())
2123           if (Instruction *NV = FoldOpIntoPhi(I))
2124             return NV;
2125         break;
2126       case Instruction::Select: {
2127         // If either operand of the select is a constant, we can fold the
2128         // comparison into the select arms, which will cause one to be
2129         // constant folded and the select turned into a bitwise or.
2130         Value *Op1 = 0, *Op2 = 0;
2131         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2132           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2133         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2134           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2135
2136         // We only want to perform this transformation if it will not lead to
2137         // additional code. This is true if either both sides of the select
2138         // fold to a constant (in which case the icmp is replaced with a select
2139         // which will usually simplify) or this is the only user of the
2140         // select (in which case we are trading a select+icmp for a simpler
2141         // select+icmp).
2142         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2143           if (!Op1)
2144             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2145                                       RHSC, I.getName());
2146           if (!Op2)
2147             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2148                                       RHSC, I.getName());
2149           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2150         }
2151         break;
2152       }
2153       case Instruction::IntToPtr:
2154         // icmp pred inttoptr(X), null -> icmp pred X, 0
2155         if (RHSC->isNullValue() && TD &&
2156             TD->getIntPtrType(RHSC->getContext()) == 
2157                LHSI->getOperand(0)->getType())
2158           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2159                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
2160         break;
2161
2162       case Instruction::Load:
2163         // Try to optimize things like "A[i] > 4" to index computations.
2164         if (GetElementPtrInst *GEP =
2165               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2166           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2167             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2168                 !cast<LoadInst>(LHSI)->isVolatile())
2169               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2170                 return Res;
2171         }
2172         break;
2173       }
2174   }
2175
2176   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2177   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2178     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2179       return NI;
2180   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2181     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2182                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2183       return NI;
2184
2185   // Test to see if the operands of the icmp are casted versions of other
2186   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2187   // now.
2188   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2189     if (Op0->getType()->isPointerTy() && 
2190         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
2191       // We keep moving the cast from the left operand over to the right
2192       // operand, where it can often be eliminated completely.
2193       Op0 = CI->getOperand(0);
2194
2195       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2196       // so eliminate it as well.
2197       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2198         Op1 = CI2->getOperand(0);
2199
2200       // If Op1 is a constant, we can fold the cast into the constant.
2201       if (Op0->getType() != Op1->getType()) {
2202         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2203           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2204         } else {
2205           // Otherwise, cast the RHS right before the icmp
2206           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2207         }
2208       }
2209       return new ICmpInst(I.getPredicate(), Op0, Op1);
2210     }
2211   }
2212   
2213   if (isa<CastInst>(Op0)) {
2214     // Handle the special case of: icmp (cast bool to X), <cst>
2215     // This comes up when you have code like
2216     //   int X = A < B;
2217     //   if (X) ...
2218     // For generality, we handle any zero-extension of any operand comparison
2219     // with a constant or another cast from the same type.
2220     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2221       if (Instruction *R = visitICmpInstWithCastAndCast(I))
2222         return R;
2223   }
2224   
2225   // See if it's the same type of instruction on the left and right.
2226   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2227     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2228       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
2229           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
2230         switch (Op0I->getOpcode()) {
2231         default: break;
2232         case Instruction::Add:
2233         case Instruction::Sub:
2234         case Instruction::Xor:
2235           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2236             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
2237                                 Op1I->getOperand(0));
2238           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2239           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2240             if (CI->getValue().isSignBit()) {
2241               ICmpInst::Predicate Pred = I.isSigned()
2242                                              ? I.getUnsignedPredicate()
2243                                              : I.getSignedPredicate();
2244               return new ICmpInst(Pred, Op0I->getOperand(0),
2245                                   Op1I->getOperand(0));
2246             }
2247             
2248             if (CI->getValue().isMaxSignedValue()) {
2249               ICmpInst::Predicate Pred = I.isSigned()
2250                                              ? I.getUnsignedPredicate()
2251                                              : I.getSignedPredicate();
2252               Pred = I.getSwappedPredicate(Pred);
2253               return new ICmpInst(Pred, Op0I->getOperand(0),
2254                                   Op1I->getOperand(0));
2255             }
2256           }
2257           break;
2258         case Instruction::Mul:
2259           if (!I.isEquality())
2260             break;
2261
2262           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2263             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2264             // Mask = -1 >> count-trailing-zeros(Cst).
2265             if (!CI->isZero() && !CI->isOne()) {
2266               const APInt &AP = CI->getValue();
2267               ConstantInt *Mask = ConstantInt::get(I.getContext(), 
2268                                       APInt::getLowBitsSet(AP.getBitWidth(),
2269                                                            AP.getBitWidth() -
2270                                                       AP.countTrailingZeros()));
2271               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
2272               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
2273               return new ICmpInst(I.getPredicate(), And1, And2);
2274             }
2275           }
2276           break;
2277         }
2278       }
2279     }
2280   }
2281   
2282   { Value *A, *B;
2283     // ~x < ~y --> y < x
2284     // ~x < cst --> ~cst < x
2285     if (match(Op0, m_Not(m_Value(A)))) {
2286       if (match(Op1, m_Not(m_Value(B))))
2287         return new ICmpInst(I.getPredicate(), B, A);
2288       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2289         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2290     }
2291
2292     // (a+b) <u a  --> llvm.uadd.with.overflow.
2293     // (a+b) <u b  --> llvm.uadd.with.overflow.
2294     if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2295         match(Op0, m_Add(m_Value(A), m_Value(B))) && 
2296         (Op1 == A || Op1 == B))
2297       if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2298         return R;
2299                                  
2300     // a >u (a+b)  --> llvm.uadd.with.overflow.
2301     // b >u (a+b)  --> llvm.uadd.with.overflow.
2302     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2303         match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2304         (Op0 == A || Op0 == B))
2305       if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2306         return R;
2307   }
2308   
2309   if (I.isEquality()) {
2310     Value *A, *B, *C, *D;
2311     
2312     // -x == -y --> x == y
2313     if (match(Op0, m_Neg(m_Value(A))) &&
2314         match(Op1, m_Neg(m_Value(B))))
2315       return new ICmpInst(I.getPredicate(), A, B);
2316     
2317     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2318       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2319         Value *OtherVal = A == Op1 ? B : A;
2320         return new ICmpInst(I.getPredicate(), OtherVal,
2321                             Constant::getNullValue(A->getType()));
2322       }
2323
2324       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2325         // A^c1 == C^c2 --> A == C^(c1^c2)
2326         ConstantInt *C1, *C2;
2327         if (match(B, m_ConstantInt(C1)) &&
2328             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2329           Constant *NC = ConstantInt::get(I.getContext(),
2330                                           C1->getValue() ^ C2->getValue());
2331           Value *Xor = Builder->CreateXor(C, NC, "tmp");
2332           return new ICmpInst(I.getPredicate(), A, Xor);
2333         }
2334         
2335         // A^B == A^D -> B == D
2336         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2337         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2338         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2339         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2340       }
2341     }
2342     
2343     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2344         (A == Op0 || B == Op0)) {
2345       // A == (A^B)  ->  B == 0
2346       Value *OtherVal = A == Op0 ? B : A;
2347       return new ICmpInst(I.getPredicate(), OtherVal,
2348                           Constant::getNullValue(A->getType()));
2349     }
2350
2351     // (A-B) == A  ->  B == 0
2352     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
2353       return new ICmpInst(I.getPredicate(), B, 
2354                           Constant::getNullValue(B->getType()));
2355
2356     // A == (A-B)  ->  B == 0
2357     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
2358       return new ICmpInst(I.getPredicate(), B,
2359                           Constant::getNullValue(B->getType()));
2360
2361     // (A+B) == A  ->  B == 0
2362     if (match(Op0, m_Add(m_Specific(Op1), m_Value(B))) ||
2363         match(Op0, m_Add(m_Value(B), m_Specific(Op1))))
2364       return new ICmpInst(I.getPredicate(), B,
2365                           Constant::getNullValue(B->getType()));
2366
2367     // A == (A+B)  ->  B == 0
2368     if (match(Op1, m_Add(m_Specific(Op0), m_Value(B))) ||
2369         match(Op1, m_Add(m_Value(B), m_Specific(Op0))))
2370       return new ICmpInst(I.getPredicate(), B,
2371                           Constant::getNullValue(B->getType()));
2372
2373     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2374     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2375         match(Op0, m_And(m_Value(A), m_Value(B))) && 
2376         match(Op1, m_And(m_Value(C), m_Value(D)))) {
2377       Value *X = 0, *Y = 0, *Z = 0;
2378       
2379       if (A == C) {
2380         X = B; Y = D; Z = A;
2381       } else if (A == D) {
2382         X = B; Y = C; Z = A;
2383       } else if (B == C) {
2384         X = A; Y = D; Z = B;
2385       } else if (B == D) {
2386         X = A; Y = C; Z = B;
2387       }
2388       
2389       if (X) {   // Build (X^Y) & Z
2390         Op1 = Builder->CreateXor(X, Y, "tmp");
2391         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
2392         I.setOperand(0, Op1);
2393         I.setOperand(1, Constant::getNullValue(Op1->getType()));
2394         return &I;
2395       }
2396     }
2397   }
2398   
2399   {
2400     Value *X; ConstantInt *Cst;
2401     // icmp X+Cst, X
2402     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2403       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2404
2405     // icmp X, X+Cst
2406     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2407       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2408   }
2409   return Changed ? &I : 0;
2410 }
2411
2412
2413
2414
2415
2416
2417 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2418 ///
2419 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2420                                                 Instruction *LHSI,
2421                                                 Constant *RHSC) {
2422   if (!isa<ConstantFP>(RHSC)) return 0;
2423   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2424   
2425   // Get the width of the mantissa.  We don't want to hack on conversions that
2426   // might lose information from the integer, e.g. "i64 -> float"
2427   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2428   if (MantissaWidth == -1) return 0;  // Unknown.
2429   
2430   // Check to see that the input is converted from an integer type that is small
2431   // enough that preserves all bits.  TODO: check here for "known" sign bits.
2432   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2433   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2434   
2435   // If this is a uitofp instruction, we need an extra bit to hold the sign.
2436   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2437   if (LHSUnsigned)
2438     ++InputSize;
2439   
2440   // If the conversion would lose info, don't hack on this.
2441   if ((int)InputSize > MantissaWidth)
2442     return 0;
2443   
2444   // Otherwise, we can potentially simplify the comparison.  We know that it
2445   // will always come through as an integer value and we know the constant is
2446   // not a NAN (it would have been previously simplified).
2447   assert(!RHS.isNaN() && "NaN comparison not already folded!");
2448   
2449   ICmpInst::Predicate Pred;
2450   switch (I.getPredicate()) {
2451   default: llvm_unreachable("Unexpected predicate!");
2452   case FCmpInst::FCMP_UEQ:
2453   case FCmpInst::FCMP_OEQ:
2454     Pred = ICmpInst::ICMP_EQ;
2455     break;
2456   case FCmpInst::FCMP_UGT:
2457   case FCmpInst::FCMP_OGT:
2458     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2459     break;
2460   case FCmpInst::FCMP_UGE:
2461   case FCmpInst::FCMP_OGE:
2462     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2463     break;
2464   case FCmpInst::FCMP_ULT:
2465   case FCmpInst::FCMP_OLT:
2466     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2467     break;
2468   case FCmpInst::FCMP_ULE:
2469   case FCmpInst::FCMP_OLE:
2470     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2471     break;
2472   case FCmpInst::FCMP_UNE:
2473   case FCmpInst::FCMP_ONE:
2474     Pred = ICmpInst::ICMP_NE;
2475     break;
2476   case FCmpInst::FCMP_ORD:
2477     return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2478   case FCmpInst::FCMP_UNO:
2479     return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2480   }
2481   
2482   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2483   
2484   // Now we know that the APFloat is a normal number, zero or inf.
2485   
2486   // See if the FP constant is too large for the integer.  For example,
2487   // comparing an i8 to 300.0.
2488   unsigned IntWidth = IntTy->getScalarSizeInBits();
2489   
2490   if (!LHSUnsigned) {
2491     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
2492     // and large values.
2493     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2494     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2495                           APFloat::rmNearestTiesToEven);
2496     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
2497       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
2498           Pred == ICmpInst::ICMP_SLE)
2499         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2500       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2501     }
2502   } else {
2503     // If the RHS value is > UnsignedMax, fold the comparison. This handles
2504     // +INF and large values.
2505     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2506     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2507                           APFloat::rmNearestTiesToEven);
2508     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
2509       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
2510           Pred == ICmpInst::ICMP_ULE)
2511         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2512       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2513     }
2514   }
2515   
2516   if (!LHSUnsigned) {
2517     // See if the RHS value is < SignedMin.
2518     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2519     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2520                           APFloat::rmNearestTiesToEven);
2521     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2522       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2523           Pred == ICmpInst::ICMP_SGE)
2524         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2525       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2526     }
2527   }
2528
2529   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2530   // [0, UMAX], but it may still be fractional.  See if it is fractional by
2531   // casting the FP value to the integer value and back, checking for equality.
2532   // Don't do this for zero, because -0.0 is not fractional.
2533   Constant *RHSInt = LHSUnsigned
2534     ? ConstantExpr::getFPToUI(RHSC, IntTy)
2535     : ConstantExpr::getFPToSI(RHSC, IntTy);
2536   if (!RHS.isZero()) {
2537     bool Equal = LHSUnsigned
2538       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2539       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2540     if (!Equal) {
2541       // If we had a comparison against a fractional value, we have to adjust
2542       // the compare predicate and sometimes the value.  RHSC is rounded towards
2543       // zero at this point.
2544       switch (Pred) {
2545       default: llvm_unreachable("Unexpected integer comparison!");
2546       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
2547         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2548       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
2549         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2550       case ICmpInst::ICMP_ULE:
2551         // (float)int <= 4.4   --> int <= 4
2552         // (float)int <= -4.4  --> false
2553         if (RHS.isNegative())
2554           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2555         break;
2556       case ICmpInst::ICMP_SLE:
2557         // (float)int <= 4.4   --> int <= 4
2558         // (float)int <= -4.4  --> int < -4
2559         if (RHS.isNegative())
2560           Pred = ICmpInst::ICMP_SLT;
2561         break;
2562       case ICmpInst::ICMP_ULT:
2563         // (float)int < -4.4   --> false
2564         // (float)int < 4.4    --> int <= 4
2565         if (RHS.isNegative())
2566           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2567         Pred = ICmpInst::ICMP_ULE;
2568         break;
2569       case ICmpInst::ICMP_SLT:
2570         // (float)int < -4.4   --> int < -4
2571         // (float)int < 4.4    --> int <= 4
2572         if (!RHS.isNegative())
2573           Pred = ICmpInst::ICMP_SLE;
2574         break;
2575       case ICmpInst::ICMP_UGT:
2576         // (float)int > 4.4    --> int > 4
2577         // (float)int > -4.4   --> true
2578         if (RHS.isNegative())
2579           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2580         break;
2581       case ICmpInst::ICMP_SGT:
2582         // (float)int > 4.4    --> int > 4
2583         // (float)int > -4.4   --> int >= -4
2584         if (RHS.isNegative())
2585           Pred = ICmpInst::ICMP_SGE;
2586         break;
2587       case ICmpInst::ICMP_UGE:
2588         // (float)int >= -4.4   --> true
2589         // (float)int >= 4.4    --> int > 4
2590         if (!RHS.isNegative())
2591           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2592         Pred = ICmpInst::ICMP_UGT;
2593         break;
2594       case ICmpInst::ICMP_SGE:
2595         // (float)int >= -4.4   --> int >= -4
2596         // (float)int >= 4.4    --> int > 4
2597         if (!RHS.isNegative())
2598           Pred = ICmpInst::ICMP_SGT;
2599         break;
2600       }
2601     }
2602   }
2603
2604   // Lower this FP comparison into an appropriate integer version of the
2605   // comparison.
2606   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2607 }
2608
2609 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2610   bool Changed = false;
2611   
2612   /// Orders the operands of the compare so that they are listed from most
2613   /// complex to least complex.  This puts constants before unary operators,
2614   /// before binary operators.
2615   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2616     I.swapOperands();
2617     Changed = true;
2618   }
2619
2620   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621   
2622   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2623     return ReplaceInstUsesWith(I, V);
2624
2625   // Simplify 'fcmp pred X, X'
2626   if (Op0 == Op1) {
2627     switch (I.getPredicate()) {
2628     default: llvm_unreachable("Unknown predicate!");
2629     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
2630     case FCmpInst::FCMP_ULT:    // True if unordered or less than
2631     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
2632     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
2633       // Canonicalize these to be 'fcmp uno %X, 0.0'.
2634       I.setPredicate(FCmpInst::FCMP_UNO);
2635       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2636       return &I;
2637       
2638     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
2639     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
2640     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
2641     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
2642       // Canonicalize these to be 'fcmp ord %X, 0.0'.
2643       I.setPredicate(FCmpInst::FCMP_ORD);
2644       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2645       return &I;
2646     }
2647   }
2648     
2649   // Handle fcmp with constant RHS
2650   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2651     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2652       switch (LHSI->getOpcode()) {
2653       case Instruction::PHI:
2654         // Only fold fcmp into the PHI if the phi and fcmp are in the same
2655         // block.  If in the same block, we're encouraging jump threading.  If
2656         // not, we are just pessimizing the code by making an i1 phi.
2657         if (LHSI->getParent() == I.getParent())
2658           if (Instruction *NV = FoldOpIntoPhi(I))
2659             return NV;
2660         break;
2661       case Instruction::SIToFP:
2662       case Instruction::UIToFP:
2663         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2664           return NV;
2665         break;
2666       case Instruction::Select: {
2667         // If either operand of the select is a constant, we can fold the
2668         // comparison into the select arms, which will cause one to be
2669         // constant folded and the select turned into a bitwise or.
2670         Value *Op1 = 0, *Op2 = 0;
2671         if (LHSI->hasOneUse()) {
2672           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2673             // Fold the known value into the constant operand.
2674             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2675             // Insert a new FCmp of the other select operand.
2676             Op2 = Builder->CreateFCmp(I.getPredicate(),
2677                                       LHSI->getOperand(2), RHSC, I.getName());
2678           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2679             // Fold the known value into the constant operand.
2680             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2681             // Insert a new FCmp of the other select operand.
2682             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2683                                       RHSC, I.getName());
2684           }
2685         }
2686
2687         if (Op1)
2688           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2689         break;
2690       }
2691       case Instruction::Load:
2692         if (GetElementPtrInst *GEP =
2693             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2694           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2695             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2696                 !cast<LoadInst>(LHSI)->isVolatile())
2697               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2698                 return Res;
2699         }
2700         break;
2701       }
2702   }
2703
2704   return Changed ? &I : 0;
2705 }