InstCombineCompares.cpp revision 210299
1202375Srdivacky//===- InstCombineCompares.cpp --------------------------------------------===//
2202375Srdivacky//
3202375Srdivacky//                     The LLVM Compiler Infrastructure
4202375Srdivacky//
5202375Srdivacky// This file is distributed under the University of Illinois Open Source
6202375Srdivacky// License. See LICENSE.TXT for details.
7202375Srdivacky//
8202375Srdivacky//===----------------------------------------------------------------------===//
9202375Srdivacky//
10202375Srdivacky// This file implements the visitICmp and visitFCmp functions.
11202375Srdivacky//
12202375Srdivacky//===----------------------------------------------------------------------===//
13202375Srdivacky
14202375Srdivacky#include "InstCombine.h"
15202375Srdivacky#include "llvm/IntrinsicInst.h"
16202375Srdivacky#include "llvm/Analysis/InstructionSimplify.h"
17202375Srdivacky#include "llvm/Analysis/MemoryBuiltins.h"
18202375Srdivacky#include "llvm/Target/TargetData.h"
19202375Srdivacky#include "llvm/Support/ConstantRange.h"
20202375Srdivacky#include "llvm/Support/GetElementPtrTypeIterator.h"
21202375Srdivacky#include "llvm/Support/PatternMatch.h"
22202375Srdivackyusing namespace llvm;
23202375Srdivackyusing namespace PatternMatch;
24202375Srdivacky
25202375Srdivacky/// AddOne - Add one to a ConstantInt
26202375Srdivackystatic Constant *AddOne(Constant *C) {
27202375Srdivacky  return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
28202375Srdivacky}
29202375Srdivacky/// SubOne - Subtract one from a ConstantInt
30202375Srdivackystatic Constant *SubOne(ConstantInt *C) {
31202375Srdivacky  return ConstantExpr::getSub(C,  ConstantInt::get(C->getType(), 1));
32202375Srdivacky}
33202375Srdivacky
34202375Srdivackystatic ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
35202375Srdivacky  return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
36202375Srdivacky}
37202375Srdivacky
38202375Srdivackystatic bool HasAddOverflow(ConstantInt *Result,
39202375Srdivacky                           ConstantInt *In1, ConstantInt *In2,
40202375Srdivacky                           bool IsSigned) {
41202375Srdivacky  if (IsSigned)
42202375Srdivacky    if (In2->getValue().isNegative())
43202375Srdivacky      return Result->getValue().sgt(In1->getValue());
44202375Srdivacky    else
45202375Srdivacky      return Result->getValue().slt(In1->getValue());
46202375Srdivacky  else
47202375Srdivacky    return Result->getValue().ult(In1->getValue());
48202375Srdivacky}
49202375Srdivacky
50202375Srdivacky/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
51202375Srdivacky/// overflowed for this type.
52202375Srdivackystatic bool AddWithOverflow(Constant *&Result, Constant *In1,
53202375Srdivacky                            Constant *In2, bool IsSigned = false) {
54202375Srdivacky  Result = ConstantExpr::getAdd(In1, In2);
55202375Srdivacky
56202375Srdivacky  if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
57202375Srdivacky    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
58202375Srdivacky      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
59202375Srdivacky      if (HasAddOverflow(ExtractElement(Result, Idx),
60202375Srdivacky                         ExtractElement(In1, Idx),
61202375Srdivacky                         ExtractElement(In2, Idx),
62202375Srdivacky                         IsSigned))
63202375Srdivacky        return true;
64202375Srdivacky    }
65202375Srdivacky    return false;
66202375Srdivacky  }
67202375Srdivacky
68202375Srdivacky  return HasAddOverflow(cast<ConstantInt>(Result),
69202375Srdivacky                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
70202375Srdivacky                        IsSigned);
71202375Srdivacky}
72202375Srdivacky
73202375Srdivackystatic bool HasSubOverflow(ConstantInt *Result,
74202375Srdivacky                           ConstantInt *In1, ConstantInt *In2,
75202375Srdivacky                           bool IsSigned) {
76202375Srdivacky  if (IsSigned)
77202375Srdivacky    if (In2->getValue().isNegative())
78202375Srdivacky      return Result->getValue().slt(In1->getValue());
79202375Srdivacky    else
80202375Srdivacky      return Result->getValue().sgt(In1->getValue());
81202375Srdivacky  else
82202375Srdivacky    return Result->getValue().ugt(In1->getValue());
83202375Srdivacky}
84202375Srdivacky
85202375Srdivacky/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
86202375Srdivacky/// overflowed for this type.
87202375Srdivackystatic bool SubWithOverflow(Constant *&Result, Constant *In1,
88202375Srdivacky                            Constant *In2, bool IsSigned = false) {
89202375Srdivacky  Result = ConstantExpr::getSub(In1, In2);
90202375Srdivacky
91202375Srdivacky  if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
92202375Srdivacky    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
93202375Srdivacky      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
94202375Srdivacky      if (HasSubOverflow(ExtractElement(Result, Idx),
95202375Srdivacky                         ExtractElement(In1, Idx),
96202375Srdivacky                         ExtractElement(In2, Idx),
97202375Srdivacky                         IsSigned))
98202375Srdivacky        return true;
99202375Srdivacky    }
100202375Srdivacky    return false;
101202375Srdivacky  }
102202375Srdivacky
103202375Srdivacky  return HasSubOverflow(cast<ConstantInt>(Result),
104202375Srdivacky                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
105202375Srdivacky                        IsSigned);
106202375Srdivacky}
107202375Srdivacky
108202375Srdivacky/// isSignBitCheck - Given an exploded icmp instruction, return true if the
109202375Srdivacky/// comparison only checks the sign bit.  If it only checks the sign bit, set
110202375Srdivacky/// TrueIfSigned if the result of the comparison is true when the input value is
111202375Srdivacky/// signed.
112202375Srdivackystatic bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
113202375Srdivacky                           bool &TrueIfSigned) {
114202375Srdivacky  switch (pred) {
115202375Srdivacky  case ICmpInst::ICMP_SLT:   // True if LHS s< 0
116202375Srdivacky    TrueIfSigned = true;
117202375Srdivacky    return RHS->isZero();
118202375Srdivacky  case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
119202375Srdivacky    TrueIfSigned = true;
120202375Srdivacky    return RHS->isAllOnesValue();
121202375Srdivacky  case ICmpInst::ICMP_SGT:   // True if LHS s> -1
122202375Srdivacky    TrueIfSigned = false;
123202375Srdivacky    return RHS->isAllOnesValue();
124202375Srdivacky  case ICmpInst::ICMP_UGT:
125202375Srdivacky    // True if LHS u> RHS and RHS == high-bit-mask - 1
126202375Srdivacky    TrueIfSigned = true;
127202375Srdivacky    return RHS->getValue() ==
128202375Srdivacky      APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
129202375Srdivacky  case ICmpInst::ICMP_UGE:
130202375Srdivacky    // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
131202375Srdivacky    TrueIfSigned = true;
132202375Srdivacky    return RHS->getValue().isSignBit();
133202375Srdivacky  default:
134202375Srdivacky    return false;
135202375Srdivacky  }
136202375Srdivacky}
137202375Srdivacky
138202375Srdivacky// isHighOnes - Return true if the constant is of the form 1+0+.
139202375Srdivacky// This is the same as lowones(~X).
140202375Srdivackystatic bool isHighOnes(const ConstantInt *CI) {
141202375Srdivacky  return (~CI->getValue() + 1).isPowerOf2();
142202375Srdivacky}
143202375Srdivacky
144202375Srdivacky/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
145202375Srdivacky/// set of known zero and one bits, compute the maximum and minimum values that
146202375Srdivacky/// could have the specified known zero and known one bits, returning them in
147202375Srdivacky/// min/max.
148202375Srdivackystatic void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
149202375Srdivacky                                                   const APInt& KnownOne,
150202375Srdivacky                                                   APInt& Min, APInt& Max) {
151202375Srdivacky  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
152202375Srdivacky         KnownZero.getBitWidth() == Min.getBitWidth() &&
153202375Srdivacky         KnownZero.getBitWidth() == Max.getBitWidth() &&
154202375Srdivacky         "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
155202375Srdivacky  APInt UnknownBits = ~(KnownZero|KnownOne);
156202375Srdivacky
157202375Srdivacky  // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
158202375Srdivacky  // bit if it is unknown.
159202375Srdivacky  Min = KnownOne;
160202375Srdivacky  Max = KnownOne|UnknownBits;
161202375Srdivacky
162202375Srdivacky  if (UnknownBits.isNegative()) { // Sign bit is unknown
163202375Srdivacky    Min.set(Min.getBitWidth()-1);
164202375Srdivacky    Max.clear(Max.getBitWidth()-1);
165202375Srdivacky  }
166202375Srdivacky}
167202375Srdivacky
168202375Srdivacky// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
169202375Srdivacky// a set of known zero and one bits, compute the maximum and minimum values that
170202375Srdivacky// could have the specified known zero and known one bits, returning them in
171202375Srdivacky// min/max.
172202375Srdivackystatic void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
173202375Srdivacky                                                     const APInt &KnownOne,
174202375Srdivacky                                                     APInt &Min, APInt &Max) {
175202375Srdivacky  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
176202375Srdivacky         KnownZero.getBitWidth() == Min.getBitWidth() &&
177202375Srdivacky         KnownZero.getBitWidth() == Max.getBitWidth() &&
178202375Srdivacky         "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
179202375Srdivacky  APInt UnknownBits = ~(KnownZero|KnownOne);
180202375Srdivacky
181202375Srdivacky  // The minimum value is when the unknown bits are all zeros.
182202375Srdivacky  Min = KnownOne;
183202375Srdivacky  // The maximum value is when the unknown bits are all ones.
184202375Srdivacky  Max = KnownOne|UnknownBits;
185202375Srdivacky}
186202375Srdivacky
187202375Srdivacky
188202375Srdivacky
189202375Srdivacky/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
190202375Srdivacky///   cmp pred (load (gep GV, ...)), cmpcst
191202375Srdivacky/// where GV is a global variable with a constant initializer.  Try to simplify
192202375Srdivacky/// this into some simple computation that does not need the load.  For example
193202375Srdivacky/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
194202375Srdivacky///
195202375Srdivacky/// If AndCst is non-null, then the loaded value is masked with that constant
196202375Srdivacky/// before doing the comparison.  This handles cases like "A[i]&4 == 0".
197202375SrdivackyInstruction *InstCombiner::
198202375SrdivackyFoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
199202375Srdivacky                             CmpInst &ICI, ConstantInt *AndCst) {
200202375Srdivacky  // We need TD information to know the pointer size unless this is inbounds.
201202375Srdivacky  if (!GEP->isInBounds() && TD == 0) return 0;
202202375Srdivacky
203202375Srdivacky  ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
204202375Srdivacky  if (Init == 0 || Init->getNumOperands() > 1024) return 0;
205202375Srdivacky
206202375Srdivacky  // There are many forms of this optimization we can handle, for now, just do
207202375Srdivacky  // the simple index into a single-dimensional array.
208202375Srdivacky  //
209202375Srdivacky  // Require: GEP GV, 0, i {{, constant indices}}
210202375Srdivacky  if (GEP->getNumOperands() < 3 ||
211202375Srdivacky      !isa<ConstantInt>(GEP->getOperand(1)) ||
212202375Srdivacky      !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
213202375Srdivacky      isa<Constant>(GEP->getOperand(2)))
214202375Srdivacky    return 0;
215202375Srdivacky
216202375Srdivacky  // Check that indices after the variable are constants and in-range for the
217202375Srdivacky  // type they index.  Collect the indices.  This is typically for arrays of
218202375Srdivacky  // structs.
219202375Srdivacky  SmallVector<unsigned, 4> LaterIndices;
220202375Srdivacky
221202375Srdivacky  const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
222202375Srdivacky  for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
223202375Srdivacky    ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
224202375Srdivacky    if (Idx == 0) return 0;  // Variable index.
225202375Srdivacky
226202375Srdivacky    uint64_t IdxVal = Idx->getZExtValue();
227202375Srdivacky    if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
228202375Srdivacky
229202375Srdivacky    if (const StructType *STy = dyn_cast<StructType>(EltTy))
230202375Srdivacky      EltTy = STy->getElementType(IdxVal);
231202375Srdivacky    else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
232202375Srdivacky      if (IdxVal >= ATy->getNumElements()) return 0;
233202375Srdivacky      EltTy = ATy->getElementType();
234202375Srdivacky    } else {
235202375Srdivacky      return 0; // Unknown type.
236202375Srdivacky    }
237202375Srdivacky
238202375Srdivacky    LaterIndices.push_back(IdxVal);
239202375Srdivacky  }
240202375Srdivacky
241202375Srdivacky  enum { Overdefined = -3, Undefined = -2 };
242202375Srdivacky
243202375Srdivacky  // Variables for our state machines.
244202375Srdivacky
245202375Srdivacky  // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
246202375Srdivacky  // "i == 47 | i == 87", where 47 is the first index the condition is true for,
247202375Srdivacky  // and 87 is the second (and last) index.  FirstTrueElement is -2 when
248202375Srdivacky  // undefined, otherwise set to the first true element.  SecondTrueElement is
249202375Srdivacky  // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
250202375Srdivacky  int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
251202375Srdivacky
252202375Srdivacky  // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
253202375Srdivacky  // form "i != 47 & i != 87".  Same state transitions as for true elements.
254202375Srdivacky  int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
255202375Srdivacky
256202375Srdivacky  /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
257202375Srdivacky  /// define a state machine that triggers for ranges of values that the index
258202375Srdivacky  /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
259202375Srdivacky  /// This is -2 when undefined, -3 when overdefined, and otherwise the last
260202375Srdivacky  /// index in the range (inclusive).  We use -2 for undefined here because we
261202375Srdivacky  /// use relative comparisons and don't want 0-1 to match -1.
262202375Srdivacky  int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
263202375Srdivacky
264202375Srdivacky  // MagicBitvector - This is a magic bitvector where we set a bit if the
265202375Srdivacky  // comparison is true for element 'i'.  If there are 64 elements or less in
266202375Srdivacky  // the array, this will fully represent all the comparison results.
267202375Srdivacky  uint64_t MagicBitvector = 0;
268202375Srdivacky
269202375Srdivacky
270202375Srdivacky  // Scan the array and see if one of our patterns matches.
271202375Srdivacky  Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
272202375Srdivacky  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
273202375Srdivacky    Constant *Elt = Init->getOperand(i);
274202375Srdivacky
275202375Srdivacky    // If this is indexing an array of structures, get the structure element.
276202375Srdivacky    if (!LaterIndices.empty())
277202375Srdivacky      Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
278202375Srdivacky                                          LaterIndices.size());
279202375Srdivacky
280202375Srdivacky    // If the element is masked, handle it.
281202375Srdivacky    if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
282202375Srdivacky
283202375Srdivacky    // Find out if the comparison would be true or false for the i'th element.
284202375Srdivacky    Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
285202375Srdivacky                                                  CompareRHS, TD);
286202375Srdivacky    // If the result is undef for this element, ignore it.
287202375Srdivacky    if (isa<UndefValue>(C)) {
288202375Srdivacky      // Extend range state machines to cover this element in case there is an
289202375Srdivacky      // undef in the middle of the range.
290202375Srdivacky      if (TrueRangeEnd == (int)i-1)
291202375Srdivacky        TrueRangeEnd = i;
292202375Srdivacky      if (FalseRangeEnd == (int)i-1)
293202375Srdivacky        FalseRangeEnd = i;
294202375Srdivacky      continue;
295202375Srdivacky    }
296202375Srdivacky
297202375Srdivacky    // If we can't compute the result for any of the elements, we have to give
298202375Srdivacky    // up evaluating the entire conditional.
299202375Srdivacky    if (!isa<ConstantInt>(C)) return 0;
300202375Srdivacky
301202375Srdivacky    // Otherwise, we know if the comparison is true or false for this element,
302202375Srdivacky    // update our state machines.
303202375Srdivacky    bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
304202375Srdivacky
305202375Srdivacky    // State machine for single/double/range index comparison.
306202375Srdivacky    if (IsTrueForElt) {
307202375Srdivacky      // Update the TrueElement state machine.
308202375Srdivacky      if (FirstTrueElement == Undefined)
309202375Srdivacky        FirstTrueElement = TrueRangeEnd = i;  // First true element.
310202375Srdivacky      else {
311202375Srdivacky        // Update double-compare state machine.
312202375Srdivacky        if (SecondTrueElement == Undefined)
313202375Srdivacky          SecondTrueElement = i;
314202375Srdivacky        else
315202375Srdivacky          SecondTrueElement = Overdefined;
316202375Srdivacky
317202375Srdivacky        // Update range state machine.
318202375Srdivacky        if (TrueRangeEnd == (int)i-1)
319202375Srdivacky          TrueRangeEnd = i;
320202375Srdivacky        else
321202375Srdivacky          TrueRangeEnd = Overdefined;
322202375Srdivacky      }
323202375Srdivacky    } else {
324202375Srdivacky      // Update the FalseElement state machine.
325202375Srdivacky      if (FirstFalseElement == Undefined)
326202375Srdivacky        FirstFalseElement = FalseRangeEnd = i; // First false element.
327202375Srdivacky      else {
328202375Srdivacky        // Update double-compare state machine.
329202375Srdivacky        if (SecondFalseElement == Undefined)
330202375Srdivacky          SecondFalseElement = i;
331202375Srdivacky        else
332202375Srdivacky          SecondFalseElement = Overdefined;
333202375Srdivacky
334202375Srdivacky        // Update range state machine.
335202375Srdivacky        if (FalseRangeEnd == (int)i-1)
336202375Srdivacky          FalseRangeEnd = i;
337202375Srdivacky        else
338202375Srdivacky          FalseRangeEnd = Overdefined;
339202375Srdivacky      }
340202375Srdivacky    }
341202375Srdivacky
342202375Srdivacky
343202375Srdivacky    // If this element is in range, update our magic bitvector.
344202375Srdivacky    if (i < 64 && IsTrueForElt)
345202375Srdivacky      MagicBitvector |= 1ULL << i;
346202375Srdivacky
347202375Srdivacky    // If all of our states become overdefined, bail out early.  Since the
348202375Srdivacky    // predicate is expensive, only check it every 8 elements.  This is only
349202375Srdivacky    // really useful for really huge arrays.
350202375Srdivacky    if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
351202375Srdivacky        SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
352202375Srdivacky        FalseRangeEnd == Overdefined)
353202375Srdivacky      return 0;
354202375Srdivacky  }
355202375Srdivacky
356202375Srdivacky  // Now that we've scanned the entire array, emit our new comparison(s).  We
357202375Srdivacky  // order the state machines in complexity of the generated code.
358202375Srdivacky  Value *Idx = GEP->getOperand(2);
359202375Srdivacky
360202375Srdivacky  // If the index is larger than the pointer size of the target, truncate the
361202375Srdivacky  // index down like the GEP would do implicitly.  We don't have to do this for
362202375Srdivacky  // an inbounds GEP because the index can't be out of range.
363202375Srdivacky  if (!GEP->isInBounds() &&
364202375Srdivacky      Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
365202375Srdivacky    Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
366202375Srdivacky
367202375Srdivacky  // If the comparison is only true for one or two elements, emit direct
368202375Srdivacky  // comparisons.
369202375Srdivacky  if (SecondTrueElement != Overdefined) {
370202375Srdivacky    // None true -> false.
371202375Srdivacky    if (FirstTrueElement == Undefined)
372202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
373202375Srdivacky
374202375Srdivacky    Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
375202375Srdivacky
376202375Srdivacky    // True for one element -> 'i == 47'.
377202375Srdivacky    if (SecondTrueElement == Undefined)
378202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
379202375Srdivacky
380202375Srdivacky    // True for two elements -> 'i == 47 | i == 72'.
381202375Srdivacky    Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
382202375Srdivacky    Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
383202375Srdivacky    Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
384202375Srdivacky    return BinaryOperator::CreateOr(C1, C2);
385202375Srdivacky  }
386202375Srdivacky
387202375Srdivacky  // If the comparison is only false for one or two elements, emit direct
388202375Srdivacky  // comparisons.
389202375Srdivacky  if (SecondFalseElement != Overdefined) {
390202375Srdivacky    // None false -> true.
391202375Srdivacky    if (FirstFalseElement == Undefined)
392202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
393202375Srdivacky
394202375Srdivacky    Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
395202375Srdivacky
396202375Srdivacky    // False for one element -> 'i != 47'.
397202375Srdivacky    if (SecondFalseElement == Undefined)
398202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
399202375Srdivacky
400202375Srdivacky    // False for two elements -> 'i != 47 & i != 72'.
401202375Srdivacky    Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
402202375Srdivacky    Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
403202375Srdivacky    Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
404202375Srdivacky    return BinaryOperator::CreateAnd(C1, C2);
405202375Srdivacky  }
406202375Srdivacky
407202375Srdivacky  // If the comparison can be replaced with a range comparison for the elements
408202375Srdivacky  // where it is true, emit the range check.
409202375Srdivacky  if (TrueRangeEnd != Overdefined) {
410202375Srdivacky    assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
411202375Srdivacky
412202375Srdivacky    // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
413202375Srdivacky    if (FirstTrueElement) {
414202375Srdivacky      Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
415202375Srdivacky      Idx = Builder->CreateAdd(Idx, Offs);
416202375Srdivacky    }
417202375Srdivacky
418202375Srdivacky    Value *End = ConstantInt::get(Idx->getType(),
419202375Srdivacky                                  TrueRangeEnd-FirstTrueElement+1);
420202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
421202375Srdivacky  }
422202375Srdivacky
423202375Srdivacky  // False range check.
424202375Srdivacky  if (FalseRangeEnd != Overdefined) {
425202375Srdivacky    assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
426202375Srdivacky    // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
427202375Srdivacky    if (FirstFalseElement) {
428202375Srdivacky      Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
429202375Srdivacky      Idx = Builder->CreateAdd(Idx, Offs);
430202375Srdivacky    }
431202375Srdivacky
432202375Srdivacky    Value *End = ConstantInt::get(Idx->getType(),
433202375Srdivacky                                  FalseRangeEnd-FirstFalseElement);
434202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
435202375Srdivacky  }
436202375Srdivacky
437202375Srdivacky
438202375Srdivacky  // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
439202375Srdivacky  // of this load, replace it with computation that does:
440202375Srdivacky  //   ((magic_cst >> i) & 1) != 0
441202375Srdivacky  if (Init->getNumOperands() <= 32 ||
442202375Srdivacky      (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
443202375Srdivacky    const Type *Ty;
444202375Srdivacky    if (Init->getNumOperands() <= 32)
445202375Srdivacky      Ty = Type::getInt32Ty(Init->getContext());
446202375Srdivacky    else
447202375Srdivacky      Ty = Type::getInt64Ty(Init->getContext());
448202375Srdivacky    Value *V = Builder->CreateIntCast(Idx, Ty, false);
449202375Srdivacky    V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
450202375Srdivacky    V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
451202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
452202375Srdivacky  }
453202375Srdivacky
454202375Srdivacky  return 0;
455202375Srdivacky}
456202375Srdivacky
457202375Srdivacky
458202375Srdivacky/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
459202375Srdivacky/// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
460202375Srdivacky/// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
461202375Srdivacky/// be complex, and scales are involved.  The above expression would also be
462202375Srdivacky/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
463202375Srdivacky/// This later form is less amenable to optimization though, and we are allowed
464202375Srdivacky/// to generate the first by knowing that pointer arithmetic doesn't overflow.
465202375Srdivacky///
466202375Srdivacky/// If we can't emit an optimized form for this expression, this returns null.
467202375Srdivacky///
468202375Srdivackystatic Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
469202375Srdivacky                                          InstCombiner &IC) {
470202375Srdivacky  TargetData &TD = *IC.getTargetData();
471202375Srdivacky  gep_type_iterator GTI = gep_type_begin(GEP);
472202375Srdivacky
473202375Srdivacky  // Check to see if this gep only has a single variable index.  If so, and if
474202375Srdivacky  // any constant indices are a multiple of its scale, then we can compute this
475202375Srdivacky  // in terms of the scale of the variable index.  For example, if the GEP
476202375Srdivacky  // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
477202375Srdivacky  // because the expression will cross zero at the same point.
478202375Srdivacky  unsigned i, e = GEP->getNumOperands();
479202375Srdivacky  int64_t Offset = 0;
480202375Srdivacky  for (i = 1; i != e; ++i, ++GTI) {
481202375Srdivacky    if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
482202375Srdivacky      // Compute the aggregate offset of constant indices.
483202375Srdivacky      if (CI->isZero()) continue;
484202375Srdivacky
485202375Srdivacky      // Handle a struct index, which adds its field offset to the pointer.
486202375Srdivacky      if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
487202375Srdivacky        Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
488202375Srdivacky      } else {
489202375Srdivacky        uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
490202375Srdivacky        Offset += Size*CI->getSExtValue();
491202375Srdivacky      }
492202375Srdivacky    } else {
493202375Srdivacky      // Found our variable index.
494202375Srdivacky      break;
495202375Srdivacky    }
496202375Srdivacky  }
497202375Srdivacky
498202375Srdivacky  // If there are no variable indices, we must have a constant offset, just
499202375Srdivacky  // evaluate it the general way.
500202375Srdivacky  if (i == e) return 0;
501202375Srdivacky
502202375Srdivacky  Value *VariableIdx = GEP->getOperand(i);
503202375Srdivacky  // Determine the scale factor of the variable element.  For example, this is
504202375Srdivacky  // 4 if the variable index is into an array of i32.
505202375Srdivacky  uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
506202375Srdivacky
507202375Srdivacky  // Verify that there are no other variable indices.  If so, emit the hard way.
508202375Srdivacky  for (++i, ++GTI; i != e; ++i, ++GTI) {
509202375Srdivacky    ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
510202375Srdivacky    if (!CI) return 0;
511202375Srdivacky
512202375Srdivacky    // Compute the aggregate offset of constant indices.
513202375Srdivacky    if (CI->isZero()) continue;
514202375Srdivacky
515202375Srdivacky    // Handle a struct index, which adds its field offset to the pointer.
516202375Srdivacky    if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
517202375Srdivacky      Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
518202375Srdivacky    } else {
519202375Srdivacky      uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
520202375Srdivacky      Offset += Size*CI->getSExtValue();
521202375Srdivacky    }
522202375Srdivacky  }
523202375Srdivacky
524202375Srdivacky  // Okay, we know we have a single variable index, which must be a
525202375Srdivacky  // pointer/array/vector index.  If there is no offset, life is simple, return
526202375Srdivacky  // the index.
527202375Srdivacky  unsigned IntPtrWidth = TD.getPointerSizeInBits();
528202375Srdivacky  if (Offset == 0) {
529202375Srdivacky    // Cast to intptrty in case a truncation occurs.  If an extension is needed,
530202375Srdivacky    // we don't need to bother extending: the extension won't affect where the
531202375Srdivacky    // computation crosses zero.
532202375Srdivacky    if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
533202375Srdivacky      VariableIdx = new TruncInst(VariableIdx,
534202375Srdivacky                                  TD.getIntPtrType(VariableIdx->getContext()),
535202375Srdivacky                                  VariableIdx->getName(), &I);
536202375Srdivacky    return VariableIdx;
537202375Srdivacky  }
538202375Srdivacky
539202375Srdivacky  // Otherwise, there is an index.  The computation we will do will be modulo
540202375Srdivacky  // the pointer size, so get it.
541202375Srdivacky  uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
542202375Srdivacky
543202375Srdivacky  Offset &= PtrSizeMask;
544202375Srdivacky  VariableScale &= PtrSizeMask;
545202375Srdivacky
546202375Srdivacky  // To do this transformation, any constant index must be a multiple of the
547202375Srdivacky  // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
548202375Srdivacky  // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
549202375Srdivacky  // multiple of the variable scale.
550202375Srdivacky  int64_t NewOffs = Offset / (int64_t)VariableScale;
551202375Srdivacky  if (Offset != NewOffs*(int64_t)VariableScale)
552202375Srdivacky    return 0;
553202375Srdivacky
554202375Srdivacky  // Okay, we can do this evaluation.  Start by converting the index to intptr.
555202375Srdivacky  const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
556202375Srdivacky  if (VariableIdx->getType() != IntPtrTy)
557202375Srdivacky    VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
558202375Srdivacky                                              true /*SExt*/,
559202375Srdivacky                                              VariableIdx->getName(), &I);
560202375Srdivacky  Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
561202375Srdivacky  return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
562202375Srdivacky}
563202375Srdivacky
564202375Srdivacky/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
565202375Srdivacky/// else.  At this point we know that the GEP is on the LHS of the comparison.
566202375SrdivackyInstruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
567202375Srdivacky                                       ICmpInst::Predicate Cond,
568202375Srdivacky                                       Instruction &I) {
569202375Srdivacky  // Look through bitcasts.
570202375Srdivacky  if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
571202375Srdivacky    RHS = BCI->getOperand(0);
572202375Srdivacky
573202375Srdivacky  Value *PtrBase = GEPLHS->getOperand(0);
574202375Srdivacky  if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
575202375Srdivacky    // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
576202375Srdivacky    // This transformation (ignoring the base and scales) is valid because we
577202375Srdivacky    // know pointers can't overflow since the gep is inbounds.  See if we can
578202375Srdivacky    // output an optimized form.
579202375Srdivacky    Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
580202375Srdivacky
581202375Srdivacky    // If not, synthesize the offset the hard way.
582202375Srdivacky    if (Offset == 0)
583202375Srdivacky      Offset = EmitGEPOffset(GEPLHS);
584202375Srdivacky    return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
585202375Srdivacky                        Constant::getNullValue(Offset->getType()));
586202375Srdivacky  } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
587202375Srdivacky    // If the base pointers are different, but the indices are the same, just
588202375Srdivacky    // compare the base pointer.
589202375Srdivacky    if (PtrBase != GEPRHS->getOperand(0)) {
590202375Srdivacky      bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
591202375Srdivacky      IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
592202375Srdivacky                        GEPRHS->getOperand(0)->getType();
593202375Srdivacky      if (IndicesTheSame)
594202375Srdivacky        for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
595202375Srdivacky          if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
596202375Srdivacky            IndicesTheSame = false;
597202375Srdivacky            break;
598202375Srdivacky          }
599202375Srdivacky
600202375Srdivacky      // If all indices are the same, just compare the base pointers.
601202375Srdivacky      if (IndicesTheSame)
602202375Srdivacky        return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
603202375Srdivacky                            GEPLHS->getOperand(0), GEPRHS->getOperand(0));
604202375Srdivacky
605202375Srdivacky      // Otherwise, the base pointers are different and the indices are
606202375Srdivacky      // different, bail out.
607202375Srdivacky      return 0;
608202375Srdivacky    }
609202375Srdivacky
610202375Srdivacky    // If one of the GEPs has all zero indices, recurse.
611202375Srdivacky    bool AllZeros = true;
612202375Srdivacky    for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
613202375Srdivacky      if (!isa<Constant>(GEPLHS->getOperand(i)) ||
614202375Srdivacky          !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
615202375Srdivacky        AllZeros = false;
616202375Srdivacky        break;
617202375Srdivacky      }
618202375Srdivacky    if (AllZeros)
619202375Srdivacky      return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
620202375Srdivacky                          ICmpInst::getSwappedPredicate(Cond), I);
621202375Srdivacky
622202375Srdivacky    // If the other GEP has all zero indices, recurse.
623202375Srdivacky    AllZeros = true;
624202375Srdivacky    for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
625202375Srdivacky      if (!isa<Constant>(GEPRHS->getOperand(i)) ||
626202375Srdivacky          !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
627202375Srdivacky        AllZeros = false;
628202375Srdivacky        break;
629202375Srdivacky      }
630202375Srdivacky    if (AllZeros)
631202375Srdivacky      return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
632202375Srdivacky
633202375Srdivacky    if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
634202375Srdivacky      // If the GEPs only differ by one index, compare it.
635202375Srdivacky      unsigned NumDifferences = 0;  // Keep track of # differences.
636202375Srdivacky      unsigned DiffOperand = 0;     // The operand that differs.
637202375Srdivacky      for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
638202375Srdivacky        if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
639202375Srdivacky          if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
640202375Srdivacky                   GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
641202375Srdivacky            // Irreconcilable differences.
642202375Srdivacky            NumDifferences = 2;
643202375Srdivacky            break;
644202375Srdivacky          } else {
645202375Srdivacky            if (NumDifferences++) break;
646202375Srdivacky            DiffOperand = i;
647202375Srdivacky          }
648202375Srdivacky        }
649202375Srdivacky
650202375Srdivacky      if (NumDifferences == 0)   // SAME GEP?
651202375Srdivacky        return ReplaceInstUsesWith(I, // No comparison is needed here.
652202375Srdivacky                               ConstantInt::get(Type::getInt1Ty(I.getContext()),
653202375Srdivacky                                             ICmpInst::isTrueWhenEqual(Cond)));
654202375Srdivacky
655202375Srdivacky      else if (NumDifferences == 1) {
656202375Srdivacky        Value *LHSV = GEPLHS->getOperand(DiffOperand);
657202375Srdivacky        Value *RHSV = GEPRHS->getOperand(DiffOperand);
658202375Srdivacky        // Make sure we do a signed comparison here.
659202375Srdivacky        return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
660202375Srdivacky      }
661202375Srdivacky    }
662202375Srdivacky
663202375Srdivacky    // Only lower this if the icmp is the only user of the GEP or if we expect
664202375Srdivacky    // the result to fold to a constant!
665202375Srdivacky    if (TD &&
666202375Srdivacky        (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
667202375Srdivacky        (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
668202375Srdivacky      // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
669202375Srdivacky      Value *L = EmitGEPOffset(GEPLHS);
670202375Srdivacky      Value *R = EmitGEPOffset(GEPRHS);
671202375Srdivacky      return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
672202375Srdivacky    }
673202375Srdivacky  }
674202375Srdivacky  return 0;
675202375Srdivacky}
676202375Srdivacky
677202375Srdivacky/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
678202375SrdivackyInstruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
679202375Srdivacky                                            Value *X, ConstantInt *CI,
680202375Srdivacky                                            ICmpInst::Predicate Pred,
681202375Srdivacky                                            Value *TheAdd) {
682202375Srdivacky  // If we have X+0, exit early (simplifying logic below) and let it get folded
683202375Srdivacky  // elsewhere.   icmp X+0, X  -> icmp X, X
684202375Srdivacky  if (CI->isZero()) {
685202375Srdivacky    bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
686202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
687202375Srdivacky  }
688202375Srdivacky
689202375Srdivacky  // (X+4) == X -> false.
690202375Srdivacky  if (Pred == ICmpInst::ICMP_EQ)
691202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
692202375Srdivacky
693202375Srdivacky  // (X+4) != X -> true.
694202375Srdivacky  if (Pred == ICmpInst::ICMP_NE)
695202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
696202375Srdivacky
697202375Srdivacky  // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
698202375Srdivacky  bool isNUW = false, isNSW = false;
699202375Srdivacky  if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
700202375Srdivacky    isNUW = Add->hasNoUnsignedWrap();
701202375Srdivacky    isNSW = Add->hasNoSignedWrap();
702202375Srdivacky  }
703202375Srdivacky
704202375Srdivacky  // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
705202375Srdivacky  // so the values can never be equal.  Similiarly for all other "or equals"
706202375Srdivacky  // operators.
707202375Srdivacky
708202375Srdivacky  // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
709202375Srdivacky  // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
710202375Srdivacky  // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
711202375Srdivacky  if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
712202375Srdivacky    // If this is an NUW add, then this is always false.
713202375Srdivacky    if (isNUW)
714202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
715202375Srdivacky
716202375Srdivacky    Value *R =
717202375Srdivacky      ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
718202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
719202375Srdivacky  }
720202375Srdivacky
721202375Srdivacky  // (X+1) >u X        --> X <u (0-1)        --> X != 255
722202375Srdivacky  // (X+2) >u X        --> X <u (0-2)        --> X <u 254
723202375Srdivacky  // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
724202375Srdivacky  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
725202375Srdivacky    // If this is an NUW add, then this is always true.
726202375Srdivacky    if (isNUW)
727202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
728202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
729202375Srdivacky  }
730202375Srdivacky
731202375Srdivacky  unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
732202375Srdivacky  ConstantInt *SMax = ConstantInt::get(X->getContext(),
733202375Srdivacky                                       APInt::getSignedMaxValue(BitWidth));
734202375Srdivacky
735202375Srdivacky  // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
736202375Srdivacky  // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
737202375Srdivacky  // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
738202375Srdivacky  // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
739202375Srdivacky  // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
740202375Srdivacky  // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
741202375Srdivacky  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
742202375Srdivacky    // If this is an NSW add, then we have two cases: if the constant is
743202375Srdivacky    // positive, then this is always false, if negative, this is always true.
744202375Srdivacky    if (isNSW) {
745202375Srdivacky      bool isTrue = CI->getValue().isNegative();
746202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
747202375Srdivacky    }
748202375Srdivacky
749202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
750202375Srdivacky  }
751202375Srdivacky
752202375Srdivacky  // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
753202375Srdivacky  // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
754202375Srdivacky  // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
755202375Srdivacky  // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
756202375Srdivacky  // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
757202375Srdivacky  // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
758202375Srdivacky
759202375Srdivacky  // If this is an NSW add, then we have two cases: if the constant is
760202375Srdivacky  // positive, then this is always true, if negative, this is always false.
761202375Srdivacky  if (isNSW) {
762202375Srdivacky    bool isTrue = !CI->getValue().isNegative();
763202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
764202375Srdivacky  }
765202375Srdivacky
766202375Srdivacky  assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
767202375Srdivacky  Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
768202375Srdivacky  return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
769202375Srdivacky}
770202375Srdivacky
771202375Srdivacky/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
772202375Srdivacky/// and CmpRHS are both known to be integer constants.
773202375SrdivackyInstruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
774202375Srdivacky                                          ConstantInt *DivRHS) {
775202375Srdivacky  ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
776202375Srdivacky  const APInt &CmpRHSV = CmpRHS->getValue();
777202375Srdivacky
778202375Srdivacky  // FIXME: If the operand types don't match the type of the divide
779202375Srdivacky  // then don't attempt this transform. The code below doesn't have the
780202375Srdivacky  // logic to deal with a signed divide and an unsigned compare (and
781202375Srdivacky  // vice versa). This is because (x /s C1) <s C2  produces different
782202375Srdivacky  // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
783202375Srdivacky  // (x /u C1) <u C2.  Simply casting the operands and result won't
784202375Srdivacky  // work. :(  The if statement below tests that condition and bails
785202375Srdivacky  // if it finds it.
786202375Srdivacky  bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
787202375Srdivacky  if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
788202375Srdivacky    return 0;
789202375Srdivacky  if (DivRHS->isZero())
790202375Srdivacky    return 0; // The ProdOV computation fails on divide by zero.
791202375Srdivacky  if (DivIsSigned && DivRHS->isAllOnesValue())
792202375Srdivacky    return 0; // The overflow computation also screws up here
793202375Srdivacky  if (DivRHS->isOne())
794202375Srdivacky    return 0; // Not worth bothering, and eliminates some funny cases
795202375Srdivacky              // with INT_MIN.
796202375Srdivacky
797202375Srdivacky  // Compute Prod = CI * DivRHS. We are essentially solving an equation
798202375Srdivacky  // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
799202375Srdivacky  // C2 (CI). By solving for X we can turn this into a range check
800202375Srdivacky  // instead of computing a divide.
801202375Srdivacky  Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
802202375Srdivacky
803202375Srdivacky  // Determine if the product overflows by seeing if the product is
804202375Srdivacky  // not equal to the divide. Make sure we do the same kind of divide
805202375Srdivacky  // as in the LHS instruction that we're folding.
806202375Srdivacky  bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
807202375Srdivacky                 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
808202375Srdivacky
809202375Srdivacky  // Get the ICmp opcode
810202375Srdivacky  ICmpInst::Predicate Pred = ICI.getPredicate();
811202375Srdivacky
812202375Srdivacky  // Figure out the interval that is being checked.  For example, a comparison
813202375Srdivacky  // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
814202375Srdivacky  // Compute this interval based on the constants involved and the signedness of
815202375Srdivacky  // the compare/divide.  This computes a half-open interval, keeping track of
816202375Srdivacky  // whether either value in the interval overflows.  After analysis each
817202375Srdivacky  // overflow variable is set to 0 if it's corresponding bound variable is valid
818202375Srdivacky  // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
819202375Srdivacky  int LoOverflow = 0, HiOverflow = 0;
820202375Srdivacky  Constant *LoBound = 0, *HiBound = 0;
821202375Srdivacky
822202375Srdivacky  if (!DivIsSigned) {  // udiv
823202375Srdivacky    // e.g. X/5 op 3  --> [15, 20)
824202375Srdivacky    LoBound = Prod;
825202375Srdivacky    HiOverflow = LoOverflow = ProdOV;
826202375Srdivacky    if (!HiOverflow)
827202375Srdivacky      HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
828202375Srdivacky  } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
829202375Srdivacky    if (CmpRHSV == 0) {       // (X / pos) op 0
830202375Srdivacky      // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
831202375Srdivacky      LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
832202375Srdivacky      HiBound = DivRHS;
833202375Srdivacky    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
834202375Srdivacky      LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
835202375Srdivacky      HiOverflow = LoOverflow = ProdOV;
836202375Srdivacky      if (!HiOverflow)
837202375Srdivacky        HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
838202375Srdivacky    } else {                       // (X / pos) op neg
839202375Srdivacky      // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
840202375Srdivacky      HiBound = AddOne(Prod);
841202375Srdivacky      LoOverflow = HiOverflow = ProdOV ? -1 : 0;
842202375Srdivacky      if (!LoOverflow) {
843202375Srdivacky        ConstantInt* DivNeg =
844202375Srdivacky                         cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
845202375Srdivacky        LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
846202375Srdivacky       }
847202375Srdivacky    }
848202375Srdivacky  } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
849202375Srdivacky    if (CmpRHSV == 0) {       // (X / neg) op 0
850202375Srdivacky      // e.g. X/-5 op 0  --> [-4, 5)
851202375Srdivacky      LoBound = AddOne(DivRHS);
852202375Srdivacky      HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
853202375Srdivacky      if (HiBound == DivRHS) {     // -INTMIN = INTMIN
854202375Srdivacky        HiOverflow = 1;            // [INTMIN+1, overflow)
855202375Srdivacky        HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
856202375Srdivacky      }
857202375Srdivacky    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
858202375Srdivacky      // e.g. X/-5 op 3  --> [-19, -14)
859202375Srdivacky      HiBound = AddOne(Prod);
860202375Srdivacky      HiOverflow = LoOverflow = ProdOV ? -1 : 0;
861202375Srdivacky      if (!LoOverflow)
862202375Srdivacky        LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
863202375Srdivacky    } else {                       // (X / neg) op neg
864202375Srdivacky      LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
865202375Srdivacky      LoOverflow = HiOverflow = ProdOV;
866202375Srdivacky      if (!HiOverflow)
867202375Srdivacky        HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
868202375Srdivacky    }
869202375Srdivacky
870202375Srdivacky    // Dividing by a negative swaps the condition.  LT <-> GT
871202375Srdivacky    Pred = ICmpInst::getSwappedPredicate(Pred);
872202375Srdivacky  }
873202375Srdivacky
874202375Srdivacky  Value *X = DivI->getOperand(0);
875202375Srdivacky  switch (Pred) {
876202375Srdivacky  default: llvm_unreachable("Unhandled icmp opcode!");
877202375Srdivacky  case ICmpInst::ICMP_EQ:
878202375Srdivacky    if (LoOverflow && HiOverflow)
879202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
880204792Srdivacky    if (HiOverflow)
881202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
882202375Srdivacky                          ICmpInst::ICMP_UGE, X, LoBound);
883204792Srdivacky    if (LoOverflow)
884202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
885202375Srdivacky                          ICmpInst::ICMP_ULT, X, HiBound);
886204792Srdivacky    return ReplaceInstUsesWith(ICI,
887204792Srdivacky                               InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
888204792Srdivacky                                               true));
889202375Srdivacky  case ICmpInst::ICMP_NE:
890202375Srdivacky    if (LoOverflow && HiOverflow)
891202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
892204792Srdivacky    if (HiOverflow)
893202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
894202375Srdivacky                          ICmpInst::ICMP_ULT, X, LoBound);
895204792Srdivacky    if (LoOverflow)
896202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
897202375Srdivacky                          ICmpInst::ICMP_UGE, X, HiBound);
898204792Srdivacky    return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
899204792Srdivacky                                                    DivIsSigned, false));
900202375Srdivacky  case ICmpInst::ICMP_ULT:
901202375Srdivacky  case ICmpInst::ICMP_SLT:
902202375Srdivacky    if (LoOverflow == +1)   // Low bound is greater than input range.
903202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
904202375Srdivacky    if (LoOverflow == -1)   // Low bound is less than input range.
905202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
906202375Srdivacky    return new ICmpInst(Pred, X, LoBound);
907202375Srdivacky  case ICmpInst::ICMP_UGT:
908202375Srdivacky  case ICmpInst::ICMP_SGT:
909202375Srdivacky    if (HiOverflow == +1)       // High bound greater than input range.
910202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
911202375Srdivacky    else if (HiOverflow == -1)  // High bound less than input range.
912202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
913202375Srdivacky    if (Pred == ICmpInst::ICMP_UGT)
914202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
915202375Srdivacky    else
916202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
917202375Srdivacky  }
918202375Srdivacky}
919202375Srdivacky
920202375Srdivacky
921202375Srdivacky/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
922202375Srdivacky///
923202375SrdivackyInstruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
924202375Srdivacky                                                          Instruction *LHSI,
925202375Srdivacky                                                          ConstantInt *RHS) {
926202375Srdivacky  const APInt &RHSV = RHS->getValue();
927202375Srdivacky
928202375Srdivacky  switch (LHSI->getOpcode()) {
929202375Srdivacky  case Instruction::Trunc:
930202375Srdivacky    if (ICI.isEquality() && LHSI->hasOneUse()) {
931202375Srdivacky      // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
932202375Srdivacky      // of the high bits truncated out of x are known.
933202375Srdivacky      unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
934202375Srdivacky             SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
935202375Srdivacky      APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
936202375Srdivacky      APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
937202375Srdivacky      ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
938202375Srdivacky
939202375Srdivacky      // If all the high bits are known, we can do this xform.
940202375Srdivacky      if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
941202375Srdivacky        // Pull in the high bits from known-ones set.
942202375Srdivacky        APInt NewRHS(RHS->getValue());
943202375Srdivacky        NewRHS.zext(SrcBits);
944202375Srdivacky        NewRHS |= KnownOne;
945202375Srdivacky        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
946202375Srdivacky                            ConstantInt::get(ICI.getContext(), NewRHS));
947202375Srdivacky      }
948202375Srdivacky    }
949202375Srdivacky    break;
950202375Srdivacky
951202375Srdivacky  case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
952202375Srdivacky    if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
953202375Srdivacky      // If this is a comparison that tests the signbit (X < 0) or (x > -1),
954202375Srdivacky      // fold the xor.
955202375Srdivacky      if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
956202375Srdivacky          (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
957202375Srdivacky        Value *CompareVal = LHSI->getOperand(0);
958202375Srdivacky
959202375Srdivacky        // If the sign bit of the XorCST is not set, there is no change to
960202375Srdivacky        // the operation, just stop using the Xor.
961202375Srdivacky        if (!XorCST->getValue().isNegative()) {
962202375Srdivacky          ICI.setOperand(0, CompareVal);
963202375Srdivacky          Worklist.Add(LHSI);
964202375Srdivacky          return &ICI;
965202375Srdivacky        }
966202375Srdivacky
967202375Srdivacky        // Was the old condition true if the operand is positive?
968202375Srdivacky        bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
969202375Srdivacky
970202375Srdivacky        // If so, the new one isn't.
971202375Srdivacky        isTrueIfPositive ^= true;
972202375Srdivacky
973202375Srdivacky        if (isTrueIfPositive)
974202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
975202375Srdivacky                              SubOne(RHS));
976202375Srdivacky        else
977202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
978202375Srdivacky                              AddOne(RHS));
979202375Srdivacky      }
980202375Srdivacky
981202375Srdivacky      if (LHSI->hasOneUse()) {
982202375Srdivacky        // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
983202375Srdivacky        if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
984202375Srdivacky          const APInt &SignBit = XorCST->getValue();
985202375Srdivacky          ICmpInst::Predicate Pred = ICI.isSigned()
986202375Srdivacky                                         ? ICI.getUnsignedPredicate()
987202375Srdivacky                                         : ICI.getSignedPredicate();
988202375Srdivacky          return new ICmpInst(Pred, LHSI->getOperand(0),
989202375Srdivacky                              ConstantInt::get(ICI.getContext(),
990202375Srdivacky                                               RHSV ^ SignBit));
991202375Srdivacky        }
992202375Srdivacky
993202375Srdivacky        // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
994202375Srdivacky        if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
995202375Srdivacky          const APInt &NotSignBit = XorCST->getValue();
996202375Srdivacky          ICmpInst::Predicate Pred = ICI.isSigned()
997202375Srdivacky                                         ? ICI.getUnsignedPredicate()
998202375Srdivacky                                         : ICI.getSignedPredicate();
999202375Srdivacky          Pred = ICI.getSwappedPredicate(Pred);
1000202375Srdivacky          return new ICmpInst(Pred, LHSI->getOperand(0),
1001202375Srdivacky                              ConstantInt::get(ICI.getContext(),
1002202375Srdivacky                                               RHSV ^ NotSignBit));
1003202375Srdivacky        }
1004202375Srdivacky      }
1005202375Srdivacky    }
1006202375Srdivacky    break;
1007202375Srdivacky  case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
1008202375Srdivacky    if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1009202375Srdivacky        LHSI->getOperand(0)->hasOneUse()) {
1010202375Srdivacky      ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1011202375Srdivacky
1012202375Srdivacky      // If the LHS is an AND of a truncating cast, we can widen the
1013202375Srdivacky      // and/compare to be the input width without changing the value
1014202375Srdivacky      // produced, eliminating a cast.
1015202375Srdivacky      if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1016202375Srdivacky        // We can do this transformation if either the AND constant does not
1017202375Srdivacky        // have its sign bit set or if it is an equality comparison.
1018202375Srdivacky        // Extending a relational comparison when we're checking the sign
1019202375Srdivacky        // bit would not work.
1020202375Srdivacky        if (Cast->hasOneUse() &&
1021202375Srdivacky            (ICI.isEquality() ||
1022202375Srdivacky             (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
1023202375Srdivacky          uint32_t BitWidth =
1024202375Srdivacky            cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
1025202375Srdivacky          APInt NewCST = AndCST->getValue();
1026202375Srdivacky          NewCST.zext(BitWidth);
1027202375Srdivacky          APInt NewCI = RHSV;
1028202375Srdivacky          NewCI.zext(BitWidth);
1029202375Srdivacky          Value *NewAnd =
1030202375Srdivacky            Builder->CreateAnd(Cast->getOperand(0),
1031202375Srdivacky                           ConstantInt::get(ICI.getContext(), NewCST),
1032202375Srdivacky                               LHSI->getName());
1033202375Srdivacky          return new ICmpInst(ICI.getPredicate(), NewAnd,
1034202375Srdivacky                              ConstantInt::get(ICI.getContext(), NewCI));
1035202375Srdivacky        }
1036202375Srdivacky      }
1037202375Srdivacky
1038202375Srdivacky      // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1039202375Srdivacky      // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1040202375Srdivacky      // happens a LOT in code produced by the C front-end, for bitfield
1041202375Srdivacky      // access.
1042202375Srdivacky      BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1043202375Srdivacky      if (Shift && !Shift->isShift())
1044202375Srdivacky        Shift = 0;
1045202375Srdivacky
1046202375Srdivacky      ConstantInt *ShAmt;
1047202375Srdivacky      ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1048202375Srdivacky      const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
1049202375Srdivacky      const Type *AndTy = AndCST->getType();          // Type of the and.
1050202375Srdivacky
1051202375Srdivacky      // We can fold this as long as we can't shift unknown bits
1052202375Srdivacky      // into the mask.  This can only happen with signed shift
1053202375Srdivacky      // rights, as they sign-extend.
1054202375Srdivacky      if (ShAmt) {
1055202375Srdivacky        bool CanFold = Shift->isLogicalShift();
1056202375Srdivacky        if (!CanFold) {
1057202375Srdivacky          // To test for the bad case of the signed shr, see if any
1058202375Srdivacky          // of the bits shifted in could be tested after the mask.
1059202375Srdivacky          uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1060202375Srdivacky          int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1061202375Srdivacky
1062202375Srdivacky          uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1063202375Srdivacky          if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
1064202375Srdivacky               AndCST->getValue()) == 0)
1065202375Srdivacky            CanFold = true;
1066202375Srdivacky        }
1067202375Srdivacky
1068202375Srdivacky        if (CanFold) {
1069202375Srdivacky          Constant *NewCst;
1070202375Srdivacky          if (Shift->getOpcode() == Instruction::Shl)
1071202375Srdivacky            NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1072202375Srdivacky          else
1073202375Srdivacky            NewCst = ConstantExpr::getShl(RHS, ShAmt);
1074202375Srdivacky
1075202375Srdivacky          // Check to see if we are shifting out any of the bits being
1076202375Srdivacky          // compared.
1077202375Srdivacky          if (ConstantExpr::get(Shift->getOpcode(),
1078202375Srdivacky                                       NewCst, ShAmt) != RHS) {
1079202375Srdivacky            // If we shifted bits out, the fold is not going to work out.
1080202375Srdivacky            // As a special case, check to see if this means that the
1081202375Srdivacky            // result is always true or false now.
1082202375Srdivacky            if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1083202375Srdivacky              return ReplaceInstUsesWith(ICI,
1084202375Srdivacky                                       ConstantInt::getFalse(ICI.getContext()));
1085202375Srdivacky            if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1086202375Srdivacky              return ReplaceInstUsesWith(ICI,
1087202375Srdivacky                                       ConstantInt::getTrue(ICI.getContext()));
1088202375Srdivacky          } else {
1089202375Srdivacky            ICI.setOperand(1, NewCst);
1090202375Srdivacky            Constant *NewAndCST;
1091202375Srdivacky            if (Shift->getOpcode() == Instruction::Shl)
1092202375Srdivacky              NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1093202375Srdivacky            else
1094202375Srdivacky              NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1095202375Srdivacky            LHSI->setOperand(1, NewAndCST);
1096202375Srdivacky            LHSI->setOperand(0, Shift->getOperand(0));
1097202375Srdivacky            Worklist.Add(Shift); // Shift is dead.
1098202375Srdivacky            return &ICI;
1099202375Srdivacky          }
1100202375Srdivacky        }
1101202375Srdivacky      }
1102202375Srdivacky
1103202375Srdivacky      // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1104202375Srdivacky      // preferable because it allows the C<<Y expression to be hoisted out
1105202375Srdivacky      // of a loop if Y is invariant and X is not.
1106202375Srdivacky      if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1107202375Srdivacky          ICI.isEquality() && !Shift->isArithmeticShift() &&
1108202375Srdivacky          !isa<Constant>(Shift->getOperand(0))) {
1109202375Srdivacky        // Compute C << Y.
1110202375Srdivacky        Value *NS;
1111202375Srdivacky        if (Shift->getOpcode() == Instruction::LShr) {
1112202375Srdivacky          NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
1113202375Srdivacky        } else {
1114202375Srdivacky          // Insert a logical shift.
1115202375Srdivacky          NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
1116202375Srdivacky        }
1117202375Srdivacky
1118202375Srdivacky        // Compute X & (C << Y).
1119202375Srdivacky        Value *NewAnd =
1120202375Srdivacky          Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1121202375Srdivacky
1122202375Srdivacky        ICI.setOperand(0, NewAnd);
1123202375Srdivacky        return &ICI;
1124202375Srdivacky      }
1125202375Srdivacky    }
1126202375Srdivacky
1127202375Srdivacky    // Try to optimize things like "A[i]&42 == 0" to index computations.
1128202375Srdivacky    if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1129202375Srdivacky      if (GetElementPtrInst *GEP =
1130202375Srdivacky          dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1131202375Srdivacky        if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1132202375Srdivacky          if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1133202375Srdivacky              !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1134202375Srdivacky            ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1135202375Srdivacky            if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1136202375Srdivacky              return Res;
1137202375Srdivacky          }
1138202375Srdivacky    }
1139202375Srdivacky    break;
1140202375Srdivacky
1141202375Srdivacky  case Instruction::Or: {
1142202375Srdivacky    if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1143202375Srdivacky      break;
1144202375Srdivacky    Value *P, *Q;
1145202375Srdivacky    if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1146202375Srdivacky      // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1147202375Srdivacky      // -> and (icmp eq P, null), (icmp eq Q, null).
1148202375Srdivacky
1149202375Srdivacky      Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1150202375Srdivacky                                        Constant::getNullValue(P->getType()));
1151202375Srdivacky      Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1152202375Srdivacky                                        Constant::getNullValue(Q->getType()));
1153202375Srdivacky      Instruction *Op;
1154202375Srdivacky      if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1155202375Srdivacky        Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1156202375Srdivacky      else
1157202375Srdivacky        Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1158202375Srdivacky      return Op;
1159202375Srdivacky    }
1160202375Srdivacky    break;
1161202375Srdivacky  }
1162202375Srdivacky
1163202375Srdivacky  case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1164202375Srdivacky    ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1165202375Srdivacky    if (!ShAmt) break;
1166202375Srdivacky
1167202375Srdivacky    uint32_t TypeBits = RHSV.getBitWidth();
1168202375Srdivacky
1169202375Srdivacky    // Check that the shift amount is in range.  If not, don't perform
1170202375Srdivacky    // undefined shifts.  When the shift is visited it will be
1171202375Srdivacky    // simplified.
1172202375Srdivacky    if (ShAmt->uge(TypeBits))
1173202375Srdivacky      break;
1174202375Srdivacky
1175202375Srdivacky    if (ICI.isEquality()) {
1176202375Srdivacky      // If we are comparing against bits always shifted out, the
1177202375Srdivacky      // comparison cannot succeed.
1178202375Srdivacky      Constant *Comp =
1179202375Srdivacky        ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1180202375Srdivacky                                                                 ShAmt);
1181202375Srdivacky      if (Comp != RHS) {// Comparing against a bit that we know is zero.
1182202375Srdivacky        bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1183202375Srdivacky        Constant *Cst =
1184202375Srdivacky          ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1185202375Srdivacky        return ReplaceInstUsesWith(ICI, Cst);
1186202375Srdivacky      }
1187202375Srdivacky
1188202375Srdivacky      if (LHSI->hasOneUse()) {
1189202375Srdivacky        // Otherwise strength reduce the shift into an and.
1190202375Srdivacky        uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1191202375Srdivacky        Constant *Mask =
1192202375Srdivacky          ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
1193202375Srdivacky                                                       TypeBits-ShAmtVal));
1194202375Srdivacky
1195202375Srdivacky        Value *And =
1196202375Srdivacky          Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1197202375Srdivacky        return new ICmpInst(ICI.getPredicate(), And,
1198202375Srdivacky                            ConstantInt::get(ICI.getContext(),
1199202375Srdivacky                                             RHSV.lshr(ShAmtVal)));
1200202375Srdivacky      }
1201202375Srdivacky    }
1202202375Srdivacky
1203202375Srdivacky    // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1204202375Srdivacky    bool TrueIfSigned = false;
1205202375Srdivacky    if (LHSI->hasOneUse() &&
1206202375Srdivacky        isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1207202375Srdivacky      // (X << 31) <s 0  --> (X&1) != 0
1208202375Srdivacky      Constant *Mask = ConstantInt::get(ICI.getContext(), APInt(TypeBits, 1) <<
1209202375Srdivacky                                           (TypeBits-ShAmt->getZExtValue()-1));
1210202375Srdivacky      Value *And =
1211202375Srdivacky        Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1212202375Srdivacky      return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1213202375Srdivacky                          And, Constant::getNullValue(And->getType()));
1214202375Srdivacky    }
1215202375Srdivacky    break;
1216202375Srdivacky  }
1217202375Srdivacky
1218202375Srdivacky  case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1219202375Srdivacky  case Instruction::AShr: {
1220202375Srdivacky    // Only handle equality comparisons of shift-by-constant.
1221202375Srdivacky    ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1222202375Srdivacky    if (!ShAmt || !ICI.isEquality()) break;
1223202375Srdivacky
1224202375Srdivacky    // Check that the shift amount is in range.  If not, don't perform
1225202375Srdivacky    // undefined shifts.  When the shift is visited it will be
1226202375Srdivacky    // simplified.
1227202375Srdivacky    uint32_t TypeBits = RHSV.getBitWidth();
1228202375Srdivacky    if (ShAmt->uge(TypeBits))
1229202375Srdivacky      break;
1230202375Srdivacky
1231202375Srdivacky    uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1232202375Srdivacky
1233202375Srdivacky    // If we are comparing against bits always shifted out, the
1234202375Srdivacky    // comparison cannot succeed.
1235202375Srdivacky    APInt Comp = RHSV << ShAmtVal;
1236202375Srdivacky    if (LHSI->getOpcode() == Instruction::LShr)
1237202375Srdivacky      Comp = Comp.lshr(ShAmtVal);
1238202375Srdivacky    else
1239202375Srdivacky      Comp = Comp.ashr(ShAmtVal);
1240202375Srdivacky
1241202375Srdivacky    if (Comp != RHSV) { // Comparing against a bit that we know is zero.
1242202375Srdivacky      bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1243202375Srdivacky      Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1244202375Srdivacky                                       IsICMP_NE);
1245202375Srdivacky      return ReplaceInstUsesWith(ICI, Cst);
1246202375Srdivacky    }
1247202375Srdivacky
1248202375Srdivacky    // Otherwise, check to see if the bits shifted out are known to be zero.
1249202375Srdivacky    // If so, we can compare against the unshifted value:
1250202375Srdivacky    //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
1251202375Srdivacky    if (LHSI->hasOneUse() &&
1252202375Srdivacky        MaskedValueIsZero(LHSI->getOperand(0),
1253202375Srdivacky                          APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
1254202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1255202375Srdivacky                          ConstantExpr::getShl(RHS, ShAmt));
1256202375Srdivacky    }
1257202375Srdivacky
1258202375Srdivacky    if (LHSI->hasOneUse()) {
1259202375Srdivacky      // Otherwise strength reduce the shift into an and.
1260202375Srdivacky      APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1261202375Srdivacky      Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
1262202375Srdivacky
1263202375Srdivacky      Value *And = Builder->CreateAnd(LHSI->getOperand(0),
1264202375Srdivacky                                      Mask, LHSI->getName()+".mask");
1265202375Srdivacky      return new ICmpInst(ICI.getPredicate(), And,
1266202375Srdivacky                          ConstantExpr::getShl(RHS, ShAmt));
1267202375Srdivacky    }
1268202375Srdivacky    break;
1269202375Srdivacky  }
1270202375Srdivacky
1271202375Srdivacky  case Instruction::SDiv:
1272202375Srdivacky  case Instruction::UDiv:
1273202375Srdivacky    // Fold: icmp pred ([us]div X, C1), C2 -> range test
1274202375Srdivacky    // Fold this div into the comparison, producing a range check.
1275202375Srdivacky    // Determine, based on the divide type, what the range is being
1276202375Srdivacky    // checked.  If there is an overflow on the low or high side, remember
1277202375Srdivacky    // it, otherwise compute the range [low, hi) bounding the new value.
1278202375Srdivacky    // See: InsertRangeTest above for the kinds of replacements possible.
1279202375Srdivacky    if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1280202375Srdivacky      if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1281202375Srdivacky                                          DivRHS))
1282202375Srdivacky        return R;
1283202375Srdivacky    break;
1284202375Srdivacky
1285202375Srdivacky  case Instruction::Add:
1286202375Srdivacky    // Fold: icmp pred (add X, C1), C2
1287202375Srdivacky    if (!ICI.isEquality()) {
1288202375Srdivacky      ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1289202375Srdivacky      if (!LHSC) break;
1290202375Srdivacky      const APInt &LHSV = LHSC->getValue();
1291202375Srdivacky
1292202375Srdivacky      ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1293202375Srdivacky                            .subtract(LHSV);
1294202375Srdivacky
1295202375Srdivacky      if (ICI.isSigned()) {
1296202375Srdivacky        if (CR.getLower().isSignBit()) {
1297202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1298202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getUpper()));
1299202375Srdivacky        } else if (CR.getUpper().isSignBit()) {
1300202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1301202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getLower()));
1302202375Srdivacky        }
1303202375Srdivacky      } else {
1304202375Srdivacky        if (CR.getLower().isMinValue()) {
1305202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1306202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getUpper()));
1307202375Srdivacky        } else if (CR.getUpper().isMinValue()) {
1308202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1309202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getLower()));
1310202375Srdivacky        }
1311202375Srdivacky      }
1312202375Srdivacky    }
1313202375Srdivacky    break;
1314202375Srdivacky  }
1315202375Srdivacky
1316202375Srdivacky  // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1317202375Srdivacky  if (ICI.isEquality()) {
1318202375Srdivacky    bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1319202375Srdivacky
1320202375Srdivacky    // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1321202375Srdivacky    // the second operand is a constant, simplify a bit.
1322202375Srdivacky    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1323202375Srdivacky      switch (BO->getOpcode()) {
1324202375Srdivacky      case Instruction::SRem:
1325202375Srdivacky        // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1326202375Srdivacky        if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1327202375Srdivacky          const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1328207618Srdivacky          if (V.sgt(1) && V.isPowerOf2()) {
1329202375Srdivacky            Value *NewRem =
1330202375Srdivacky              Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1331202375Srdivacky                                  BO->getName());
1332202375Srdivacky            return new ICmpInst(ICI.getPredicate(), NewRem,
1333202375Srdivacky                                Constant::getNullValue(BO->getType()));
1334202375Srdivacky          }
1335202375Srdivacky        }
1336202375Srdivacky        break;
1337202375Srdivacky      case Instruction::Add:
1338202375Srdivacky        // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1339202375Srdivacky        if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1340202375Srdivacky          if (BO->hasOneUse())
1341202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1342202375Srdivacky                                ConstantExpr::getSub(RHS, BOp1C));
1343202375Srdivacky        } else if (RHSV == 0) {
1344202375Srdivacky          // Replace ((add A, B) != 0) with (A != -B) if A or B is
1345202375Srdivacky          // efficiently invertible, or if the add has just this one use.
1346202375Srdivacky          Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1347202375Srdivacky
1348202375Srdivacky          if (Value *NegVal = dyn_castNegVal(BOp1))
1349202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1350202375Srdivacky          else if (Value *NegVal = dyn_castNegVal(BOp0))
1351202375Srdivacky            return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1352202375Srdivacky          else if (BO->hasOneUse()) {
1353202375Srdivacky            Value *Neg = Builder->CreateNeg(BOp1);
1354202375Srdivacky            Neg->takeName(BO);
1355202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1356202375Srdivacky          }
1357202375Srdivacky        }
1358202375Srdivacky        break;
1359202375Srdivacky      case Instruction::Xor:
1360202375Srdivacky        // For the xor case, we can xor two constants together, eliminating
1361202375Srdivacky        // the explicit xor.
1362202375Srdivacky        if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1363202375Srdivacky          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1364202375Srdivacky                              ConstantExpr::getXor(RHS, BOC));
1365202375Srdivacky
1366202375Srdivacky        // FALLTHROUGH
1367202375Srdivacky      case Instruction::Sub:
1368202375Srdivacky        // Replace (([sub|xor] A, B) != 0) with (A != B)
1369202375Srdivacky        if (RHSV == 0)
1370202375Srdivacky          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1371202375Srdivacky                              BO->getOperand(1));
1372202375Srdivacky        break;
1373202375Srdivacky
1374202375Srdivacky      case Instruction::Or:
1375202375Srdivacky        // If bits are being or'd in that are not present in the constant we
1376202375Srdivacky        // are comparing against, then the comparison could never succeed!
1377202375Srdivacky        if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1378202375Srdivacky          Constant *NotCI = ConstantExpr::getNot(RHS);
1379202375Srdivacky          if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1380202375Srdivacky            return ReplaceInstUsesWith(ICI,
1381202375Srdivacky                             ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1382202375Srdivacky                                       isICMP_NE));
1383202375Srdivacky        }
1384202375Srdivacky        break;
1385202375Srdivacky
1386202375Srdivacky      case Instruction::And:
1387202375Srdivacky        if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1388202375Srdivacky          // If bits are being compared against that are and'd out, then the
1389202375Srdivacky          // comparison can never succeed!
1390202375Srdivacky          if ((RHSV & ~BOC->getValue()) != 0)
1391202375Srdivacky            return ReplaceInstUsesWith(ICI,
1392202375Srdivacky                             ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1393202375Srdivacky                                       isICMP_NE));
1394202375Srdivacky
1395202375Srdivacky          // If we have ((X & C) == C), turn it into ((X & C) != 0).
1396202375Srdivacky          if (RHS == BOC && RHSV.isPowerOf2())
1397202375Srdivacky            return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1398202375Srdivacky                                ICmpInst::ICMP_NE, LHSI,
1399202375Srdivacky                                Constant::getNullValue(RHS->getType()));
1400202375Srdivacky
1401202375Srdivacky          // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1402202375Srdivacky          if (BOC->getValue().isSignBit()) {
1403202375Srdivacky            Value *X = BO->getOperand(0);
1404202375Srdivacky            Constant *Zero = Constant::getNullValue(X->getType());
1405202375Srdivacky            ICmpInst::Predicate pred = isICMP_NE ?
1406202375Srdivacky              ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1407202375Srdivacky            return new ICmpInst(pred, X, Zero);
1408202375Srdivacky          }
1409202375Srdivacky
1410202375Srdivacky          // ((X & ~7) == 0) --> X < 8
1411202375Srdivacky          if (RHSV == 0 && isHighOnes(BOC)) {
1412202375Srdivacky            Value *X = BO->getOperand(0);
1413202375Srdivacky            Constant *NegX = ConstantExpr::getNeg(BOC);
1414202375Srdivacky            ICmpInst::Predicate pred = isICMP_NE ?
1415202375Srdivacky              ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1416202375Srdivacky            return new ICmpInst(pred, X, NegX);
1417202375Srdivacky          }
1418202375Srdivacky        }
1419202375Srdivacky      default: break;
1420202375Srdivacky      }
1421202375Srdivacky    } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1422202375Srdivacky      // Handle icmp {eq|ne} <intrinsic>, intcst.
1423202375Srdivacky      switch (II->getIntrinsicID()) {
1424202375Srdivacky      case Intrinsic::bswap:
1425202375Srdivacky        Worklist.Add(II);
1426210299Sed        ICI.setOperand(0, II->getArgOperand(0));
1427202375Srdivacky        ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1428202375Srdivacky        return &ICI;
1429202375Srdivacky      case Intrinsic::ctlz:
1430202375Srdivacky      case Intrinsic::cttz:
1431202375Srdivacky        // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1432202375Srdivacky        if (RHSV == RHS->getType()->getBitWidth()) {
1433202375Srdivacky          Worklist.Add(II);
1434210299Sed          ICI.setOperand(0, II->getArgOperand(0));
1435202375Srdivacky          ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1436202375Srdivacky          return &ICI;
1437202375Srdivacky        }
1438202375Srdivacky        break;
1439202375Srdivacky      case Intrinsic::ctpop:
1440202375Srdivacky        // popcount(A) == 0  ->  A == 0 and likewise for !=
1441202375Srdivacky        if (RHS->isZero()) {
1442202375Srdivacky          Worklist.Add(II);
1443210299Sed          ICI.setOperand(0, II->getArgOperand(0));
1444202375Srdivacky          ICI.setOperand(1, RHS);
1445202375Srdivacky          return &ICI;
1446202375Srdivacky        }
1447202375Srdivacky        break;
1448202375Srdivacky      default:
1449210299Sed        break;
1450202375Srdivacky      }
1451202375Srdivacky    }
1452202375Srdivacky  }
1453202375Srdivacky  return 0;
1454202375Srdivacky}
1455202375Srdivacky
1456202375Srdivacky/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1457202375Srdivacky/// We only handle extending casts so far.
1458202375Srdivacky///
1459202375SrdivackyInstruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1460202375Srdivacky  const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1461202375Srdivacky  Value *LHSCIOp        = LHSCI->getOperand(0);
1462202375Srdivacky  const Type *SrcTy     = LHSCIOp->getType();
1463202375Srdivacky  const Type *DestTy    = LHSCI->getType();
1464202375Srdivacky  Value *RHSCIOp;
1465202375Srdivacky
1466202375Srdivacky  // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1467202375Srdivacky  // integer type is the same size as the pointer type.
1468202375Srdivacky  if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1469202375Srdivacky      TD->getPointerSizeInBits() ==
1470202375Srdivacky         cast<IntegerType>(DestTy)->getBitWidth()) {
1471202375Srdivacky    Value *RHSOp = 0;
1472202375Srdivacky    if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1473202375Srdivacky      RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1474202375Srdivacky    } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1475202375Srdivacky      RHSOp = RHSC->getOperand(0);
1476202375Srdivacky      // If the pointer types don't match, insert a bitcast.
1477202375Srdivacky      if (LHSCIOp->getType() != RHSOp->getType())
1478202375Srdivacky        RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1479202375Srdivacky    }
1480202375Srdivacky
1481202375Srdivacky    if (RHSOp)
1482202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1483202375Srdivacky  }
1484202375Srdivacky
1485202375Srdivacky  // The code below only handles extension cast instructions, so far.
1486202375Srdivacky  // Enforce this.
1487202375Srdivacky  if (LHSCI->getOpcode() != Instruction::ZExt &&
1488202375Srdivacky      LHSCI->getOpcode() != Instruction::SExt)
1489202375Srdivacky    return 0;
1490202375Srdivacky
1491202375Srdivacky  bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1492202375Srdivacky  bool isSignedCmp = ICI.isSigned();
1493202375Srdivacky
1494202375Srdivacky  if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1495202375Srdivacky    // Not an extension from the same type?
1496202375Srdivacky    RHSCIOp = CI->getOperand(0);
1497202375Srdivacky    if (RHSCIOp->getType() != LHSCIOp->getType())
1498202375Srdivacky      return 0;
1499202375Srdivacky
1500202375Srdivacky    // If the signedness of the two casts doesn't agree (i.e. one is a sext
1501202375Srdivacky    // and the other is a zext), then we can't handle this.
1502202375Srdivacky    if (CI->getOpcode() != LHSCI->getOpcode())
1503202375Srdivacky      return 0;
1504202375Srdivacky
1505202375Srdivacky    // Deal with equality cases early.
1506202375Srdivacky    if (ICI.isEquality())
1507202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1508202375Srdivacky
1509202375Srdivacky    // A signed comparison of sign extended values simplifies into a
1510202375Srdivacky    // signed comparison.
1511202375Srdivacky    if (isSignedCmp && isSignedExt)
1512202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1513202375Srdivacky
1514202375Srdivacky    // The other three cases all fold into an unsigned comparison.
1515202375Srdivacky    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1516202375Srdivacky  }
1517202375Srdivacky
1518202375Srdivacky  // If we aren't dealing with a constant on the RHS, exit early
1519202375Srdivacky  ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1520202375Srdivacky  if (!CI)
1521202375Srdivacky    return 0;
1522202375Srdivacky
1523202375Srdivacky  // Compute the constant that would happen if we truncated to SrcTy then
1524202375Srdivacky  // reextended to DestTy.
1525202375Srdivacky  Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1526202375Srdivacky  Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1527202375Srdivacky                                                Res1, DestTy);
1528202375Srdivacky
1529202375Srdivacky  // If the re-extended constant didn't change...
1530202375Srdivacky  if (Res2 == CI) {
1531202375Srdivacky    // Deal with equality cases early.
1532202375Srdivacky    if (ICI.isEquality())
1533202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1534202375Srdivacky
1535202375Srdivacky    // A signed comparison of sign extended values simplifies into a
1536202375Srdivacky    // signed comparison.
1537202375Srdivacky    if (isSignedExt && isSignedCmp)
1538202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1539202375Srdivacky
1540202375Srdivacky    // The other three cases all fold into an unsigned comparison.
1541202375Srdivacky    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1542202375Srdivacky  }
1543202375Srdivacky
1544202375Srdivacky  // The re-extended constant changed so the constant cannot be represented
1545202375Srdivacky  // in the shorter type. Consequently, we cannot emit a simple comparison.
1546202375Srdivacky
1547202375Srdivacky  // First, handle some easy cases. We know the result cannot be equal at this
1548202375Srdivacky  // point so handle the ICI.isEquality() cases
1549202375Srdivacky  if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1550202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
1551202375Srdivacky  if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1552202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
1553202375Srdivacky
1554202375Srdivacky  // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1555202375Srdivacky  // should have been folded away previously and not enter in here.
1556202375Srdivacky  Value *Result;
1557202375Srdivacky  if (isSignedCmp) {
1558202375Srdivacky    // We're performing a signed comparison.
1559202375Srdivacky    if (cast<ConstantInt>(CI)->getValue().isNegative())
1560202375Srdivacky      Result = ConstantInt::getFalse(ICI.getContext()); // X < (small) --> false
1561202375Srdivacky    else
1562202375Srdivacky      Result = ConstantInt::getTrue(ICI.getContext());  // X < (large) --> true
1563202375Srdivacky  } else {
1564202375Srdivacky    // We're performing an unsigned comparison.
1565202375Srdivacky    if (isSignedExt) {
1566202375Srdivacky      // We're performing an unsigned comp with a sign extended value.
1567202375Srdivacky      // This is true if the input is >= 0. [aka >s -1]
1568202375Srdivacky      Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1569202375Srdivacky      Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1570202375Srdivacky    } else {
1571202375Srdivacky      // Unsigned extend & unsigned compare -> always true.
1572202375Srdivacky      Result = ConstantInt::getTrue(ICI.getContext());
1573202375Srdivacky    }
1574202375Srdivacky  }
1575202375Srdivacky
1576202375Srdivacky  // Finally, return the value computed.
1577202375Srdivacky  if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
1578202375Srdivacky      ICI.getPredicate() == ICmpInst::ICMP_SLT)
1579202375Srdivacky    return ReplaceInstUsesWith(ICI, Result);
1580202375Srdivacky
1581202375Srdivacky  assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
1582202375Srdivacky          ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
1583202375Srdivacky         "ICmp should be folded!");
1584202375Srdivacky  if (Constant *CI = dyn_cast<Constant>(Result))
1585202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
1586202375Srdivacky  return BinaryOperator::CreateNot(Result);
1587202375Srdivacky}
1588202375Srdivacky
1589202375Srdivacky
1590202375Srdivacky
1591202375SrdivackyInstruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1592202375Srdivacky  bool Changed = false;
1593203954Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1594202375Srdivacky
1595202375Srdivacky  /// Orders the operands of the compare so that they are listed from most
1596202375Srdivacky  /// complex to least complex.  This puts constants before unary operators,
1597202375Srdivacky  /// before binary operators.
1598203954Srdivacky  if (getComplexity(Op0) < getComplexity(Op1)) {
1599202375Srdivacky    I.swapOperands();
1600203954Srdivacky    std::swap(Op0, Op1);
1601202375Srdivacky    Changed = true;
1602202375Srdivacky  }
1603202375Srdivacky
1604202375Srdivacky  if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1605202375Srdivacky    return ReplaceInstUsesWith(I, V);
1606202375Srdivacky
1607202375Srdivacky  const Type *Ty = Op0->getType();
1608202375Srdivacky
1609202375Srdivacky  // icmp's with boolean values can always be turned into bitwise operations
1610203954Srdivacky  if (Ty->isIntegerTy(1)) {
1611202375Srdivacky    switch (I.getPredicate()) {
1612202375Srdivacky    default: llvm_unreachable("Invalid icmp instruction!");
1613202375Srdivacky    case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
1614202375Srdivacky      Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1615202375Srdivacky      return BinaryOperator::CreateNot(Xor);
1616202375Srdivacky    }
1617202375Srdivacky    case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
1618202375Srdivacky      return BinaryOperator::CreateXor(Op0, Op1);
1619202375Srdivacky
1620202375Srdivacky    case ICmpInst::ICMP_UGT:
1621202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
1622202375Srdivacky      // FALL THROUGH
1623202375Srdivacky    case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
1624202375Srdivacky      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1625202375Srdivacky      return BinaryOperator::CreateAnd(Not, Op1);
1626202375Srdivacky    }
1627202375Srdivacky    case ICmpInst::ICMP_SGT:
1628202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
1629202375Srdivacky      // FALL THROUGH
1630202375Srdivacky    case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
1631202375Srdivacky      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1632202375Srdivacky      return BinaryOperator::CreateAnd(Not, Op0);
1633202375Srdivacky    }
1634202375Srdivacky    case ICmpInst::ICMP_UGE:
1635202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
1636202375Srdivacky      // FALL THROUGH
1637202375Srdivacky    case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
1638202375Srdivacky      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1639202375Srdivacky      return BinaryOperator::CreateOr(Not, Op1);
1640202375Srdivacky    }
1641202375Srdivacky    case ICmpInst::ICMP_SGE:
1642202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
1643202375Srdivacky      // FALL THROUGH
1644202375Srdivacky    case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
1645202375Srdivacky      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1646202375Srdivacky      return BinaryOperator::CreateOr(Not, Op0);
1647202375Srdivacky    }
1648202375Srdivacky    }
1649202375Srdivacky  }
1650202375Srdivacky
1651202375Srdivacky  unsigned BitWidth = 0;
1652202375Srdivacky  if (TD)
1653202375Srdivacky    BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
1654203954Srdivacky  else if (Ty->isIntOrIntVectorTy())
1655202375Srdivacky    BitWidth = Ty->getScalarSizeInBits();
1656202375Srdivacky
1657202375Srdivacky  bool isSignBit = false;
1658202375Srdivacky
1659202375Srdivacky  // See if we are doing a comparison with a constant.
1660202375Srdivacky  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1661202375Srdivacky    Value *A = 0, *B = 0;
1662202375Srdivacky
1663202375Srdivacky    // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1664202375Srdivacky    if (I.isEquality() && CI->isZero() &&
1665202375Srdivacky        match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1666202375Srdivacky      // (icmp cond A B) if cond is equality
1667202375Srdivacky      return new ICmpInst(I.getPredicate(), A, B);
1668202375Srdivacky    }
1669202375Srdivacky
1670202375Srdivacky    // If we have an icmp le or icmp ge instruction, turn it into the
1671202375Srdivacky    // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
1672202375Srdivacky    // them being folded in the code below.  The SimplifyICmpInst code has
1673202375Srdivacky    // already handled the edge cases for us, so we just assert on them.
1674202375Srdivacky    switch (I.getPredicate()) {
1675202375Srdivacky    default: break;
1676202375Srdivacky    case ICmpInst::ICMP_ULE:
1677202375Srdivacky      assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
1678202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1679202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
1680202375Srdivacky    case ICmpInst::ICMP_SLE:
1681202375Srdivacky      assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
1682202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1683202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
1684202375Srdivacky    case ICmpInst::ICMP_UGE:
1685202375Srdivacky      assert(!CI->isMinValue(false));                  // A >=u MIN -> TRUE
1686202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1687202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
1688202375Srdivacky    case ICmpInst::ICMP_SGE:
1689202375Srdivacky      assert(!CI->isMinValue(true));                   // A >=s MIN -> TRUE
1690202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1691202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
1692202375Srdivacky    }
1693202375Srdivacky
1694202375Srdivacky    // If this comparison is a normal comparison, it demands all
1695202375Srdivacky    // bits, if it is a sign bit comparison, it only demands the sign bit.
1696202375Srdivacky    bool UnusedBit;
1697202375Srdivacky    isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1698202375Srdivacky  }
1699202375Srdivacky
1700202375Srdivacky  // See if we can fold the comparison based on range information we can get
1701202375Srdivacky  // by checking whether bits are known to be zero or one in the input.
1702202375Srdivacky  if (BitWidth != 0) {
1703202375Srdivacky    APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1704202375Srdivacky    APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1705202375Srdivacky
1706202375Srdivacky    if (SimplifyDemandedBits(I.getOperandUse(0),
1707202375Srdivacky                             isSignBit ? APInt::getSignBit(BitWidth)
1708202375Srdivacky                                       : APInt::getAllOnesValue(BitWidth),
1709202375Srdivacky                             Op0KnownZero, Op0KnownOne, 0))
1710202375Srdivacky      return &I;
1711202375Srdivacky    if (SimplifyDemandedBits(I.getOperandUse(1),
1712202375Srdivacky                             APInt::getAllOnesValue(BitWidth),
1713202375Srdivacky                             Op1KnownZero, Op1KnownOne, 0))
1714202375Srdivacky      return &I;
1715202375Srdivacky
1716202375Srdivacky    // Given the known and unknown bits, compute a range that the LHS could be
1717202375Srdivacky    // in.  Compute the Min, Max and RHS values based on the known bits. For the
1718202375Srdivacky    // EQ and NE we use unsigned values.
1719202375Srdivacky    APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1720202375Srdivacky    APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1721202375Srdivacky    if (I.isSigned()) {
1722202375Srdivacky      ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1723202375Srdivacky                                             Op0Min, Op0Max);
1724202375Srdivacky      ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1725202375Srdivacky                                             Op1Min, Op1Max);
1726202375Srdivacky    } else {
1727202375Srdivacky      ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1728202375Srdivacky                                               Op0Min, Op0Max);
1729202375Srdivacky      ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1730202375Srdivacky                                               Op1Min, Op1Max);
1731202375Srdivacky    }
1732202375Srdivacky
1733202375Srdivacky    // If Min and Max are known to be the same, then SimplifyDemandedBits
1734202375Srdivacky    // figured out that the LHS is a constant.  Just constant fold this now so
1735202375Srdivacky    // that code below can assume that Min != Max.
1736202375Srdivacky    if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1737202375Srdivacky      return new ICmpInst(I.getPredicate(),
1738202375Srdivacky                          ConstantInt::get(I.getContext(), Op0Min), Op1);
1739202375Srdivacky    if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1740202375Srdivacky      return new ICmpInst(I.getPredicate(), Op0,
1741202375Srdivacky                          ConstantInt::get(I.getContext(), Op1Min));
1742202375Srdivacky
1743202375Srdivacky    // Based on the range information we know about the LHS, see if we can
1744202375Srdivacky    // simplify this comparison.  For example, (x&4) < 8  is always true.
1745202375Srdivacky    switch (I.getPredicate()) {
1746202375Srdivacky    default: llvm_unreachable("Unknown icmp opcode!");
1747202375Srdivacky    case ICmpInst::ICMP_EQ:
1748202375Srdivacky      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1749202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1750202375Srdivacky      break;
1751202375Srdivacky    case ICmpInst::ICMP_NE:
1752202375Srdivacky      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1753202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1754202375Srdivacky      break;
1755202375Srdivacky    case ICmpInst::ICMP_ULT:
1756202375Srdivacky      if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
1757202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1758202375Srdivacky      if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
1759202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1760202375Srdivacky      if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
1761202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
1762202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1763202375Srdivacky        if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
1764202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
1765202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
1766202375Srdivacky
1767202375Srdivacky        // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
1768202375Srdivacky        if (CI->isMinValue(true))
1769202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1770202375Srdivacky                           Constant::getAllOnesValue(Op0->getType()));
1771202375Srdivacky      }
1772202375Srdivacky      break;
1773202375Srdivacky    case ICmpInst::ICMP_UGT:
1774202375Srdivacky      if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
1775202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1776202375Srdivacky      if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
1777202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1778202375Srdivacky
1779202375Srdivacky      if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
1780202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
1781202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1782202375Srdivacky        if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
1783202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
1784202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
1785202375Srdivacky
1786202375Srdivacky        // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
1787202375Srdivacky        if (CI->isMaxValue(true))
1788202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1789202375Srdivacky                              Constant::getNullValue(Op0->getType()));
1790202375Srdivacky      }
1791202375Srdivacky      break;
1792202375Srdivacky    case ICmpInst::ICMP_SLT:
1793202375Srdivacky      if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
1794202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1795202375Srdivacky      if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
1796202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1797202375Srdivacky      if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
1798202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
1799202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1800202375Srdivacky        if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
1801202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
1802202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
1803202375Srdivacky      }
1804202375Srdivacky      break;
1805202375Srdivacky    case ICmpInst::ICMP_SGT:
1806202375Srdivacky      if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
1807202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1808202375Srdivacky      if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
1809202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1810202375Srdivacky
1811202375Srdivacky      if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
1812202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
1813202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1814202375Srdivacky        if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
1815202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
1816202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
1817202375Srdivacky      }
1818202375Srdivacky      break;
1819202375Srdivacky    case ICmpInst::ICMP_SGE:
1820202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
1821202375Srdivacky      if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
1822202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1823202375Srdivacky      if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
1824202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1825202375Srdivacky      break;
1826202375Srdivacky    case ICmpInst::ICMP_SLE:
1827202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
1828202375Srdivacky      if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
1829202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1830202375Srdivacky      if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
1831202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1832202375Srdivacky      break;
1833202375Srdivacky    case ICmpInst::ICMP_UGE:
1834202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
1835202375Srdivacky      if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
1836202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1837202375Srdivacky      if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
1838202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1839202375Srdivacky      break;
1840202375Srdivacky    case ICmpInst::ICMP_ULE:
1841202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
1842202375Srdivacky      if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
1843202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1844202375Srdivacky      if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
1845202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1846202375Srdivacky      break;
1847202375Srdivacky    }
1848202375Srdivacky
1849202375Srdivacky    // Turn a signed comparison into an unsigned one if both operands
1850202375Srdivacky    // are known to have the same sign.
1851202375Srdivacky    if (I.isSigned() &&
1852202375Srdivacky        ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
1853202375Srdivacky         (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
1854202375Srdivacky      return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
1855202375Srdivacky  }
1856202375Srdivacky
1857202375Srdivacky  // Test if the ICmpInst instruction is used exclusively by a select as
1858202375Srdivacky  // part of a minimum or maximum operation. If so, refrain from doing
1859202375Srdivacky  // any other folding. This helps out other analyses which understand
1860202375Srdivacky  // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
1861202375Srdivacky  // and CodeGen. And in this case, at least one of the comparison
1862202375Srdivacky  // operands has at least one user besides the compare (the select),
1863202375Srdivacky  // which would often largely negate the benefit of folding anyway.
1864202375Srdivacky  if (I.hasOneUse())
1865202375Srdivacky    if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
1866202375Srdivacky      if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
1867202375Srdivacky          (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
1868202375Srdivacky        return 0;
1869202375Srdivacky
1870202375Srdivacky  // See if we are doing a comparison between a constant and an instruction that
1871202375Srdivacky  // can be folded into the comparison.
1872202375Srdivacky  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1873202375Srdivacky    // Since the RHS is a ConstantInt (CI), if the left hand side is an
1874202375Srdivacky    // instruction, see if that instruction also has constants so that the
1875202375Srdivacky    // instruction can be folded into the icmp
1876202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1877202375Srdivacky      if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
1878202375Srdivacky        return Res;
1879202375Srdivacky  }
1880202375Srdivacky
1881202375Srdivacky  // Handle icmp with constant (but not simple integer constant) RHS
1882202375Srdivacky  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
1883202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1884202375Srdivacky      switch (LHSI->getOpcode()) {
1885202375Srdivacky      case Instruction::GetElementPtr:
1886202375Srdivacky          // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
1887202375Srdivacky        if (RHSC->isNullValue() &&
1888202375Srdivacky            cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
1889202375Srdivacky          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
1890202375Srdivacky                  Constant::getNullValue(LHSI->getOperand(0)->getType()));
1891202375Srdivacky        break;
1892202375Srdivacky      case Instruction::PHI:
1893202375Srdivacky        // Only fold icmp into the PHI if the phi and icmp are in the same
1894202375Srdivacky        // block.  If in the same block, we're encouraging jump threading.  If
1895202375Srdivacky        // not, we are just pessimizing the code by making an i1 phi.
1896202375Srdivacky        if (LHSI->getParent() == I.getParent())
1897202375Srdivacky          if (Instruction *NV = FoldOpIntoPhi(I, true))
1898202375Srdivacky            return NV;
1899202375Srdivacky        break;
1900202375Srdivacky      case Instruction::Select: {
1901202375Srdivacky        // If either operand of the select is a constant, we can fold the
1902202375Srdivacky        // comparison into the select arms, which will cause one to be
1903202375Srdivacky        // constant folded and the select turned into a bitwise or.
1904202375Srdivacky        Value *Op1 = 0, *Op2 = 0;
1905202375Srdivacky        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
1906202375Srdivacky          Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
1907202375Srdivacky        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
1908202375Srdivacky          Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
1909202375Srdivacky
1910202375Srdivacky        // We only want to perform this transformation if it will not lead to
1911202375Srdivacky        // additional code. This is true if either both sides of the select
1912202375Srdivacky        // fold to a constant (in which case the icmp is replaced with a select
1913202375Srdivacky        // which will usually simplify) or this is the only user of the
1914202375Srdivacky        // select (in which case we are trading a select+icmp for a simpler
1915202375Srdivacky        // select+icmp).
1916202375Srdivacky        if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
1917202375Srdivacky          if (!Op1)
1918202375Srdivacky            Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
1919202375Srdivacky                                      RHSC, I.getName());
1920202375Srdivacky          if (!Op2)
1921202375Srdivacky            Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
1922202375Srdivacky                                      RHSC, I.getName());
1923202375Srdivacky          return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
1924202375Srdivacky        }
1925202375Srdivacky        break;
1926202375Srdivacky      }
1927202375Srdivacky      case Instruction::IntToPtr:
1928202375Srdivacky        // icmp pred inttoptr(X), null -> icmp pred X, 0
1929202375Srdivacky        if (RHSC->isNullValue() && TD &&
1930202375Srdivacky            TD->getIntPtrType(RHSC->getContext()) ==
1931202375Srdivacky               LHSI->getOperand(0)->getType())
1932202375Srdivacky          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
1933202375Srdivacky                        Constant::getNullValue(LHSI->getOperand(0)->getType()));
1934202375Srdivacky        break;
1935202375Srdivacky
1936202375Srdivacky      case Instruction::Load:
1937202375Srdivacky        // Try to optimize things like "A[i] > 4" to index computations.
1938202375Srdivacky        if (GetElementPtrInst *GEP =
1939202375Srdivacky              dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
1940202375Srdivacky          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1941202375Srdivacky            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1942202375Srdivacky                !cast<LoadInst>(LHSI)->isVolatile())
1943202375Srdivacky              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
1944202375Srdivacky                return Res;
1945202375Srdivacky        }
1946202375Srdivacky        break;
1947202375Srdivacky      }
1948202375Srdivacky  }
1949202375Srdivacky
1950202375Srdivacky  // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
1951202375Srdivacky  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
1952202375Srdivacky    if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
1953202375Srdivacky      return NI;
1954202375Srdivacky  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
1955202375Srdivacky    if (Instruction *NI = FoldGEPICmp(GEP, Op0,
1956202375Srdivacky                           ICmpInst::getSwappedPredicate(I.getPredicate()), I))
1957202375Srdivacky      return NI;
1958202375Srdivacky
1959202375Srdivacky  // Test to see if the operands of the icmp are casted versions of other
1960202375Srdivacky  // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
1961202375Srdivacky  // now.
1962202375Srdivacky  if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
1963204642Srdivacky    if (Op0->getType()->isPointerTy() &&
1964202375Srdivacky        (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
1965202375Srdivacky      // We keep moving the cast from the left operand over to the right
1966202375Srdivacky      // operand, where it can often be eliminated completely.
1967202375Srdivacky      Op0 = CI->getOperand(0);
1968202375Srdivacky
1969202375Srdivacky      // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
1970202375Srdivacky      // so eliminate it as well.
1971202375Srdivacky      if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
1972202375Srdivacky        Op1 = CI2->getOperand(0);
1973202375Srdivacky
1974202375Srdivacky      // If Op1 is a constant, we can fold the cast into the constant.
1975202375Srdivacky      if (Op0->getType() != Op1->getType()) {
1976202375Srdivacky        if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1977202375Srdivacky          Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
1978202375Srdivacky        } else {
1979202375Srdivacky          // Otherwise, cast the RHS right before the icmp
1980202375Srdivacky          Op1 = Builder->CreateBitCast(Op1, Op0->getType());
1981202375Srdivacky        }
1982202375Srdivacky      }
1983202375Srdivacky      return new ICmpInst(I.getPredicate(), Op0, Op1);
1984202375Srdivacky    }
1985202375Srdivacky  }
1986202375Srdivacky
1987202375Srdivacky  if (isa<CastInst>(Op0)) {
1988202375Srdivacky    // Handle the special case of: icmp (cast bool to X), <cst>
1989202375Srdivacky    // This comes up when you have code like
1990202375Srdivacky    //   int X = A < B;
1991202375Srdivacky    //   if (X) ...
1992202375Srdivacky    // For generality, we handle any zero-extension of any operand comparison
1993202375Srdivacky    // with a constant or another cast from the same type.
1994202375Srdivacky    if (isa<Constant>(Op1) || isa<CastInst>(Op1))
1995202375Srdivacky      if (Instruction *R = visitICmpInstWithCastAndCast(I))
1996202375Srdivacky        return R;
1997202375Srdivacky  }
1998202375Srdivacky
1999202375Srdivacky  // See if it's the same type of instruction on the left and right.
2000202375Srdivacky  if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2001202375Srdivacky    if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2002202375Srdivacky      if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
2003202375Srdivacky          Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
2004202375Srdivacky        switch (Op0I->getOpcode()) {
2005202375Srdivacky        default: break;
2006202375Srdivacky        case Instruction::Add:
2007202375Srdivacky        case Instruction::Sub:
2008202375Srdivacky        case Instruction::Xor:
2009202375Srdivacky          if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2010202375Srdivacky            return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
2011202375Srdivacky                                Op1I->getOperand(0));
2012202375Srdivacky          // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2013202375Srdivacky          if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2014202375Srdivacky            if (CI->getValue().isSignBit()) {
2015202375Srdivacky              ICmpInst::Predicate Pred = I.isSigned()
2016202375Srdivacky                                             ? I.getUnsignedPredicate()
2017202375Srdivacky                                             : I.getSignedPredicate();
2018202375Srdivacky              return new ICmpInst(Pred, Op0I->getOperand(0),
2019202375Srdivacky                                  Op1I->getOperand(0));
2020202375Srdivacky            }
2021202375Srdivacky
2022202375Srdivacky            if (CI->getValue().isMaxSignedValue()) {
2023202375Srdivacky              ICmpInst::Predicate Pred = I.isSigned()
2024202375Srdivacky                                             ? I.getUnsignedPredicate()
2025202375Srdivacky                                             : I.getSignedPredicate();
2026202375Srdivacky              Pred = I.getSwappedPredicate(Pred);
2027202375Srdivacky              return new ICmpInst(Pred, Op0I->getOperand(0),
2028202375Srdivacky                                  Op1I->getOperand(0));
2029202375Srdivacky            }
2030202375Srdivacky          }
2031202375Srdivacky          break;
2032202375Srdivacky        case Instruction::Mul:
2033202375Srdivacky          if (!I.isEquality())
2034202375Srdivacky            break;
2035202375Srdivacky
2036202375Srdivacky          if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2037202375Srdivacky            // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2038202375Srdivacky            // Mask = -1 >> count-trailing-zeros(Cst).
2039202375Srdivacky            if (!CI->isZero() && !CI->isOne()) {
2040202375Srdivacky              const APInt &AP = CI->getValue();
2041202375Srdivacky              ConstantInt *Mask = ConstantInt::get(I.getContext(),
2042202375Srdivacky                                      APInt::getLowBitsSet(AP.getBitWidth(),
2043202375Srdivacky                                                           AP.getBitWidth() -
2044202375Srdivacky                                                      AP.countTrailingZeros()));
2045202375Srdivacky              Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
2046202375Srdivacky              Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
2047202375Srdivacky              return new ICmpInst(I.getPredicate(), And1, And2);
2048202375Srdivacky            }
2049202375Srdivacky          }
2050202375Srdivacky          break;
2051202375Srdivacky        }
2052202375Srdivacky      }
2053202375Srdivacky    }
2054202375Srdivacky  }
2055202375Srdivacky
2056202375Srdivacky  // ~x < ~y --> y < x
2057202375Srdivacky  { Value *A, *B;
2058202375Srdivacky    if (match(Op0, m_Not(m_Value(A))) &&
2059202375Srdivacky        match(Op1, m_Not(m_Value(B))))
2060202375Srdivacky      return new ICmpInst(I.getPredicate(), B, A);
2061202375Srdivacky  }
2062202375Srdivacky
2063202375Srdivacky  if (I.isEquality()) {
2064202375Srdivacky    Value *A, *B, *C, *D;
2065202375Srdivacky
2066202375Srdivacky    // -x == -y --> x == y
2067202375Srdivacky    if (match(Op0, m_Neg(m_Value(A))) &&
2068202375Srdivacky        match(Op1, m_Neg(m_Value(B))))
2069202375Srdivacky      return new ICmpInst(I.getPredicate(), A, B);
2070202375Srdivacky
2071202375Srdivacky    if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2072202375Srdivacky      if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2073202375Srdivacky        Value *OtherVal = A == Op1 ? B : A;
2074202375Srdivacky        return new ICmpInst(I.getPredicate(), OtherVal,
2075202375Srdivacky                            Constant::getNullValue(A->getType()));
2076202375Srdivacky      }
2077202375Srdivacky
2078202375Srdivacky      if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2079202375Srdivacky        // A^c1 == C^c2 --> A == C^(c1^c2)
2080202375Srdivacky        ConstantInt *C1, *C2;
2081202375Srdivacky        if (match(B, m_ConstantInt(C1)) &&
2082202375Srdivacky            match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2083202375Srdivacky          Constant *NC = ConstantInt::get(I.getContext(),
2084202375Srdivacky                                          C1->getValue() ^ C2->getValue());
2085202375Srdivacky          Value *Xor = Builder->CreateXor(C, NC, "tmp");
2086202375Srdivacky          return new ICmpInst(I.getPredicate(), A, Xor);
2087202375Srdivacky        }
2088202375Srdivacky
2089202375Srdivacky        // A^B == A^D -> B == D
2090202375Srdivacky        if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2091202375Srdivacky        if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2092202375Srdivacky        if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2093202375Srdivacky        if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2094202375Srdivacky      }
2095202375Srdivacky    }
2096202375Srdivacky
2097202375Srdivacky    if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2098202375Srdivacky        (A == Op0 || B == Op0)) {
2099202375Srdivacky      // A == (A^B)  ->  B == 0
2100202375Srdivacky      Value *OtherVal = A == Op0 ? B : A;
2101202375Srdivacky      return new ICmpInst(I.getPredicate(), OtherVal,
2102202375Srdivacky                          Constant::getNullValue(A->getType()));
2103202375Srdivacky    }
2104202375Srdivacky
2105202375Srdivacky    // (A-B) == A  ->  B == 0
2106202375Srdivacky    if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
2107202375Srdivacky      return new ICmpInst(I.getPredicate(), B,
2108202375Srdivacky                          Constant::getNullValue(B->getType()));
2109202375Srdivacky
2110202375Srdivacky    // A == (A-B)  ->  B == 0
2111202375Srdivacky    if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
2112202375Srdivacky      return new ICmpInst(I.getPredicate(), B,
2113202375Srdivacky                          Constant::getNullValue(B->getType()));
2114202375Srdivacky
2115202375Srdivacky    // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2116202375Srdivacky    if (Op0->hasOneUse() && Op1->hasOneUse() &&
2117202375Srdivacky        match(Op0, m_And(m_Value(A), m_Value(B))) &&
2118202375Srdivacky        match(Op1, m_And(m_Value(C), m_Value(D)))) {
2119202375Srdivacky      Value *X = 0, *Y = 0, *Z = 0;
2120202375Srdivacky
2121202375Srdivacky      if (A == C) {
2122202375Srdivacky        X = B; Y = D; Z = A;
2123202375Srdivacky      } else if (A == D) {
2124202375Srdivacky        X = B; Y = C; Z = A;
2125202375Srdivacky      } else if (B == C) {
2126202375Srdivacky        X = A; Y = D; Z = B;
2127202375Srdivacky      } else if (B == D) {
2128202375Srdivacky        X = A; Y = C; Z = B;
2129202375Srdivacky      }
2130202375Srdivacky
2131202375Srdivacky      if (X) {   // Build (X^Y) & Z
2132202375Srdivacky        Op1 = Builder->CreateXor(X, Y, "tmp");
2133202375Srdivacky        Op1 = Builder->CreateAnd(Op1, Z, "tmp");
2134202375Srdivacky        I.setOperand(0, Op1);
2135202375Srdivacky        I.setOperand(1, Constant::getNullValue(Op1->getType()));
2136202375Srdivacky        return &I;
2137202375Srdivacky      }
2138202375Srdivacky    }
2139202375Srdivacky  }
2140202375Srdivacky
2141202375Srdivacky  {
2142202375Srdivacky    Value *X; ConstantInt *Cst;
2143202375Srdivacky    // icmp X+Cst, X
2144202375Srdivacky    if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2145202375Srdivacky      return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2146202375Srdivacky
2147202375Srdivacky    // icmp X, X+Cst
2148202375Srdivacky    if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2149202375Srdivacky      return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2150202375Srdivacky  }
2151202375Srdivacky  return Changed ? &I : 0;
2152202375Srdivacky}
2153202375Srdivacky
2154202375Srdivacky
2155202375Srdivacky
2156202375Srdivacky
2157202375Srdivacky
2158202375Srdivacky
2159202375Srdivacky/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2160202375Srdivacky///
2161202375SrdivackyInstruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2162202375Srdivacky                                                Instruction *LHSI,
2163202375Srdivacky                                                Constant *RHSC) {
2164202375Srdivacky  if (!isa<ConstantFP>(RHSC)) return 0;
2165202375Srdivacky  const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2166202375Srdivacky
2167202375Srdivacky  // Get the width of the mantissa.  We don't want to hack on conversions that
2168202375Srdivacky  // might lose information from the integer, e.g. "i64 -> float"
2169202375Srdivacky  int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2170202375Srdivacky  if (MantissaWidth == -1) return 0;  // Unknown.
2171202375Srdivacky
2172202375Srdivacky  // Check to see that the input is converted from an integer type that is small
2173202375Srdivacky  // enough that preserves all bits.  TODO: check here for "known" sign bits.
2174202375Srdivacky  // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2175202375Srdivacky  unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2176202375Srdivacky
2177202375Srdivacky  // If this is a uitofp instruction, we need an extra bit to hold the sign.
2178202375Srdivacky  bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2179202375Srdivacky  if (LHSUnsigned)
2180202375Srdivacky    ++InputSize;
2181202375Srdivacky
2182202375Srdivacky  // If the conversion would lose info, don't hack on this.
2183202375Srdivacky  if ((int)InputSize > MantissaWidth)
2184202375Srdivacky    return 0;
2185202375Srdivacky
2186202375Srdivacky  // Otherwise, we can potentially simplify the comparison.  We know that it
2187202375Srdivacky  // will always come through as an integer value and we know the constant is
2188202375Srdivacky  // not a NAN (it would have been previously simplified).
2189202375Srdivacky  assert(!RHS.isNaN() && "NaN comparison not already folded!");
2190202375Srdivacky
2191202375Srdivacky  ICmpInst::Predicate Pred;
2192202375Srdivacky  switch (I.getPredicate()) {
2193202375Srdivacky  default: llvm_unreachable("Unexpected predicate!");
2194202375Srdivacky  case FCmpInst::FCMP_UEQ:
2195202375Srdivacky  case FCmpInst::FCMP_OEQ:
2196202375Srdivacky    Pred = ICmpInst::ICMP_EQ;
2197202375Srdivacky    break;
2198202375Srdivacky  case FCmpInst::FCMP_UGT:
2199202375Srdivacky  case FCmpInst::FCMP_OGT:
2200202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2201202375Srdivacky    break;
2202202375Srdivacky  case FCmpInst::FCMP_UGE:
2203202375Srdivacky  case FCmpInst::FCMP_OGE:
2204202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2205202375Srdivacky    break;
2206202375Srdivacky  case FCmpInst::FCMP_ULT:
2207202375Srdivacky  case FCmpInst::FCMP_OLT:
2208202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2209202375Srdivacky    break;
2210202375Srdivacky  case FCmpInst::FCMP_ULE:
2211202375Srdivacky  case FCmpInst::FCMP_OLE:
2212202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2213202375Srdivacky    break;
2214202375Srdivacky  case FCmpInst::FCMP_UNE:
2215202375Srdivacky  case FCmpInst::FCMP_ONE:
2216202375Srdivacky    Pred = ICmpInst::ICMP_NE;
2217202375Srdivacky    break;
2218202375Srdivacky  case FCmpInst::FCMP_ORD:
2219202375Srdivacky    return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2220202375Srdivacky  case FCmpInst::FCMP_UNO:
2221202375Srdivacky    return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2222202375Srdivacky  }
2223202375Srdivacky
2224202375Srdivacky  const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2225202375Srdivacky
2226202375Srdivacky  // Now we know that the APFloat is a normal number, zero or inf.
2227202375Srdivacky
2228202375Srdivacky  // See if the FP constant is too large for the integer.  For example,
2229202375Srdivacky  // comparing an i8 to 300.0.
2230202375Srdivacky  unsigned IntWidth = IntTy->getScalarSizeInBits();
2231202375Srdivacky
2232202375Srdivacky  if (!LHSUnsigned) {
2233202375Srdivacky    // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
2234202375Srdivacky    // and large values.
2235202375Srdivacky    APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2236202375Srdivacky    SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2237202375Srdivacky                          APFloat::rmNearestTiesToEven);
2238202375Srdivacky    if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
2239202375Srdivacky      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
2240202375Srdivacky          Pred == ICmpInst::ICMP_SLE)
2241202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2242202375Srdivacky      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2243202375Srdivacky    }
2244202375Srdivacky  } else {
2245202375Srdivacky    // If the RHS value is > UnsignedMax, fold the comparison. This handles
2246202375Srdivacky    // +INF and large values.
2247202375Srdivacky    APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2248202375Srdivacky    UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2249202375Srdivacky                          APFloat::rmNearestTiesToEven);
2250202375Srdivacky    if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
2251202375Srdivacky      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
2252202375Srdivacky          Pred == ICmpInst::ICMP_ULE)
2253202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2254202375Srdivacky      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2255202375Srdivacky    }
2256202375Srdivacky  }
2257202375Srdivacky
2258202375Srdivacky  if (!LHSUnsigned) {
2259202375Srdivacky    // See if the RHS value is < SignedMin.
2260202375Srdivacky    APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2261202375Srdivacky    SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2262202375Srdivacky                          APFloat::rmNearestTiesToEven);
2263202375Srdivacky    if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2264202375Srdivacky      if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2265202375Srdivacky          Pred == ICmpInst::ICMP_SGE)
2266202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2267202375Srdivacky      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2268202375Srdivacky    }
2269202375Srdivacky  }
2270202375Srdivacky
2271202375Srdivacky  // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2272202375Srdivacky  // [0, UMAX], but it may still be fractional.  See if it is fractional by
2273202375Srdivacky  // casting the FP value to the integer value and back, checking for equality.
2274202375Srdivacky  // Don't do this for zero, because -0.0 is not fractional.
2275202375Srdivacky  Constant *RHSInt = LHSUnsigned
2276202375Srdivacky    ? ConstantExpr::getFPToUI(RHSC, IntTy)
2277202375Srdivacky    : ConstantExpr::getFPToSI(RHSC, IntTy);
2278202375Srdivacky  if (!RHS.isZero()) {
2279202375Srdivacky    bool Equal = LHSUnsigned
2280202375Srdivacky      ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2281202375Srdivacky      : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2282202375Srdivacky    if (!Equal) {
2283202375Srdivacky      // If we had a comparison against a fractional value, we have to adjust
2284202375Srdivacky      // the compare predicate and sometimes the value.  RHSC is rounded towards
2285202375Srdivacky      // zero at this point.
2286202375Srdivacky      switch (Pred) {
2287202375Srdivacky      default: llvm_unreachable("Unexpected integer comparison!");
2288202375Srdivacky      case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
2289202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2290202375Srdivacky      case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
2291202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2292202375Srdivacky      case ICmpInst::ICMP_ULE:
2293202375Srdivacky        // (float)int <= 4.4   --> int <= 4
2294202375Srdivacky        // (float)int <= -4.4  --> false
2295202375Srdivacky        if (RHS.isNegative())
2296202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2297202375Srdivacky        break;
2298202375Srdivacky      case ICmpInst::ICMP_SLE:
2299202375Srdivacky        // (float)int <= 4.4   --> int <= 4
2300202375Srdivacky        // (float)int <= -4.4  --> int < -4
2301202375Srdivacky        if (RHS.isNegative())
2302202375Srdivacky          Pred = ICmpInst::ICMP_SLT;
2303202375Srdivacky        break;
2304202375Srdivacky      case ICmpInst::ICMP_ULT:
2305202375Srdivacky        // (float)int < -4.4   --> false
2306202375Srdivacky        // (float)int < 4.4    --> int <= 4
2307202375Srdivacky        if (RHS.isNegative())
2308202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2309202375Srdivacky        Pred = ICmpInst::ICMP_ULE;
2310202375Srdivacky        break;
2311202375Srdivacky      case ICmpInst::ICMP_SLT:
2312202375Srdivacky        // (float)int < -4.4   --> int < -4
2313202375Srdivacky        // (float)int < 4.4    --> int <= 4
2314202375Srdivacky        if (!RHS.isNegative())
2315202375Srdivacky          Pred = ICmpInst::ICMP_SLE;
2316202375Srdivacky        break;
2317202375Srdivacky      case ICmpInst::ICMP_UGT:
2318202375Srdivacky        // (float)int > 4.4    --> int > 4
2319202375Srdivacky        // (float)int > -4.4   --> true
2320202375Srdivacky        if (RHS.isNegative())
2321202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2322202375Srdivacky        break;
2323202375Srdivacky      case ICmpInst::ICMP_SGT:
2324202375Srdivacky        // (float)int > 4.4    --> int > 4
2325202375Srdivacky        // (float)int > -4.4   --> int >= -4
2326202375Srdivacky        if (RHS.isNegative())
2327202375Srdivacky          Pred = ICmpInst::ICMP_SGE;
2328202375Srdivacky        break;
2329202375Srdivacky      case ICmpInst::ICMP_UGE:
2330202375Srdivacky        // (float)int >= -4.4   --> true
2331202375Srdivacky        // (float)int >= 4.4    --> int > 4
2332202375Srdivacky        if (!RHS.isNegative())
2333202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2334202375Srdivacky        Pred = ICmpInst::ICMP_UGT;
2335202375Srdivacky        break;
2336202375Srdivacky      case ICmpInst::ICMP_SGE:
2337202375Srdivacky        // (float)int >= -4.4   --> int >= -4
2338202375Srdivacky        // (float)int >= 4.4    --> int > 4
2339202375Srdivacky        if (!RHS.isNegative())
2340202375Srdivacky          Pred = ICmpInst::ICMP_SGT;
2341202375Srdivacky        break;
2342202375Srdivacky      }
2343202375Srdivacky    }
2344202375Srdivacky  }
2345202375Srdivacky
2346202375Srdivacky  // Lower this FP comparison into an appropriate integer version of the
2347202375Srdivacky  // comparison.
2348202375Srdivacky  return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2349202375Srdivacky}
2350202375Srdivacky
2351202375SrdivackyInstruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2352202375Srdivacky  bool Changed = false;
2353202375Srdivacky
2354202375Srdivacky  /// Orders the operands of the compare so that they are listed from most
2355202375Srdivacky  /// complex to least complex.  This puts constants before unary operators,
2356202375Srdivacky  /// before binary operators.
2357202375Srdivacky  if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2358202375Srdivacky    I.swapOperands();
2359202375Srdivacky    Changed = true;
2360202375Srdivacky  }
2361202375Srdivacky
2362202375Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2363202375Srdivacky
2364202375Srdivacky  if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2365202375Srdivacky    return ReplaceInstUsesWith(I, V);
2366202375Srdivacky
2367202375Srdivacky  // Simplify 'fcmp pred X, X'
2368202375Srdivacky  if (Op0 == Op1) {
2369202375Srdivacky    switch (I.getPredicate()) {
2370202375Srdivacky    default: llvm_unreachable("Unknown predicate!");
2371202375Srdivacky    case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
2372202375Srdivacky    case FCmpInst::FCMP_ULT:    // True if unordered or less than
2373202375Srdivacky    case FCmpInst::FCMP_UGT:    // True if unordered or greater than
2374202375Srdivacky    case FCmpInst::FCMP_UNE:    // True if unordered or not equal
2375202375Srdivacky      // Canonicalize these to be 'fcmp uno %X, 0.0'.
2376202375Srdivacky      I.setPredicate(FCmpInst::FCMP_UNO);
2377202375Srdivacky      I.setOperand(1, Constant::getNullValue(Op0->getType()));
2378202375Srdivacky      return &I;
2379202375Srdivacky
2380202375Srdivacky    case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
2381202375Srdivacky    case FCmpInst::FCMP_OEQ:    // True if ordered and equal
2382202375Srdivacky    case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
2383202375Srdivacky    case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
2384202375Srdivacky      // Canonicalize these to be 'fcmp ord %X, 0.0'.
2385202375Srdivacky      I.setPredicate(FCmpInst::FCMP_ORD);
2386202375Srdivacky      I.setOperand(1, Constant::getNullValue(Op0->getType()));
2387202375Srdivacky      return &I;
2388202375Srdivacky    }
2389202375Srdivacky  }
2390202375Srdivacky
2391202375Srdivacky  // Handle fcmp with constant RHS
2392202375Srdivacky  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2393202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2394202375Srdivacky      switch (LHSI->getOpcode()) {
2395202375Srdivacky      case Instruction::PHI:
2396202375Srdivacky        // Only fold fcmp into the PHI if the phi and fcmp are in the same
2397202375Srdivacky        // block.  If in the same block, we're encouraging jump threading.  If
2398202375Srdivacky        // not, we are just pessimizing the code by making an i1 phi.
2399202375Srdivacky        if (LHSI->getParent() == I.getParent())
2400202375Srdivacky          if (Instruction *NV = FoldOpIntoPhi(I, true))
2401202375Srdivacky            return NV;
2402202375Srdivacky        break;
2403202375Srdivacky      case Instruction::SIToFP:
2404202375Srdivacky      case Instruction::UIToFP:
2405202375Srdivacky        if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2406202375Srdivacky          return NV;
2407202375Srdivacky        break;
2408202375Srdivacky      case Instruction::Select: {
2409202375Srdivacky        // If either operand of the select is a constant, we can fold the
2410202375Srdivacky        // comparison into the select arms, which will cause one to be
2411202375Srdivacky        // constant folded and the select turned into a bitwise or.
2412202375Srdivacky        Value *Op1 = 0, *Op2 = 0;
2413202375Srdivacky        if (LHSI->hasOneUse()) {
2414202375Srdivacky          if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2415202375Srdivacky            // Fold the known value into the constant operand.
2416202375Srdivacky            Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2417202375Srdivacky            // Insert a new FCmp of the other select operand.
2418202375Srdivacky            Op2 = Builder->CreateFCmp(I.getPredicate(),
2419202375Srdivacky                                      LHSI->getOperand(2), RHSC, I.getName());
2420202375Srdivacky          } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2421202375Srdivacky            // Fold the known value into the constant operand.
2422202375Srdivacky            Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2423202375Srdivacky            // Insert a new FCmp of the other select operand.
2424202375Srdivacky            Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2425202375Srdivacky                                      RHSC, I.getName());
2426202375Srdivacky          }
2427202375Srdivacky        }
2428202375Srdivacky
2429202375Srdivacky        if (Op1)
2430202375Srdivacky          return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2431202375Srdivacky        break;
2432202375Srdivacky      }
2433204642Srdivacky      case Instruction::Load:
2434204642Srdivacky        if (GetElementPtrInst *GEP =
2435204642Srdivacky            dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2436204642Srdivacky          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2437204642Srdivacky            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2438204642Srdivacky                !cast<LoadInst>(LHSI)->isVolatile())
2439204642Srdivacky              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2440204642Srdivacky                return Res;
2441204642Srdivacky        }
2442204642Srdivacky        break;
2443202375Srdivacky      }
2444202375Srdivacky  }
2445202375Srdivacky
2446202375Srdivacky  return Changed ? &I : 0;
2447202375Srdivacky}
2448