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