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