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