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"
15226633Sdim#include "llvm/Analysis/ConstantFolding.h"
16202375Srdivacky#include "llvm/Analysis/InstructionSimplify.h"
17202375Srdivacky#include "llvm/Analysis/MemoryBuiltins.h"
18249423Sdim#include "llvm/IR/DataLayout.h"
19249423Sdim#include "llvm/IR/IntrinsicInst.h"
20202375Srdivacky#include "llvm/Support/ConstantRange.h"
21202375Srdivacky#include "llvm/Support/GetElementPtrTypeIterator.h"
22202375Srdivacky#include "llvm/Support/PatternMatch.h"
23249423Sdim#include "llvm/Target/TargetLibraryInfo.h"
24202375Srdivackyusing namespace llvm;
25202375Srdivackyusing namespace PatternMatch;
26202375Srdivacky
27218893Sdimstatic ConstantInt *getOne(Constant *C) {
28218893Sdim  return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29218893Sdim}
30218893Sdim
31202375Srdivacky/// AddOne - Add one to a ConstantInt
32202375Srdivackystatic Constant *AddOne(Constant *C) {
33202375Srdivacky  return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
34202375Srdivacky}
35202375Srdivacky/// SubOne - Subtract one from a ConstantInt
36218893Sdimstatic Constant *SubOne(Constant *C) {
37218893Sdim  return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
38202375Srdivacky}
39202375Srdivacky
40202375Srdivackystatic ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
41202375Srdivacky  return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
42202375Srdivacky}
43202375Srdivacky
44202375Srdivackystatic bool HasAddOverflow(ConstantInt *Result,
45202375Srdivacky                           ConstantInt *In1, ConstantInt *In2,
46202375Srdivacky                           bool IsSigned) {
47224145Sdim  if (!IsSigned)
48202375Srdivacky    return Result->getValue().ult(In1->getValue());
49224145Sdim
50224145Sdim  if (In2->isNegative())
51224145Sdim    return Result->getValue().sgt(In1->getValue());
52224145Sdim  return Result->getValue().slt(In1->getValue());
53202375Srdivacky}
54202375Srdivacky
55202375Srdivacky/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
56202375Srdivacky/// overflowed for this type.
57202375Srdivackystatic bool AddWithOverflow(Constant *&Result, Constant *In1,
58202375Srdivacky                            Constant *In2, bool IsSigned = false) {
59202375Srdivacky  Result = ConstantExpr::getAdd(In1, In2);
60202375Srdivacky
61226633Sdim  if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
62202375Srdivacky    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
63202375Srdivacky      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
64202375Srdivacky      if (HasAddOverflow(ExtractElement(Result, Idx),
65202375Srdivacky                         ExtractElement(In1, Idx),
66202375Srdivacky                         ExtractElement(In2, Idx),
67202375Srdivacky                         IsSigned))
68202375Srdivacky        return true;
69202375Srdivacky    }
70202375Srdivacky    return false;
71202375Srdivacky  }
72202375Srdivacky
73202375Srdivacky  return HasAddOverflow(cast<ConstantInt>(Result),
74202375Srdivacky                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
75202375Srdivacky                        IsSigned);
76202375Srdivacky}
77202375Srdivacky
78202375Srdivackystatic bool HasSubOverflow(ConstantInt *Result,
79202375Srdivacky                           ConstantInt *In1, ConstantInt *In2,
80202375Srdivacky                           bool IsSigned) {
81224145Sdim  if (!IsSigned)
82202375Srdivacky    return Result->getValue().ugt(In1->getValue());
83226633Sdim
84224145Sdim  if (In2->isNegative())
85224145Sdim    return Result->getValue().slt(In1->getValue());
86224145Sdim
87224145Sdim  return Result->getValue().sgt(In1->getValue());
88202375Srdivacky}
89202375Srdivacky
90202375Srdivacky/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
91202375Srdivacky/// overflowed for this type.
92202375Srdivackystatic bool SubWithOverflow(Constant *&Result, Constant *In1,
93202375Srdivacky                            Constant *In2, bool IsSigned = false) {
94202375Srdivacky  Result = ConstantExpr::getSub(In1, In2);
95202375Srdivacky
96226633Sdim  if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
97202375Srdivacky    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
98202375Srdivacky      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
99202375Srdivacky      if (HasSubOverflow(ExtractElement(Result, Idx),
100202375Srdivacky                         ExtractElement(In1, Idx),
101202375Srdivacky                         ExtractElement(In2, Idx),
102202375Srdivacky                         IsSigned))
103202375Srdivacky        return true;
104202375Srdivacky    }
105202375Srdivacky    return false;
106202375Srdivacky  }
107202375Srdivacky
108202375Srdivacky  return HasSubOverflow(cast<ConstantInt>(Result),
109202375Srdivacky                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
110202375Srdivacky                        IsSigned);
111202375Srdivacky}
112202375Srdivacky
113202375Srdivacky/// isSignBitCheck - Given an exploded icmp instruction, return true if the
114202375Srdivacky/// comparison only checks the sign bit.  If it only checks the sign bit, set
115202375Srdivacky/// TrueIfSigned if the result of the comparison is true when the input value is
116202375Srdivacky/// signed.
117202375Srdivackystatic bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
118202375Srdivacky                           bool &TrueIfSigned) {
119202375Srdivacky  switch (pred) {
120202375Srdivacky  case ICmpInst::ICMP_SLT:   // True if LHS s< 0
121202375Srdivacky    TrueIfSigned = true;
122202375Srdivacky    return RHS->isZero();
123202375Srdivacky  case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
124202375Srdivacky    TrueIfSigned = true;
125202375Srdivacky    return RHS->isAllOnesValue();
126202375Srdivacky  case ICmpInst::ICMP_SGT:   // True if LHS s> -1
127202375Srdivacky    TrueIfSigned = false;
128202375Srdivacky    return RHS->isAllOnesValue();
129202375Srdivacky  case ICmpInst::ICMP_UGT:
130202375Srdivacky    // True if LHS u> RHS and RHS == high-bit-mask - 1
131202375Srdivacky    TrueIfSigned = true;
132224145Sdim    return RHS->isMaxValue(true);
133226633Sdim  case ICmpInst::ICMP_UGE:
134202375Srdivacky    // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135202375Srdivacky    TrueIfSigned = true;
136202375Srdivacky    return RHS->getValue().isSignBit();
137202375Srdivacky  default:
138202375Srdivacky    return false;
139202375Srdivacky  }
140202375Srdivacky}
141202375Srdivacky
142249423Sdim/// Returns true if the exploded icmp can be expressed as a signed comparison
143249423Sdim/// to zero and updates the predicate accordingly.
144249423Sdim/// The signedness of the comparison is preserved.
145249423Sdimstatic bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
146249423Sdim  if (!ICmpInst::isSigned(pred))
147249423Sdim    return false;
148249423Sdim
149249423Sdim  if (RHS->isZero())
150249423Sdim    return ICmpInst::isRelational(pred);
151249423Sdim
152249423Sdim  if (RHS->isOne()) {
153249423Sdim    if (pred == ICmpInst::ICMP_SLT) {
154249423Sdim      pred = ICmpInst::ICMP_SLE;
155249423Sdim      return true;
156249423Sdim    }
157249423Sdim  } else if (RHS->isAllOnesValue()) {
158249423Sdim    if (pred == ICmpInst::ICMP_SGT) {
159249423Sdim      pred = ICmpInst::ICMP_SGE;
160249423Sdim      return true;
161249423Sdim    }
162249423Sdim  }
163249423Sdim
164249423Sdim  return false;
165249423Sdim}
166249423Sdim
167202375Srdivacky// isHighOnes - Return true if the constant is of the form 1+0+.
168202375Srdivacky// This is the same as lowones(~X).
169202375Srdivackystatic bool isHighOnes(const ConstantInt *CI) {
170202375Srdivacky  return (~CI->getValue() + 1).isPowerOf2();
171202375Srdivacky}
172202375Srdivacky
173226633Sdim/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
174202375Srdivacky/// set of known zero and one bits, compute the maximum and minimum values that
175202375Srdivacky/// could have the specified known zero and known one bits, returning them in
176202375Srdivacky/// min/max.
177202375Srdivackystatic void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
178202375Srdivacky                                                   const APInt& KnownOne,
179202375Srdivacky                                                   APInt& Min, APInt& Max) {
180202375Srdivacky  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
181202375Srdivacky         KnownZero.getBitWidth() == Min.getBitWidth() &&
182202375Srdivacky         KnownZero.getBitWidth() == Max.getBitWidth() &&
183202375Srdivacky         "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
184202375Srdivacky  APInt UnknownBits = ~(KnownZero|KnownOne);
185202375Srdivacky
186202375Srdivacky  // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
187202375Srdivacky  // bit if it is unknown.
188202375Srdivacky  Min = KnownOne;
189202375Srdivacky  Max = KnownOne|UnknownBits;
190226633Sdim
191202375Srdivacky  if (UnknownBits.isNegative()) { // Sign bit is unknown
192218893Sdim    Min.setBit(Min.getBitWidth()-1);
193218893Sdim    Max.clearBit(Max.getBitWidth()-1);
194202375Srdivacky  }
195202375Srdivacky}
196202375Srdivacky
197202375Srdivacky// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
198202375Srdivacky// a set of known zero and one bits, compute the maximum and minimum values that
199202375Srdivacky// could have the specified known zero and known one bits, returning them in
200202375Srdivacky// min/max.
201202375Srdivackystatic void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202202375Srdivacky                                                     const APInt &KnownOne,
203202375Srdivacky                                                     APInt &Min, APInt &Max) {
204202375Srdivacky  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205202375Srdivacky         KnownZero.getBitWidth() == Min.getBitWidth() &&
206202375Srdivacky         KnownZero.getBitWidth() == Max.getBitWidth() &&
207202375Srdivacky         "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208202375Srdivacky  APInt UnknownBits = ~(KnownZero|KnownOne);
209226633Sdim
210202375Srdivacky  // The minimum value is when the unknown bits are all zeros.
211202375Srdivacky  Min = KnownOne;
212202375Srdivacky  // The maximum value is when the unknown bits are all ones.
213202375Srdivacky  Max = KnownOne|UnknownBits;
214202375Srdivacky}
215202375Srdivacky
216202375Srdivacky
217202375Srdivacky
218202375Srdivacky/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
219202375Srdivacky///   cmp pred (load (gep GV, ...)), cmpcst
220202375Srdivacky/// where GV is a global variable with a constant initializer.  Try to simplify
221202375Srdivacky/// this into some simple computation that does not need the load.  For example
222202375Srdivacky/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
223202375Srdivacky///
224202375Srdivacky/// If AndCst is non-null, then the loaded value is masked with that constant
225202375Srdivacky/// before doing the comparison.  This handles cases like "A[i]&4 == 0".
226202375SrdivackyInstruction *InstCombiner::
227202375SrdivackyFoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
228202375Srdivacky                             CmpInst &ICI, ConstantInt *AndCst) {
229202375Srdivacky  // We need TD information to know the pointer size unless this is inbounds.
230202375Srdivacky  if (!GEP->isInBounds() && TD == 0) return 0;
231226633Sdim
232234353Sdim  Constant *Init = GV->getInitializer();
233234353Sdim  if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
234234353Sdim    return 0;
235251662Sdim
236234353Sdim  uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
237234353Sdim  if (ArrayElementCount > 1024) return 0;  // Don't blow up on huge arrays.
238226633Sdim
239202375Srdivacky  // There are many forms of this optimization we can handle, for now, just do
240202375Srdivacky  // the simple index into a single-dimensional array.
241202375Srdivacky  //
242202375Srdivacky  // Require: GEP GV, 0, i {{, constant indices}}
243202375Srdivacky  if (GEP->getNumOperands() < 3 ||
244202375Srdivacky      !isa<ConstantInt>(GEP->getOperand(1)) ||
245202375Srdivacky      !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
246202375Srdivacky      isa<Constant>(GEP->getOperand(2)))
247202375Srdivacky    return 0;
248202375Srdivacky
249202375Srdivacky  // Check that indices after the variable are constants and in-range for the
250202375Srdivacky  // type they index.  Collect the indices.  This is typically for arrays of
251202375Srdivacky  // structs.
252202375Srdivacky  SmallVector<unsigned, 4> LaterIndices;
253226633Sdim
254234353Sdim  Type *EltTy = Init->getType()->getArrayElementType();
255202375Srdivacky  for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
256202375Srdivacky    ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
257202375Srdivacky    if (Idx == 0) return 0;  // Variable index.
258226633Sdim
259202375Srdivacky    uint64_t IdxVal = Idx->getZExtValue();
260202375Srdivacky    if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
261226633Sdim
262226633Sdim    if (StructType *STy = dyn_cast<StructType>(EltTy))
263202375Srdivacky      EltTy = STy->getElementType(IdxVal);
264226633Sdim    else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
265202375Srdivacky      if (IdxVal >= ATy->getNumElements()) return 0;
266202375Srdivacky      EltTy = ATy->getElementType();
267202375Srdivacky    } else {
268202375Srdivacky      return 0; // Unknown type.
269202375Srdivacky    }
270226633Sdim
271202375Srdivacky    LaterIndices.push_back(IdxVal);
272202375Srdivacky  }
273226633Sdim
274202375Srdivacky  enum { Overdefined = -3, Undefined = -2 };
275202375Srdivacky
276202375Srdivacky  // Variables for our state machines.
277226633Sdim
278202375Srdivacky  // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
279202375Srdivacky  // "i == 47 | i == 87", where 47 is the first index the condition is true for,
280202375Srdivacky  // and 87 is the second (and last) index.  FirstTrueElement is -2 when
281202375Srdivacky  // undefined, otherwise set to the first true element.  SecondTrueElement is
282202375Srdivacky  // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
283202375Srdivacky  int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
284202375Srdivacky
285202375Srdivacky  // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
286202375Srdivacky  // form "i != 47 & i != 87".  Same state transitions as for true elements.
287202375Srdivacky  int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
288226633Sdim
289202375Srdivacky  /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
290202375Srdivacky  /// define a state machine that triggers for ranges of values that the index
291202375Srdivacky  /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
292202375Srdivacky  /// This is -2 when undefined, -3 when overdefined, and otherwise the last
293202375Srdivacky  /// index in the range (inclusive).  We use -2 for undefined here because we
294202375Srdivacky  /// use relative comparisons and don't want 0-1 to match -1.
295202375Srdivacky  int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
296226633Sdim
297202375Srdivacky  // MagicBitvector - This is a magic bitvector where we set a bit if the
298202375Srdivacky  // comparison is true for element 'i'.  If there are 64 elements or less in
299202375Srdivacky  // the array, this will fully represent all the comparison results.
300202375Srdivacky  uint64_t MagicBitvector = 0;
301226633Sdim
302226633Sdim
303202375Srdivacky  // Scan the array and see if one of our patterns matches.
304202375Srdivacky  Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
305234353Sdim  for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
306234353Sdim    Constant *Elt = Init->getAggregateElement(i);
307234353Sdim    if (Elt == 0) return 0;
308226633Sdim
309202375Srdivacky    // If this is indexing an array of structures, get the structure element.
310202375Srdivacky    if (!LaterIndices.empty())
311224145Sdim      Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
312226633Sdim
313202375Srdivacky    // If the element is masked, handle it.
314202375Srdivacky    if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
315226633Sdim
316202375Srdivacky    // Find out if the comparison would be true or false for the i'th element.
317202375Srdivacky    Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
318234353Sdim                                                  CompareRHS, TD, TLI);
319202375Srdivacky    // If the result is undef for this element, ignore it.
320202375Srdivacky    if (isa<UndefValue>(C)) {
321202375Srdivacky      // Extend range state machines to cover this element in case there is an
322202375Srdivacky      // undef in the middle of the range.
323202375Srdivacky      if (TrueRangeEnd == (int)i-1)
324202375Srdivacky        TrueRangeEnd = i;
325202375Srdivacky      if (FalseRangeEnd == (int)i-1)
326202375Srdivacky        FalseRangeEnd = i;
327202375Srdivacky      continue;
328202375Srdivacky    }
329226633Sdim
330202375Srdivacky    // If we can't compute the result for any of the elements, we have to give
331202375Srdivacky    // up evaluating the entire conditional.
332202375Srdivacky    if (!isa<ConstantInt>(C)) return 0;
333226633Sdim
334202375Srdivacky    // Otherwise, we know if the comparison is true or false for this element,
335202375Srdivacky    // update our state machines.
336202375Srdivacky    bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
337226633Sdim
338202375Srdivacky    // State machine for single/double/range index comparison.
339202375Srdivacky    if (IsTrueForElt) {
340202375Srdivacky      // Update the TrueElement state machine.
341202375Srdivacky      if (FirstTrueElement == Undefined)
342202375Srdivacky        FirstTrueElement = TrueRangeEnd = i;  // First true element.
343202375Srdivacky      else {
344202375Srdivacky        // Update double-compare state machine.
345202375Srdivacky        if (SecondTrueElement == Undefined)
346202375Srdivacky          SecondTrueElement = i;
347202375Srdivacky        else
348202375Srdivacky          SecondTrueElement = Overdefined;
349226633Sdim
350202375Srdivacky        // Update range state machine.
351202375Srdivacky        if (TrueRangeEnd == (int)i-1)
352202375Srdivacky          TrueRangeEnd = i;
353202375Srdivacky        else
354202375Srdivacky          TrueRangeEnd = Overdefined;
355202375Srdivacky      }
356202375Srdivacky    } else {
357202375Srdivacky      // Update the FalseElement state machine.
358202375Srdivacky      if (FirstFalseElement == Undefined)
359202375Srdivacky        FirstFalseElement = FalseRangeEnd = i; // First false element.
360202375Srdivacky      else {
361202375Srdivacky        // Update double-compare state machine.
362202375Srdivacky        if (SecondFalseElement == Undefined)
363202375Srdivacky          SecondFalseElement = i;
364202375Srdivacky        else
365202375Srdivacky          SecondFalseElement = Overdefined;
366226633Sdim
367202375Srdivacky        // Update range state machine.
368202375Srdivacky        if (FalseRangeEnd == (int)i-1)
369202375Srdivacky          FalseRangeEnd = i;
370202375Srdivacky        else
371202375Srdivacky          FalseRangeEnd = Overdefined;
372202375Srdivacky      }
373202375Srdivacky    }
374226633Sdim
375226633Sdim
376202375Srdivacky    // If this element is in range, update our magic bitvector.
377202375Srdivacky    if (i < 64 && IsTrueForElt)
378202375Srdivacky      MagicBitvector |= 1ULL << i;
379226633Sdim
380202375Srdivacky    // If all of our states become overdefined, bail out early.  Since the
381202375Srdivacky    // predicate is expensive, only check it every 8 elements.  This is only
382202375Srdivacky    // really useful for really huge arrays.
383202375Srdivacky    if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
384202375Srdivacky        SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
385202375Srdivacky        FalseRangeEnd == Overdefined)
386202375Srdivacky      return 0;
387202375Srdivacky  }
388202375Srdivacky
389202375Srdivacky  // Now that we've scanned the entire array, emit our new comparison(s).  We
390202375Srdivacky  // order the state machines in complexity of the generated code.
391202375Srdivacky  Value *Idx = GEP->getOperand(2);
392202375Srdivacky
393202375Srdivacky  // If the index is larger than the pointer size of the target, truncate the
394202375Srdivacky  // index down like the GEP would do implicitly.  We don't have to do this for
395202375Srdivacky  // an inbounds GEP because the index can't be out of range.
396202375Srdivacky  if (!GEP->isInBounds() &&
397202375Srdivacky      Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
398202375Srdivacky    Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
399226633Sdim
400202375Srdivacky  // If the comparison is only true for one or two elements, emit direct
401202375Srdivacky  // comparisons.
402202375Srdivacky  if (SecondTrueElement != Overdefined) {
403202375Srdivacky    // None true -> false.
404202375Srdivacky    if (FirstTrueElement == Undefined)
405202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
406226633Sdim
407202375Srdivacky    Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
408226633Sdim
409202375Srdivacky    // True for one element -> 'i == 47'.
410202375Srdivacky    if (SecondTrueElement == Undefined)
411202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
412226633Sdim
413202375Srdivacky    // True for two elements -> 'i == 47 | i == 72'.
414202375Srdivacky    Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
415202375Srdivacky    Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
416202375Srdivacky    Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
417202375Srdivacky    return BinaryOperator::CreateOr(C1, C2);
418202375Srdivacky  }
419202375Srdivacky
420202375Srdivacky  // If the comparison is only false for one or two elements, emit direct
421202375Srdivacky  // comparisons.
422202375Srdivacky  if (SecondFalseElement != Overdefined) {
423202375Srdivacky    // None false -> true.
424202375Srdivacky    if (FirstFalseElement == Undefined)
425202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
426226633Sdim
427202375Srdivacky    Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
428202375Srdivacky
429202375Srdivacky    // False for one element -> 'i != 47'.
430202375Srdivacky    if (SecondFalseElement == Undefined)
431202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
432226633Sdim
433202375Srdivacky    // False for two elements -> 'i != 47 & i != 72'.
434202375Srdivacky    Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
435202375Srdivacky    Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
436202375Srdivacky    Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
437202375Srdivacky    return BinaryOperator::CreateAnd(C1, C2);
438202375Srdivacky  }
439226633Sdim
440202375Srdivacky  // If the comparison can be replaced with a range comparison for the elements
441202375Srdivacky  // where it is true, emit the range check.
442202375Srdivacky  if (TrueRangeEnd != Overdefined) {
443202375Srdivacky    assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
444226633Sdim
445202375Srdivacky    // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
446202375Srdivacky    if (FirstTrueElement) {
447202375Srdivacky      Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
448202375Srdivacky      Idx = Builder->CreateAdd(Idx, Offs);
449202375Srdivacky    }
450226633Sdim
451202375Srdivacky    Value *End = ConstantInt::get(Idx->getType(),
452202375Srdivacky                                  TrueRangeEnd-FirstTrueElement+1);
453202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
454202375Srdivacky  }
455226633Sdim
456202375Srdivacky  // False range check.
457202375Srdivacky  if (FalseRangeEnd != Overdefined) {
458202375Srdivacky    assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
459202375Srdivacky    // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
460202375Srdivacky    if (FirstFalseElement) {
461202375Srdivacky      Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
462202375Srdivacky      Idx = Builder->CreateAdd(Idx, Offs);
463202375Srdivacky    }
464226633Sdim
465202375Srdivacky    Value *End = ConstantInt::get(Idx->getType(),
466202375Srdivacky                                  FalseRangeEnd-FirstFalseElement);
467202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
468202375Srdivacky  }
469226633Sdim
470226633Sdim
471249423Sdim  // If a magic bitvector captures the entire comparison state
472202375Srdivacky  // of this load, replace it with computation that does:
473202375Srdivacky  //   ((magic_cst >> i) & 1) != 0
474249423Sdim  {
475249423Sdim    Type *Ty = 0;
476249423Sdim
477249423Sdim    // Look for an appropriate type:
478249423Sdim    // - The type of Idx if the magic fits
479249423Sdim    // - The smallest fitting legal type if we have a DataLayout
480249423Sdim    // - Default to i32
481249423Sdim    if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
482249423Sdim      Ty = Idx->getType();
483249423Sdim    else if (TD)
484249423Sdim      Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
485249423Sdim    else if (ArrayElementCount <= 32)
486202375Srdivacky      Ty = Type::getInt32Ty(Init->getContext());
487249423Sdim
488249423Sdim    if (Ty != 0) {
489249423Sdim      Value *V = Builder->CreateIntCast(Idx, Ty, false);
490249423Sdim      V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
491249423Sdim      V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
492249423Sdim      return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
493249423Sdim    }
494202375Srdivacky  }
495226633Sdim
496202375Srdivacky  return 0;
497202375Srdivacky}
498202375Srdivacky
499202375Srdivacky
500202375Srdivacky/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
501202375Srdivacky/// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
502202375Srdivacky/// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
503202375Srdivacky/// be complex, and scales are involved.  The above expression would also be
504202375Srdivacky/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
505202375Srdivacky/// This later form is less amenable to optimization though, and we are allowed
506202375Srdivacky/// to generate the first by knowing that pointer arithmetic doesn't overflow.
507202375Srdivacky///
508202375Srdivacky/// If we can't emit an optimized form for this expression, this returns null.
509226633Sdim///
510223017Sdimstatic Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
511243830Sdim  DataLayout &TD = *IC.getDataLayout();
512202375Srdivacky  gep_type_iterator GTI = gep_type_begin(GEP);
513226633Sdim
514202375Srdivacky  // Check to see if this gep only has a single variable index.  If so, and if
515202375Srdivacky  // any constant indices are a multiple of its scale, then we can compute this
516202375Srdivacky  // in terms of the scale of the variable index.  For example, if the GEP
517202375Srdivacky  // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
518202375Srdivacky  // because the expression will cross zero at the same point.
519202375Srdivacky  unsigned i, e = GEP->getNumOperands();
520202375Srdivacky  int64_t Offset = 0;
521202375Srdivacky  for (i = 1; i != e; ++i, ++GTI) {
522202375Srdivacky    if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
523202375Srdivacky      // Compute the aggregate offset of constant indices.
524202375Srdivacky      if (CI->isZero()) continue;
525226633Sdim
526202375Srdivacky      // Handle a struct index, which adds its field offset to the pointer.
527226633Sdim      if (StructType *STy = dyn_cast<StructType>(*GTI)) {
528202375Srdivacky        Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
529202375Srdivacky      } else {
530202375Srdivacky        uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
531202375Srdivacky        Offset += Size*CI->getSExtValue();
532202375Srdivacky      }
533202375Srdivacky    } else {
534202375Srdivacky      // Found our variable index.
535202375Srdivacky      break;
536202375Srdivacky    }
537202375Srdivacky  }
538226633Sdim
539202375Srdivacky  // If there are no variable indices, we must have a constant offset, just
540202375Srdivacky  // evaluate it the general way.
541202375Srdivacky  if (i == e) return 0;
542226633Sdim
543202375Srdivacky  Value *VariableIdx = GEP->getOperand(i);
544202375Srdivacky  // Determine the scale factor of the variable element.  For example, this is
545202375Srdivacky  // 4 if the variable index is into an array of i32.
546202375Srdivacky  uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
547226633Sdim
548202375Srdivacky  // Verify that there are no other variable indices.  If so, emit the hard way.
549202375Srdivacky  for (++i, ++GTI; i != e; ++i, ++GTI) {
550202375Srdivacky    ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
551202375Srdivacky    if (!CI) return 0;
552226633Sdim
553202375Srdivacky    // Compute the aggregate offset of constant indices.
554202375Srdivacky    if (CI->isZero()) continue;
555226633Sdim
556202375Srdivacky    // Handle a struct index, which adds its field offset to the pointer.
557226633Sdim    if (StructType *STy = dyn_cast<StructType>(*GTI)) {
558202375Srdivacky      Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
559202375Srdivacky    } else {
560202375Srdivacky      uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
561202375Srdivacky      Offset += Size*CI->getSExtValue();
562202375Srdivacky    }
563202375Srdivacky  }
564226633Sdim
565202375Srdivacky  // Okay, we know we have a single variable index, which must be a
566202375Srdivacky  // pointer/array/vector index.  If there is no offset, life is simple, return
567202375Srdivacky  // the index.
568202375Srdivacky  unsigned IntPtrWidth = TD.getPointerSizeInBits();
569202375Srdivacky  if (Offset == 0) {
570202375Srdivacky    // Cast to intptrty in case a truncation occurs.  If an extension is needed,
571202375Srdivacky    // we don't need to bother extending: the extension won't affect where the
572202375Srdivacky    // computation crosses zero.
573223017Sdim    if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
574226633Sdim      Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
575223017Sdim      VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
576223017Sdim    }
577202375Srdivacky    return VariableIdx;
578202375Srdivacky  }
579226633Sdim
580202375Srdivacky  // Otherwise, there is an index.  The computation we will do will be modulo
581202375Srdivacky  // the pointer size, so get it.
582202375Srdivacky  uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
583226633Sdim
584202375Srdivacky  Offset &= PtrSizeMask;
585202375Srdivacky  VariableScale &= PtrSizeMask;
586226633Sdim
587202375Srdivacky  // To do this transformation, any constant index must be a multiple of the
588202375Srdivacky  // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
589202375Srdivacky  // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
590202375Srdivacky  // multiple of the variable scale.
591202375Srdivacky  int64_t NewOffs = Offset / (int64_t)VariableScale;
592202375Srdivacky  if (Offset != NewOffs*(int64_t)VariableScale)
593202375Srdivacky    return 0;
594226633Sdim
595202375Srdivacky  // Okay, we can do this evaluation.  Start by converting the index to intptr.
596226633Sdim  Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
597202375Srdivacky  if (VariableIdx->getType() != IntPtrTy)
598223017Sdim    VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
599223017Sdim                                            true /*Signed*/);
600202375Srdivacky  Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
601223017Sdim  return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
602202375Srdivacky}
603202375Srdivacky
604202375Srdivacky/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
605202375Srdivacky/// else.  At this point we know that the GEP is on the LHS of the comparison.
606202375SrdivackyInstruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
607202375Srdivacky                                       ICmpInst::Predicate Cond,
608202375Srdivacky                                       Instruction &I) {
609234353Sdim  // Don't transform signed compares of GEPs into index compares. Even if the
610234353Sdim  // GEP is inbounds, the final add of the base pointer can have signed overflow
611234353Sdim  // and would change the result of the icmp.
612234353Sdim  // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
613234353Sdim  // the maximum signed value for the pointer type.
614234353Sdim  if (ICmpInst::isSigned(Cond))
615234353Sdim    return 0;
616234353Sdim
617202375Srdivacky  // Look through bitcasts.
618202375Srdivacky  if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
619202375Srdivacky    RHS = BCI->getOperand(0);
620202375Srdivacky
621202375Srdivacky  Value *PtrBase = GEPLHS->getOperand(0);
622202375Srdivacky  if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
623202375Srdivacky    // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
624202375Srdivacky    // This transformation (ignoring the base and scales) is valid because we
625202375Srdivacky    // know pointers can't overflow since the gep is inbounds.  See if we can
626202375Srdivacky    // output an optimized form.
627223017Sdim    Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
628226633Sdim
629202375Srdivacky    // If not, synthesize the offset the hard way.
630202375Srdivacky    if (Offset == 0)
631202375Srdivacky      Offset = EmitGEPOffset(GEPLHS);
632202375Srdivacky    return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
633202375Srdivacky                        Constant::getNullValue(Offset->getType()));
634202375Srdivacky  } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
635202375Srdivacky    // If the base pointers are different, but the indices are the same, just
636202375Srdivacky    // compare the base pointer.
637202375Srdivacky    if (PtrBase != GEPRHS->getOperand(0)) {
638202375Srdivacky      bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
639202375Srdivacky      IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
640202375Srdivacky                        GEPRHS->getOperand(0)->getType();
641202375Srdivacky      if (IndicesTheSame)
642202375Srdivacky        for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
643202375Srdivacky          if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
644202375Srdivacky            IndicesTheSame = false;
645202375Srdivacky            break;
646202375Srdivacky          }
647202375Srdivacky
648202375Srdivacky      // If all indices are the same, just compare the base pointers.
649202375Srdivacky      if (IndicesTheSame)
650202375Srdivacky        return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
651202375Srdivacky                            GEPLHS->getOperand(0), GEPRHS->getOperand(0));
652202375Srdivacky
653234353Sdim      // If we're comparing GEPs with two base pointers that only differ in type
654234353Sdim      // and both GEPs have only constant indices or just one use, then fold
655234353Sdim      // the compare with the adjusted indices.
656234353Sdim      if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
657234353Sdim          (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
658234353Sdim          (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
659234353Sdim          PtrBase->stripPointerCasts() ==
660234353Sdim            GEPRHS->getOperand(0)->stripPointerCasts()) {
661234353Sdim        Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
662234353Sdim                                         EmitGEPOffset(GEPLHS),
663234353Sdim                                         EmitGEPOffset(GEPRHS));
664234353Sdim        return ReplaceInstUsesWith(I, Cmp);
665234353Sdim      }
666234353Sdim
667202375Srdivacky      // Otherwise, the base pointers are different and the indices are
668202375Srdivacky      // different, bail out.
669202375Srdivacky      return 0;
670202375Srdivacky    }
671202375Srdivacky
672202375Srdivacky    // If one of the GEPs has all zero indices, recurse.
673202375Srdivacky    bool AllZeros = true;
674202375Srdivacky    for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
675202375Srdivacky      if (!isa<Constant>(GEPLHS->getOperand(i)) ||
676202375Srdivacky          !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
677202375Srdivacky        AllZeros = false;
678202375Srdivacky        break;
679202375Srdivacky      }
680202375Srdivacky    if (AllZeros)
681202375Srdivacky      return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
682202375Srdivacky                          ICmpInst::getSwappedPredicate(Cond), I);
683202375Srdivacky
684202375Srdivacky    // If the other GEP has all zero indices, recurse.
685202375Srdivacky    AllZeros = true;
686202375Srdivacky    for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
687202375Srdivacky      if (!isa<Constant>(GEPRHS->getOperand(i)) ||
688202375Srdivacky          !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
689202375Srdivacky        AllZeros = false;
690202375Srdivacky        break;
691202375Srdivacky      }
692202375Srdivacky    if (AllZeros)
693202375Srdivacky      return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
694202375Srdivacky
695223017Sdim    bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
696202375Srdivacky    if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
697202375Srdivacky      // If the GEPs only differ by one index, compare it.
698202375Srdivacky      unsigned NumDifferences = 0;  // Keep track of # differences.
699202375Srdivacky      unsigned DiffOperand = 0;     // The operand that differs.
700202375Srdivacky      for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
701202375Srdivacky        if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
702202375Srdivacky          if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
703202375Srdivacky                   GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
704202375Srdivacky            // Irreconcilable differences.
705202375Srdivacky            NumDifferences = 2;
706202375Srdivacky            break;
707202375Srdivacky          } else {
708202375Srdivacky            if (NumDifferences++) break;
709202375Srdivacky            DiffOperand = i;
710202375Srdivacky          }
711202375Srdivacky        }
712202375Srdivacky
713202375Srdivacky      if (NumDifferences == 0)   // SAME GEP?
714202375Srdivacky        return ReplaceInstUsesWith(I, // No comparison is needed here.
715202375Srdivacky                               ConstantInt::get(Type::getInt1Ty(I.getContext()),
716202375Srdivacky                                             ICmpInst::isTrueWhenEqual(Cond)));
717202375Srdivacky
718223017Sdim      else if (NumDifferences == 1 && GEPsInBounds) {
719202375Srdivacky        Value *LHSV = GEPLHS->getOperand(DiffOperand);
720202375Srdivacky        Value *RHSV = GEPRHS->getOperand(DiffOperand);
721202375Srdivacky        // Make sure we do a signed comparison here.
722202375Srdivacky        return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
723202375Srdivacky      }
724202375Srdivacky    }
725202375Srdivacky
726202375Srdivacky    // Only lower this if the icmp is the only user of the GEP or if we expect
727202375Srdivacky    // the result to fold to a constant!
728202375Srdivacky    if (TD &&
729223017Sdim        GEPsInBounds &&
730202375Srdivacky        (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
731202375Srdivacky        (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
732202375Srdivacky      // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
733202375Srdivacky      Value *L = EmitGEPOffset(GEPLHS);
734202375Srdivacky      Value *R = EmitGEPOffset(GEPRHS);
735202375Srdivacky      return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
736202375Srdivacky    }
737202375Srdivacky  }
738202375Srdivacky  return 0;
739202375Srdivacky}
740202375Srdivacky
741202375Srdivacky/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
742202375SrdivackyInstruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
743202375Srdivacky                                            Value *X, ConstantInt *CI,
744202375Srdivacky                                            ICmpInst::Predicate Pred,
745202375Srdivacky                                            Value *TheAdd) {
746202375Srdivacky  // If we have X+0, exit early (simplifying logic below) and let it get folded
747202375Srdivacky  // elsewhere.   icmp X+0, X  -> icmp X, X
748202375Srdivacky  if (CI->isZero()) {
749202375Srdivacky    bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
750202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
751202375Srdivacky  }
752226633Sdim
753202375Srdivacky  // (X+4) == X -> false.
754202375Srdivacky  if (Pred == ICmpInst::ICMP_EQ)
755202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
756202375Srdivacky
757202375Srdivacky  // (X+4) != X -> true.
758202375Srdivacky  if (Pred == ICmpInst::ICMP_NE)
759202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
760202375Srdivacky
761202375Srdivacky  // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
762221345Sdim  // so the values can never be equal.  Similarly for all other "or equals"
763202375Srdivacky  // operators.
764226633Sdim
765202375Srdivacky  // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
766202375Srdivacky  // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
767202375Srdivacky  // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
768202375Srdivacky  if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
769226633Sdim    Value *R =
770202375Srdivacky      ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
771202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
772202375Srdivacky  }
773226633Sdim
774202375Srdivacky  // (X+1) >u X        --> X <u (0-1)        --> X != 255
775202375Srdivacky  // (X+2) >u X        --> X <u (0-2)        --> X <u 254
776202375Srdivacky  // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
777218893Sdim  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
778202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
779226633Sdim
780202375Srdivacky  unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
781202375Srdivacky  ConstantInt *SMax = ConstantInt::get(X->getContext(),
782202375Srdivacky                                       APInt::getSignedMaxValue(BitWidth));
783202375Srdivacky
784202375Srdivacky  // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
785202375Srdivacky  // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
786202375Srdivacky  // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
787202375Srdivacky  // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
788202375Srdivacky  // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
789202375Srdivacky  // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
790218893Sdim  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
791202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
792226633Sdim
793202375Srdivacky  // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
794202375Srdivacky  // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
795202375Srdivacky  // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
796202375Srdivacky  // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
797202375Srdivacky  // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
798202375Srdivacky  // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
799226633Sdim
800202375Srdivacky  assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
801202375Srdivacky  Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
802202375Srdivacky  return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
803202375Srdivacky}
804202375Srdivacky
805202375Srdivacky/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
806202375Srdivacky/// and CmpRHS are both known to be integer constants.
807202375SrdivackyInstruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
808202375Srdivacky                                          ConstantInt *DivRHS) {
809202375Srdivacky  ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
810202375Srdivacky  const APInt &CmpRHSV = CmpRHS->getValue();
811226633Sdim
812226633Sdim  // FIXME: If the operand types don't match the type of the divide
813202375Srdivacky  // then don't attempt this transform. The code below doesn't have the
814202375Srdivacky  // logic to deal with a signed divide and an unsigned compare (and
815226633Sdim  // vice versa). This is because (x /s C1) <s C2  produces different
816202375Srdivacky  // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
817226633Sdim  // (x /u C1) <u C2.  Simply casting the operands and result won't
818226633Sdim  // work. :(  The if statement below tests that condition and bails
819218893Sdim  // if it finds it.
820202375Srdivacky  bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
821202375Srdivacky  if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
822202375Srdivacky    return 0;
823202375Srdivacky  if (DivRHS->isZero())
824202375Srdivacky    return 0; // The ProdOV computation fails on divide by zero.
825202375Srdivacky  if (DivIsSigned && DivRHS->isAllOnesValue())
826202375Srdivacky    return 0; // The overflow computation also screws up here
827218893Sdim  if (DivRHS->isOne()) {
828218893Sdim    // This eliminates some funny cases with INT_MIN.
829218893Sdim    ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
830218893Sdim    return &ICI;
831218893Sdim  }
832202375Srdivacky
833202375Srdivacky  // Compute Prod = CI * DivRHS. We are essentially solving an equation
834226633Sdim  // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
835226633Sdim  // C2 (CI). By solving for X we can turn this into a range check
836226633Sdim  // instead of computing a divide.
837202375Srdivacky  Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
838202375Srdivacky
839202375Srdivacky  // Determine if the product overflows by seeing if the product is
840202375Srdivacky  // not equal to the divide. Make sure we do the same kind of divide
841226633Sdim  // as in the LHS instruction that we're folding.
842202375Srdivacky  bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
843202375Srdivacky                 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
844202375Srdivacky
845202375Srdivacky  // Get the ICmp opcode
846202375Srdivacky  ICmpInst::Predicate Pred = ICI.getPredicate();
847202375Srdivacky
848218893Sdim  /// If the division is known to be exact, then there is no remainder from the
849218893Sdim  /// divide, so the covered range size is unit, otherwise it is the divisor.
850218893Sdim  ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
851226633Sdim
852202375Srdivacky  // Figure out the interval that is being checked.  For example, a comparison
853226633Sdim  // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
854202375Srdivacky  // Compute this interval based on the constants involved and the signedness of
855202375Srdivacky  // the compare/divide.  This computes a half-open interval, keeping track of
856202375Srdivacky  // whether either value in the interval overflows.  After analysis each
857202375Srdivacky  // overflow variable is set to 0 if it's corresponding bound variable is valid
858202375Srdivacky  // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
859202375Srdivacky  int LoOverflow = 0, HiOverflow = 0;
860202375Srdivacky  Constant *LoBound = 0, *HiBound = 0;
861218893Sdim
862202375Srdivacky  if (!DivIsSigned) {  // udiv
863202375Srdivacky    // e.g. X/5 op 3  --> [15, 20)
864202375Srdivacky    LoBound = Prod;
865202375Srdivacky    HiOverflow = LoOverflow = ProdOV;
866218893Sdim    if (!HiOverflow) {
867218893Sdim      // If this is not an exact divide, then many values in the range collapse
868218893Sdim      // to the same result value.
869218893Sdim      HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
870218893Sdim    }
871226633Sdim
872202375Srdivacky  } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
873202375Srdivacky    if (CmpRHSV == 0) {       // (X / pos) op 0
874202375Srdivacky      // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
875218893Sdim      LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
876218893Sdim      HiBound = RangeSize;
877202375Srdivacky    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
878202375Srdivacky      LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
879202375Srdivacky      HiOverflow = LoOverflow = ProdOV;
880202375Srdivacky      if (!HiOverflow)
881218893Sdim        HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
882202375Srdivacky    } else {                       // (X / pos) op neg
883202375Srdivacky      // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
884202375Srdivacky      HiBound = AddOne(Prod);
885202375Srdivacky      LoOverflow = HiOverflow = ProdOV ? -1 : 0;
886202375Srdivacky      if (!LoOverflow) {
887218893Sdim        ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
888202375Srdivacky        LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
889218893Sdim      }
890202375Srdivacky    }
891224145Sdim  } else if (DivRHS->isNegative()) { // Divisor is < 0.
892218893Sdim    if (DivI->isExact())
893218893Sdim      RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
894202375Srdivacky    if (CmpRHSV == 0) {       // (X / neg) op 0
895202375Srdivacky      // e.g. X/-5 op 0  --> [-4, 5)
896218893Sdim      LoBound = AddOne(RangeSize);
897218893Sdim      HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
898202375Srdivacky      if (HiBound == DivRHS) {     // -INTMIN = INTMIN
899202375Srdivacky        HiOverflow = 1;            // [INTMIN+1, overflow)
900202375Srdivacky        HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
901202375Srdivacky      }
902202375Srdivacky    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
903202375Srdivacky      // e.g. X/-5 op 3  --> [-19, -14)
904202375Srdivacky      HiBound = AddOne(Prod);
905202375Srdivacky      HiOverflow = LoOverflow = ProdOV ? -1 : 0;
906202375Srdivacky      if (!LoOverflow)
907218893Sdim        LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
908202375Srdivacky    } else {                       // (X / neg) op neg
909202375Srdivacky      LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
910202375Srdivacky      LoOverflow = HiOverflow = ProdOV;
911202375Srdivacky      if (!HiOverflow)
912218893Sdim        HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
913202375Srdivacky    }
914226633Sdim
915202375Srdivacky    // Dividing by a negative swaps the condition.  LT <-> GT
916202375Srdivacky    Pred = ICmpInst::getSwappedPredicate(Pred);
917202375Srdivacky  }
918202375Srdivacky
919202375Srdivacky  Value *X = DivI->getOperand(0);
920202375Srdivacky  switch (Pred) {
921202375Srdivacky  default: llvm_unreachable("Unhandled icmp opcode!");
922202375Srdivacky  case ICmpInst::ICMP_EQ:
923202375Srdivacky    if (LoOverflow && HiOverflow)
924202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
925204792Srdivacky    if (HiOverflow)
926202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
927202375Srdivacky                          ICmpInst::ICMP_UGE, X, LoBound);
928204792Srdivacky    if (LoOverflow)
929202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
930202375Srdivacky                          ICmpInst::ICMP_ULT, X, HiBound);
931218893Sdim    return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
932218893Sdim                                                    DivIsSigned, true));
933202375Srdivacky  case ICmpInst::ICMP_NE:
934202375Srdivacky    if (LoOverflow && HiOverflow)
935202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
936204792Srdivacky    if (HiOverflow)
937202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
938202375Srdivacky                          ICmpInst::ICMP_ULT, X, LoBound);
939204792Srdivacky    if (LoOverflow)
940202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
941202375Srdivacky                          ICmpInst::ICMP_UGE, X, HiBound);
942204792Srdivacky    return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
943204792Srdivacky                                                    DivIsSigned, false));
944202375Srdivacky  case ICmpInst::ICMP_ULT:
945202375Srdivacky  case ICmpInst::ICMP_SLT:
946202375Srdivacky    if (LoOverflow == +1)   // Low bound is greater than input range.
947202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
948202375Srdivacky    if (LoOverflow == -1)   // Low bound is less than input range.
949202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
950202375Srdivacky    return new ICmpInst(Pred, X, LoBound);
951202375Srdivacky  case ICmpInst::ICMP_UGT:
952202375Srdivacky  case ICmpInst::ICMP_SGT:
953202375Srdivacky    if (HiOverflow == +1)       // High bound greater than input range.
954202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
955218893Sdim    if (HiOverflow == -1)       // High bound less than input range.
956202375Srdivacky      return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
957202375Srdivacky    if (Pred == ICmpInst::ICMP_UGT)
958202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
959218893Sdim    return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
960202375Srdivacky  }
961202375Srdivacky}
962202375Srdivacky
963218893Sdim/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
964218893SdimInstruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
965218893Sdim                                          ConstantInt *ShAmt) {
966218893Sdim  const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
967226633Sdim
968218893Sdim  // Check that the shift amount is in range.  If not, don't perform
969218893Sdim  // undefined shifts.  When the shift is visited it will be
970218893Sdim  // simplified.
971218893Sdim  uint32_t TypeBits = CmpRHSV.getBitWidth();
972218893Sdim  uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
973218893Sdim  if (ShAmtVal >= TypeBits || ShAmtVal == 0)
974218893Sdim    return 0;
975226633Sdim
976218893Sdim  if (!ICI.isEquality()) {
977218893Sdim    // If we have an unsigned comparison and an ashr, we can't simplify this.
978218893Sdim    // Similarly for signed comparisons with lshr.
979218893Sdim    if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
980218893Sdim      return 0;
981226633Sdim
982223017Sdim    // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
983223017Sdim    // by a power of 2.  Since we already have logic to simplify these,
984223017Sdim    // transform to div and then simplify the resultant comparison.
985218893Sdim    if (Shr->getOpcode() == Instruction::AShr &&
986223017Sdim        (!Shr->isExact() || ShAmtVal == TypeBits - 1))
987218893Sdim      return 0;
988226633Sdim
989218893Sdim    // Revisit the shift (to delete it).
990218893Sdim    Worklist.Add(Shr);
991226633Sdim
992218893Sdim    Constant *DivCst =
993218893Sdim      ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
994226633Sdim
995218893Sdim    Value *Tmp =
996218893Sdim      Shr->getOpcode() == Instruction::AShr ?
997218893Sdim      Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
998218893Sdim      Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
999226633Sdim
1000218893Sdim    ICI.setOperand(0, Tmp);
1001226633Sdim
1002218893Sdim    // If the builder folded the binop, just return it.
1003218893Sdim    BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1004218893Sdim    if (TheDiv == 0)
1005218893Sdim      return &ICI;
1006226633Sdim
1007218893Sdim    // Otherwise, fold this div/compare.
1008218893Sdim    assert(TheDiv->getOpcode() == Instruction::SDiv ||
1009218893Sdim           TheDiv->getOpcode() == Instruction::UDiv);
1010226633Sdim
1011218893Sdim    Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1012218893Sdim    assert(Res && "This div/cst should have folded!");
1013218893Sdim    return Res;
1014218893Sdim  }
1015226633Sdim
1016226633Sdim
1017218893Sdim  // If we are comparing against bits always shifted out, the
1018218893Sdim  // comparison cannot succeed.
1019218893Sdim  APInt Comp = CmpRHSV << ShAmtVal;
1020218893Sdim  ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
1021218893Sdim  if (Shr->getOpcode() == Instruction::LShr)
1022218893Sdim    Comp = Comp.lshr(ShAmtVal);
1023218893Sdim  else
1024218893Sdim    Comp = Comp.ashr(ShAmtVal);
1025226633Sdim
1026218893Sdim  if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1027218893Sdim    bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1028218893Sdim    Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1029218893Sdim                                     IsICMP_NE);
1030218893Sdim    return ReplaceInstUsesWith(ICI, Cst);
1031218893Sdim  }
1032226633Sdim
1033218893Sdim  // Otherwise, check to see if the bits shifted out are known to be zero.
1034218893Sdim  // If so, we can compare against the unshifted value:
1035218893Sdim  //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
1036218893Sdim  if (Shr->hasOneUse() && Shr->isExact())
1037218893Sdim    return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1038226633Sdim
1039218893Sdim  if (Shr->hasOneUse()) {
1040218893Sdim    // Otherwise strength reduce the shift into an and.
1041218893Sdim    APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1042218893Sdim    Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
1043226633Sdim
1044218893Sdim    Value *And = Builder->CreateAnd(Shr->getOperand(0),
1045218893Sdim                                    Mask, Shr->getName()+".mask");
1046218893Sdim    return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1047218893Sdim  }
1048218893Sdim  return 0;
1049218893Sdim}
1050202375Srdivacky
1051218893Sdim
1052202375Srdivacky/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1053202375Srdivacky///
1054202375SrdivackyInstruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1055202375Srdivacky                                                          Instruction *LHSI,
1056202375Srdivacky                                                          ConstantInt *RHS) {
1057202375Srdivacky  const APInt &RHSV = RHS->getValue();
1058226633Sdim
1059202375Srdivacky  switch (LHSI->getOpcode()) {
1060202375Srdivacky  case Instruction::Trunc:
1061202375Srdivacky    if (ICI.isEquality() && LHSI->hasOneUse()) {
1062202375Srdivacky      // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1063202375Srdivacky      // of the high bits truncated out of x are known.
1064202375Srdivacky      unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1065202375Srdivacky             SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1066202375Srdivacky      APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1067234353Sdim      ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
1068226633Sdim
1069202375Srdivacky      // If all the high bits are known, we can do this xform.
1070202375Srdivacky      if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1071202375Srdivacky        // Pull in the high bits from known-ones set.
1072218893Sdim        APInt NewRHS = RHS->getValue().zext(SrcBits);
1073239462Sdim        NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1074202375Srdivacky        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1075202375Srdivacky                            ConstantInt::get(ICI.getContext(), NewRHS));
1076202375Srdivacky      }
1077202375Srdivacky    }
1078202375Srdivacky    break;
1079226633Sdim
1080202375Srdivacky  case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
1081202375Srdivacky    if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1082202375Srdivacky      // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1083202375Srdivacky      // fold the xor.
1084202375Srdivacky      if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1085202375Srdivacky          (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1086202375Srdivacky        Value *CompareVal = LHSI->getOperand(0);
1087226633Sdim
1088202375Srdivacky        // If the sign bit of the XorCST is not set, there is no change to
1089202375Srdivacky        // the operation, just stop using the Xor.
1090224145Sdim        if (!XorCST->isNegative()) {
1091202375Srdivacky          ICI.setOperand(0, CompareVal);
1092202375Srdivacky          Worklist.Add(LHSI);
1093202375Srdivacky          return &ICI;
1094202375Srdivacky        }
1095226633Sdim
1096202375Srdivacky        // Was the old condition true if the operand is positive?
1097202375Srdivacky        bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1098226633Sdim
1099202375Srdivacky        // If so, the new one isn't.
1100202375Srdivacky        isTrueIfPositive ^= true;
1101226633Sdim
1102202375Srdivacky        if (isTrueIfPositive)
1103202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1104202375Srdivacky                              SubOne(RHS));
1105202375Srdivacky        else
1106202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1107202375Srdivacky                              AddOne(RHS));
1108202375Srdivacky      }
1109202375Srdivacky
1110202375Srdivacky      if (LHSI->hasOneUse()) {
1111202375Srdivacky        // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1112202375Srdivacky        if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1113202375Srdivacky          const APInt &SignBit = XorCST->getValue();
1114202375Srdivacky          ICmpInst::Predicate Pred = ICI.isSigned()
1115202375Srdivacky                                         ? ICI.getUnsignedPredicate()
1116202375Srdivacky                                         : ICI.getSignedPredicate();
1117202375Srdivacky          return new ICmpInst(Pred, LHSI->getOperand(0),
1118202375Srdivacky                              ConstantInt::get(ICI.getContext(),
1119202375Srdivacky                                               RHSV ^ SignBit));
1120202375Srdivacky        }
1121202375Srdivacky
1122202375Srdivacky        // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1123224145Sdim        if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
1124202375Srdivacky          const APInt &NotSignBit = XorCST->getValue();
1125202375Srdivacky          ICmpInst::Predicate Pred = ICI.isSigned()
1126202375Srdivacky                                         ? ICI.getUnsignedPredicate()
1127202375Srdivacky                                         : ICI.getSignedPredicate();
1128202375Srdivacky          Pred = ICI.getSwappedPredicate(Pred);
1129202375Srdivacky          return new ICmpInst(Pred, LHSI->getOperand(0),
1130202375Srdivacky                              ConstantInt::get(ICI.getContext(),
1131202375Srdivacky                                               RHSV ^ NotSignBit));
1132202375Srdivacky        }
1133202375Srdivacky      }
1134202375Srdivacky    }
1135202375Srdivacky    break;
1136202375Srdivacky  case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
1137202375Srdivacky    if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1138202375Srdivacky        LHSI->getOperand(0)->hasOneUse()) {
1139202375Srdivacky      ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1140226633Sdim
1141202375Srdivacky      // If the LHS is an AND of a truncating cast, we can widen the
1142202375Srdivacky      // and/compare to be the input width without changing the value
1143202375Srdivacky      // produced, eliminating a cast.
1144202375Srdivacky      if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1145202375Srdivacky        // We can do this transformation if either the AND constant does not
1146226633Sdim        // have its sign bit set or if it is an equality comparison.
1147202375Srdivacky        // Extending a relational comparison when we're checking the sign
1148202375Srdivacky        // bit would not work.
1149224145Sdim        if (ICI.isEquality() ||
1150224145Sdim            (!AndCST->isNegative() && RHSV.isNonNegative())) {
1151224145Sdim          Value *NewAnd =
1152202375Srdivacky            Builder->CreateAnd(Cast->getOperand(0),
1153224145Sdim                               ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1154224145Sdim          NewAnd->takeName(LHSI);
1155202375Srdivacky          return new ICmpInst(ICI.getPredicate(), NewAnd,
1156224145Sdim                              ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1157202375Srdivacky        }
1158202375Srdivacky      }
1159224145Sdim
1160224145Sdim      // If the LHS is an AND of a zext, and we have an equality compare, we can
1161224145Sdim      // shrink the and/compare to the smaller type, eliminating the cast.
1162224145Sdim      if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1163226633Sdim        IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1164224145Sdim        // Make sure we don't compare the upper bits, SimplifyDemandedBits
1165224145Sdim        // should fold the icmp to true/false in that case.
1166224145Sdim        if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1167224145Sdim          Value *NewAnd =
1168224145Sdim            Builder->CreateAnd(Cast->getOperand(0),
1169224145Sdim                               ConstantExpr::getTrunc(AndCST, Ty));
1170224145Sdim          NewAnd->takeName(LHSI);
1171224145Sdim          return new ICmpInst(ICI.getPredicate(), NewAnd,
1172224145Sdim                              ConstantExpr::getTrunc(RHS, Ty));
1173224145Sdim        }
1174224145Sdim      }
1175224145Sdim
1176202375Srdivacky      // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1177202375Srdivacky      // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1178202375Srdivacky      // happens a LOT in code produced by the C front-end, for bitfield
1179202375Srdivacky      // access.
1180202375Srdivacky      BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1181202375Srdivacky      if (Shift && !Shift->isShift())
1182202375Srdivacky        Shift = 0;
1183226633Sdim
1184202375Srdivacky      ConstantInt *ShAmt;
1185202375Srdivacky      ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1186226633Sdim      Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
1187226633Sdim      Type *AndTy = AndCST->getType();          // Type of the and.
1188226633Sdim
1189202375Srdivacky      // We can fold this as long as we can't shift unknown bits
1190202375Srdivacky      // into the mask.  This can only happen with signed shift
1191202375Srdivacky      // rights, as they sign-extend.
1192202375Srdivacky      if (ShAmt) {
1193202375Srdivacky        bool CanFold = Shift->isLogicalShift();
1194202375Srdivacky        if (!CanFold) {
1195202375Srdivacky          // To test for the bad case of the signed shr, see if any
1196202375Srdivacky          // of the bits shifted in could be tested after the mask.
1197202375Srdivacky          uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1198202375Srdivacky          int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1199226633Sdim
1200202375Srdivacky          uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1201226633Sdim          if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
1202202375Srdivacky               AndCST->getValue()) == 0)
1203202375Srdivacky            CanFold = true;
1204202375Srdivacky        }
1205226633Sdim
1206202375Srdivacky        if (CanFold) {
1207202375Srdivacky          Constant *NewCst;
1208202375Srdivacky          if (Shift->getOpcode() == Instruction::Shl)
1209202375Srdivacky            NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1210202375Srdivacky          else
1211202375Srdivacky            NewCst = ConstantExpr::getShl(RHS, ShAmt);
1212226633Sdim
1213202375Srdivacky          // Check to see if we are shifting out any of the bits being
1214202375Srdivacky          // compared.
1215202375Srdivacky          if (ConstantExpr::get(Shift->getOpcode(),
1216202375Srdivacky                                       NewCst, ShAmt) != RHS) {
1217202375Srdivacky            // If we shifted bits out, the fold is not going to work out.
1218202375Srdivacky            // As a special case, check to see if this means that the
1219202375Srdivacky            // result is always true or false now.
1220202375Srdivacky            if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1221202375Srdivacky              return ReplaceInstUsesWith(ICI,
1222202375Srdivacky                                       ConstantInt::getFalse(ICI.getContext()));
1223202375Srdivacky            if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1224202375Srdivacky              return ReplaceInstUsesWith(ICI,
1225202375Srdivacky                                       ConstantInt::getTrue(ICI.getContext()));
1226202375Srdivacky          } else {
1227202375Srdivacky            ICI.setOperand(1, NewCst);
1228202375Srdivacky            Constant *NewAndCST;
1229202375Srdivacky            if (Shift->getOpcode() == Instruction::Shl)
1230202375Srdivacky              NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1231202375Srdivacky            else
1232202375Srdivacky              NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1233202375Srdivacky            LHSI->setOperand(1, NewAndCST);
1234202375Srdivacky            LHSI->setOperand(0, Shift->getOperand(0));
1235202375Srdivacky            Worklist.Add(Shift); // Shift is dead.
1236202375Srdivacky            return &ICI;
1237202375Srdivacky          }
1238202375Srdivacky        }
1239202375Srdivacky      }
1240226633Sdim
1241202375Srdivacky      // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1242202375Srdivacky      // preferable because it allows the C<<Y expression to be hoisted out
1243202375Srdivacky      // of a loop if Y is invariant and X is not.
1244202375Srdivacky      if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1245202375Srdivacky          ICI.isEquality() && !Shift->isArithmeticShift() &&
1246202375Srdivacky          !isa<Constant>(Shift->getOperand(0))) {
1247202375Srdivacky        // Compute C << Y.
1248202375Srdivacky        Value *NS;
1249202375Srdivacky        if (Shift->getOpcode() == Instruction::LShr) {
1250226633Sdim          NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
1251202375Srdivacky        } else {
1252202375Srdivacky          // Insert a logical shift.
1253226633Sdim          NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
1254202375Srdivacky        }
1255226633Sdim
1256202375Srdivacky        // Compute X & (C << Y).
1257226633Sdim        Value *NewAnd =
1258202375Srdivacky          Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1259226633Sdim
1260202375Srdivacky        ICI.setOperand(0, NewAnd);
1261202375Srdivacky        return &ICI;
1262202375Srdivacky      }
1263249423Sdim
1264249423Sdim      // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1265249423Sdim      // bit set in (X & AndCST) will produce a result greater than RHSV.
1266249423Sdim      if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1267249423Sdim        unsigned NTZ = AndCST->getValue().countTrailingZeros();
1268249423Sdim        if ((NTZ < AndCST->getBitWidth()) &&
1269249423Sdim            APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1270249423Sdim          return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1271249423Sdim                              Constant::getNullValue(RHS->getType()));
1272249423Sdim      }
1273202375Srdivacky    }
1274226633Sdim
1275202375Srdivacky    // Try to optimize things like "A[i]&42 == 0" to index computations.
1276202375Srdivacky    if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1277202375Srdivacky      if (GetElementPtrInst *GEP =
1278202375Srdivacky          dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1279202375Srdivacky        if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1280202375Srdivacky          if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1281202375Srdivacky              !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1282202375Srdivacky            ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1283202375Srdivacky            if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1284202375Srdivacky              return Res;
1285202375Srdivacky          }
1286202375Srdivacky    }
1287202375Srdivacky    break;
1288202375Srdivacky
1289202375Srdivacky  case Instruction::Or: {
1290202375Srdivacky    if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1291202375Srdivacky      break;
1292202375Srdivacky    Value *P, *Q;
1293202375Srdivacky    if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1294202375Srdivacky      // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1295202375Srdivacky      // -> and (icmp eq P, null), (icmp eq Q, null).
1296202375Srdivacky      Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1297202375Srdivacky                                        Constant::getNullValue(P->getType()));
1298202375Srdivacky      Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1299202375Srdivacky                                        Constant::getNullValue(Q->getType()));
1300202375Srdivacky      Instruction *Op;
1301202375Srdivacky      if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1302202375Srdivacky        Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1303202375Srdivacky      else
1304202375Srdivacky        Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1305202375Srdivacky      return Op;
1306202375Srdivacky    }
1307202375Srdivacky    break;
1308202375Srdivacky  }
1309226633Sdim
1310249423Sdim  case Instruction::Mul: {       // (icmp pred (mul X, Val), CI)
1311249423Sdim    ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1312249423Sdim    if (!Val) break;
1313249423Sdim
1314249423Sdim    // If this is a signed comparison to 0 and the mul is sign preserving,
1315249423Sdim    // use the mul LHS operand instead.
1316249423Sdim    ICmpInst::Predicate pred = ICI.getPredicate();
1317249423Sdim    if (isSignTest(pred, RHS) && !Val->isZero() &&
1318249423Sdim        cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1319249423Sdim      return new ICmpInst(Val->isNegative() ?
1320249423Sdim                          ICmpInst::getSwappedPredicate(pred) : pred,
1321249423Sdim                          LHSI->getOperand(0),
1322249423Sdim                          Constant::getNullValue(RHS->getType()));
1323249423Sdim
1324249423Sdim    break;
1325249423Sdim  }
1326249423Sdim
1327202375Srdivacky  case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1328202375Srdivacky    ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1329202375Srdivacky    if (!ShAmt) break;
1330226633Sdim
1331202375Srdivacky    uint32_t TypeBits = RHSV.getBitWidth();
1332226633Sdim
1333202375Srdivacky    // Check that the shift amount is in range.  If not, don't perform
1334202375Srdivacky    // undefined shifts.  When the shift is visited it will be
1335202375Srdivacky    // simplified.
1336202375Srdivacky    if (ShAmt->uge(TypeBits))
1337202375Srdivacky      break;
1338226633Sdim
1339202375Srdivacky    if (ICI.isEquality()) {
1340202375Srdivacky      // If we are comparing against bits always shifted out, the
1341202375Srdivacky      // comparison cannot succeed.
1342202375Srdivacky      Constant *Comp =
1343202375Srdivacky        ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1344202375Srdivacky                                                                 ShAmt);
1345202375Srdivacky      if (Comp != RHS) {// Comparing against a bit that we know is zero.
1346202375Srdivacky        bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1347202375Srdivacky        Constant *Cst =
1348202375Srdivacky          ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1349202375Srdivacky        return ReplaceInstUsesWith(ICI, Cst);
1350202375Srdivacky      }
1351226633Sdim
1352218893Sdim      // If the shift is NUW, then it is just shifting out zeros, no need for an
1353218893Sdim      // AND.
1354218893Sdim      if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1355218893Sdim        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1356218893Sdim                            ConstantExpr::getLShr(RHS, ShAmt));
1357226633Sdim
1358249423Sdim      // If the shift is NSW and we compare to 0, then it is just shifting out
1359249423Sdim      // sign bits, no need for an AND either.
1360249423Sdim      if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1361249423Sdim        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1362249423Sdim                            ConstantExpr::getLShr(RHS, ShAmt));
1363249423Sdim
1364202375Srdivacky      if (LHSI->hasOneUse()) {
1365202375Srdivacky        // Otherwise strength reduce the shift into an and.
1366202375Srdivacky        uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1367202375Srdivacky        Constant *Mask =
1368226633Sdim          ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
1369202375Srdivacky                                                       TypeBits-ShAmtVal));
1370226633Sdim
1371202375Srdivacky        Value *And =
1372202375Srdivacky          Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1373202375Srdivacky        return new ICmpInst(ICI.getPredicate(), And,
1374218893Sdim                            ConstantExpr::getLShr(RHS, ShAmt));
1375202375Srdivacky      }
1376202375Srdivacky    }
1377226633Sdim
1378249423Sdim    // If this is a signed comparison to 0 and the shift is sign preserving,
1379249423Sdim    // use the shift LHS operand instead.
1380249423Sdim    ICmpInst::Predicate pred = ICI.getPredicate();
1381249423Sdim    if (isSignTest(pred, RHS) &&
1382249423Sdim        cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1383249423Sdim      return new ICmpInst(pred,
1384249423Sdim                          LHSI->getOperand(0),
1385249423Sdim                          Constant::getNullValue(RHS->getType()));
1386249423Sdim
1387202375Srdivacky    // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1388202375Srdivacky    bool TrueIfSigned = false;
1389202375Srdivacky    if (LHSI->hasOneUse() &&
1390202375Srdivacky        isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1391202375Srdivacky      // (X << 31) <s 0  --> (X&1) != 0
1392218893Sdim      Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1393226633Sdim                                        APInt::getOneBitSet(TypeBits,
1394218893Sdim                                            TypeBits-ShAmt->getZExtValue()-1));
1395202375Srdivacky      Value *And =
1396202375Srdivacky        Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1397202375Srdivacky      return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1398202375Srdivacky                          And, Constant::getNullValue(And->getType()));
1399202375Srdivacky    }
1400249423Sdim
1401249423Sdim    // Transform (icmp pred iM (shl iM %v, N), CI)
1402249423Sdim    // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1403249423Sdim    // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
1404249423Sdim    // This enables to get rid of the shift in favor of a trunc which can be
1405249423Sdim    // free on the target. It has the additional benefit of comparing to a
1406249423Sdim    // smaller constant, which will be target friendly.
1407249423Sdim    unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1408249423Sdim    if (LHSI->hasOneUse() &&
1409249423Sdim        Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1410249423Sdim      Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1411249423Sdim      Constant *NCI = ConstantExpr::getTrunc(
1412249423Sdim                        ConstantExpr::getAShr(RHS,
1413249423Sdim                          ConstantInt::get(RHS->getType(), Amt)),
1414249423Sdim                        NTy);
1415249423Sdim      return new ICmpInst(ICI.getPredicate(),
1416249423Sdim                          Builder->CreateTrunc(LHSI->getOperand(0), NTy),
1417249423Sdim                          NCI);
1418249423Sdim    }
1419249423Sdim
1420202375Srdivacky    break;
1421202375Srdivacky  }
1422226633Sdim
1423202375Srdivacky  case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1424221345Sdim  case Instruction::AShr: {
1425221345Sdim    // Handle equality comparisons of shift-by-constant.
1426221345Sdim    BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1427221345Sdim    if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1428221345Sdim      if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1429218893Sdim        return Res;
1430221345Sdim    }
1431221345Sdim
1432221345Sdim    // Handle exact shr's.
1433221345Sdim    if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1434221345Sdim      if (RHSV.isMinValue())
1435221345Sdim        return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1436221345Sdim    }
1437202375Srdivacky    break;
1438221345Sdim  }
1439226633Sdim
1440202375Srdivacky  case Instruction::SDiv:
1441202375Srdivacky  case Instruction::UDiv:
1442202375Srdivacky    // Fold: icmp pred ([us]div X, C1), C2 -> range test
1443226633Sdim    // Fold this div into the comparison, producing a range check.
1444226633Sdim    // Determine, based on the divide type, what the range is being
1445226633Sdim    // checked.  If there is an overflow on the low or high side, remember
1446202375Srdivacky    // it, otherwise compute the range [low, hi) bounding the new value.
1447202375Srdivacky    // See: InsertRangeTest above for the kinds of replacements possible.
1448202375Srdivacky    if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1449202375Srdivacky      if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1450202375Srdivacky                                          DivRHS))
1451202375Srdivacky        return R;
1452202375Srdivacky    break;
1453202375Srdivacky
1454202375Srdivacky  case Instruction::Add:
1455202375Srdivacky    // Fold: icmp pred (add X, C1), C2
1456202375Srdivacky    if (!ICI.isEquality()) {
1457202375Srdivacky      ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1458202375Srdivacky      if (!LHSC) break;
1459202375Srdivacky      const APInt &LHSV = LHSC->getValue();
1460202375Srdivacky
1461202375Srdivacky      ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1462202375Srdivacky                            .subtract(LHSV);
1463202375Srdivacky
1464202375Srdivacky      if (ICI.isSigned()) {
1465202375Srdivacky        if (CR.getLower().isSignBit()) {
1466202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1467202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getUpper()));
1468202375Srdivacky        } else if (CR.getUpper().isSignBit()) {
1469202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1470202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getLower()));
1471202375Srdivacky        }
1472202375Srdivacky      } else {
1473202375Srdivacky        if (CR.getLower().isMinValue()) {
1474202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1475202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getUpper()));
1476202375Srdivacky        } else if (CR.getUpper().isMinValue()) {
1477202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1478202375Srdivacky                              ConstantInt::get(ICI.getContext(),CR.getLower()));
1479202375Srdivacky        }
1480202375Srdivacky      }
1481202375Srdivacky    }
1482202375Srdivacky    break;
1483202375Srdivacky  }
1484226633Sdim
1485202375Srdivacky  // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1486202375Srdivacky  if (ICI.isEquality()) {
1487202375Srdivacky    bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1488226633Sdim
1489226633Sdim    // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1490202375Srdivacky    // the second operand is a constant, simplify a bit.
1491202375Srdivacky    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1492202375Srdivacky      switch (BO->getOpcode()) {
1493202375Srdivacky      case Instruction::SRem:
1494202375Srdivacky        // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1495202375Srdivacky        if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1496202375Srdivacky          const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1497207618Srdivacky          if (V.sgt(1) && V.isPowerOf2()) {
1498202375Srdivacky            Value *NewRem =
1499202375Srdivacky              Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1500202375Srdivacky                                  BO->getName());
1501202375Srdivacky            return new ICmpInst(ICI.getPredicate(), NewRem,
1502202375Srdivacky                                Constant::getNullValue(BO->getType()));
1503202375Srdivacky          }
1504202375Srdivacky        }
1505202375Srdivacky        break;
1506202375Srdivacky      case Instruction::Add:
1507202375Srdivacky        // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1508202375Srdivacky        if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1509202375Srdivacky          if (BO->hasOneUse())
1510202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1511202375Srdivacky                                ConstantExpr::getSub(RHS, BOp1C));
1512202375Srdivacky        } else if (RHSV == 0) {
1513202375Srdivacky          // Replace ((add A, B) != 0) with (A != -B) if A or B is
1514202375Srdivacky          // efficiently invertible, or if the add has just this one use.
1515202375Srdivacky          Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1516226633Sdim
1517202375Srdivacky          if (Value *NegVal = dyn_castNegVal(BOp1))
1518202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1519221345Sdim          if (Value *NegVal = dyn_castNegVal(BOp0))
1520202375Srdivacky            return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1521221345Sdim          if (BO->hasOneUse()) {
1522202375Srdivacky            Value *Neg = Builder->CreateNeg(BOp1);
1523202375Srdivacky            Neg->takeName(BO);
1524202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1525202375Srdivacky          }
1526202375Srdivacky        }
1527202375Srdivacky        break;
1528202375Srdivacky      case Instruction::Xor:
1529202375Srdivacky        // For the xor case, we can xor two constants together, eliminating
1530202375Srdivacky        // the explicit xor.
1531224145Sdim        if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1532224145Sdim          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1533202375Srdivacky                              ConstantExpr::getXor(RHS, BOC));
1534224145Sdim        } else if (RHSV == 0) {
1535224145Sdim          // Replace ((xor A, B) != 0) with (A != B)
1536224145Sdim          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1537224145Sdim                              BO->getOperand(1));
1538224145Sdim        }
1539224145Sdim        break;
1540202375Srdivacky      case Instruction::Sub:
1541224145Sdim        // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1542224145Sdim        if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1543224145Sdim          if (BO->hasOneUse())
1544224145Sdim            return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1545224145Sdim                                ConstantExpr::getSub(BOp0C, RHS));
1546224145Sdim        } else if (RHSV == 0) {
1547224145Sdim          // Replace ((sub A, B) != 0) with (A != B)
1548202375Srdivacky          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1549202375Srdivacky                              BO->getOperand(1));
1550224145Sdim        }
1551202375Srdivacky        break;
1552202375Srdivacky      case Instruction::Or:
1553202375Srdivacky        // If bits are being or'd in that are not present in the constant we
1554202375Srdivacky        // are comparing against, then the comparison could never succeed!
1555212904Sdim        if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1556202375Srdivacky          Constant *NotCI = ConstantExpr::getNot(RHS);
1557202375Srdivacky          if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1558202375Srdivacky            return ReplaceInstUsesWith(ICI,
1559226633Sdim                             ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1560202375Srdivacky                                       isICMP_NE));
1561202375Srdivacky        }
1562202375Srdivacky        break;
1563226633Sdim
1564202375Srdivacky      case Instruction::And:
1565202375Srdivacky        if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1566202375Srdivacky          // If bits are being compared against that are and'd out, then the
1567202375Srdivacky          // comparison can never succeed!
1568202375Srdivacky          if ((RHSV & ~BOC->getValue()) != 0)
1569202375Srdivacky            return ReplaceInstUsesWith(ICI,
1570202375Srdivacky                             ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1571202375Srdivacky                                       isICMP_NE));
1572226633Sdim
1573202375Srdivacky          // If we have ((X & C) == C), turn it into ((X & C) != 0).
1574202375Srdivacky          if (RHS == BOC && RHSV.isPowerOf2())
1575202375Srdivacky            return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1576202375Srdivacky                                ICmpInst::ICMP_NE, LHSI,
1577202375Srdivacky                                Constant::getNullValue(RHS->getType()));
1578224145Sdim
1579224145Sdim          // Don't perform the following transforms if the AND has multiple uses
1580224145Sdim          if (!BO->hasOneUse())
1581224145Sdim            break;
1582224145Sdim
1583202375Srdivacky          // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1584202375Srdivacky          if (BOC->getValue().isSignBit()) {
1585202375Srdivacky            Value *X = BO->getOperand(0);
1586202375Srdivacky            Constant *Zero = Constant::getNullValue(X->getType());
1587226633Sdim            ICmpInst::Predicate pred = isICMP_NE ?
1588202375Srdivacky              ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1589202375Srdivacky            return new ICmpInst(pred, X, Zero);
1590202375Srdivacky          }
1591226633Sdim
1592202375Srdivacky          // ((X & ~7) == 0) --> X < 8
1593202375Srdivacky          if (RHSV == 0 && isHighOnes(BOC)) {
1594202375Srdivacky            Value *X = BO->getOperand(0);
1595202375Srdivacky            Constant *NegX = ConstantExpr::getNeg(BOC);
1596226633Sdim            ICmpInst::Predicate pred = isICMP_NE ?
1597202375Srdivacky              ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1598202375Srdivacky            return new ICmpInst(pred, X, NegX);
1599202375Srdivacky          }
1600202375Srdivacky        }
1601249423Sdim        break;
1602249423Sdim      case Instruction::Mul:
1603249423Sdim        if (RHSV == 0 && BO->hasNoSignedWrap()) {
1604249423Sdim          if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1605249423Sdim            // The trivial case (mul X, 0) is handled by InstSimplify
1606249423Sdim            // General case : (mul X, C) != 0 iff X != 0
1607249423Sdim            //                (mul X, C) == 0 iff X == 0
1608249423Sdim            if (!BOC->isZero())
1609249423Sdim              return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1610249423Sdim                                  Constant::getNullValue(RHS->getType()));
1611249423Sdim          }
1612249423Sdim        }
1613249423Sdim        break;
1614202375Srdivacky      default: break;
1615202375Srdivacky      }
1616202375Srdivacky    } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1617202375Srdivacky      // Handle icmp {eq|ne} <intrinsic>, intcst.
1618202375Srdivacky      switch (II->getIntrinsicID()) {
1619202375Srdivacky      case Intrinsic::bswap:
1620202375Srdivacky        Worklist.Add(II);
1621210299Sed        ICI.setOperand(0, II->getArgOperand(0));
1622202375Srdivacky        ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1623202375Srdivacky        return &ICI;
1624202375Srdivacky      case Intrinsic::ctlz:
1625202375Srdivacky      case Intrinsic::cttz:
1626202375Srdivacky        // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1627202375Srdivacky        if (RHSV == RHS->getType()->getBitWidth()) {
1628202375Srdivacky          Worklist.Add(II);
1629210299Sed          ICI.setOperand(0, II->getArgOperand(0));
1630202375Srdivacky          ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1631202375Srdivacky          return &ICI;
1632202375Srdivacky        }
1633202375Srdivacky        break;
1634202375Srdivacky      case Intrinsic::ctpop:
1635202375Srdivacky        // popcount(A) == 0  ->  A == 0 and likewise for !=
1636202375Srdivacky        if (RHS->isZero()) {
1637202375Srdivacky          Worklist.Add(II);
1638210299Sed          ICI.setOperand(0, II->getArgOperand(0));
1639202375Srdivacky          ICI.setOperand(1, RHS);
1640202375Srdivacky          return &ICI;
1641202375Srdivacky        }
1642202375Srdivacky        break;
1643202375Srdivacky      default:
1644210299Sed        break;
1645202375Srdivacky      }
1646202375Srdivacky    }
1647202375Srdivacky  }
1648202375Srdivacky  return 0;
1649202375Srdivacky}
1650202375Srdivacky
1651202375Srdivacky/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1652202375Srdivacky/// We only handle extending casts so far.
1653202375Srdivacky///
1654202375SrdivackyInstruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1655202375Srdivacky  const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1656202375Srdivacky  Value *LHSCIOp        = LHSCI->getOperand(0);
1657226633Sdim  Type *SrcTy     = LHSCIOp->getType();
1658226633Sdim  Type *DestTy    = LHSCI->getType();
1659202375Srdivacky  Value *RHSCIOp;
1660202375Srdivacky
1661226633Sdim  // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1662202375Srdivacky  // integer type is the same size as the pointer type.
1663202375Srdivacky  if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1664202375Srdivacky      TD->getPointerSizeInBits() ==
1665202375Srdivacky         cast<IntegerType>(DestTy)->getBitWidth()) {
1666202375Srdivacky    Value *RHSOp = 0;
1667202375Srdivacky    if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1668202375Srdivacky      RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1669202375Srdivacky    } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1670202375Srdivacky      RHSOp = RHSC->getOperand(0);
1671202375Srdivacky      // If the pointer types don't match, insert a bitcast.
1672202375Srdivacky      if (LHSCIOp->getType() != RHSOp->getType())
1673202375Srdivacky        RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1674202375Srdivacky    }
1675202375Srdivacky
1676202375Srdivacky    if (RHSOp)
1677202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1678202375Srdivacky  }
1679226633Sdim
1680202375Srdivacky  // The code below only handles extension cast instructions, so far.
1681202375Srdivacky  // Enforce this.
1682202375Srdivacky  if (LHSCI->getOpcode() != Instruction::ZExt &&
1683202375Srdivacky      LHSCI->getOpcode() != Instruction::SExt)
1684202375Srdivacky    return 0;
1685202375Srdivacky
1686202375Srdivacky  bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1687202375Srdivacky  bool isSignedCmp = ICI.isSigned();
1688202375Srdivacky
1689202375Srdivacky  if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1690202375Srdivacky    // Not an extension from the same type?
1691202375Srdivacky    RHSCIOp = CI->getOperand(0);
1692226633Sdim    if (RHSCIOp->getType() != LHSCIOp->getType())
1693202375Srdivacky      return 0;
1694226633Sdim
1695202375Srdivacky    // If the signedness of the two casts doesn't agree (i.e. one is a sext
1696202375Srdivacky    // and the other is a zext), then we can't handle this.
1697202375Srdivacky    if (CI->getOpcode() != LHSCI->getOpcode())
1698202375Srdivacky      return 0;
1699202375Srdivacky
1700202375Srdivacky    // Deal with equality cases early.
1701202375Srdivacky    if (ICI.isEquality())
1702202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1703202375Srdivacky
1704202375Srdivacky    // A signed comparison of sign extended values simplifies into a
1705202375Srdivacky    // signed comparison.
1706202375Srdivacky    if (isSignedCmp && isSignedExt)
1707202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1708202375Srdivacky
1709202375Srdivacky    // The other three cases all fold into an unsigned comparison.
1710202375Srdivacky    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1711202375Srdivacky  }
1712202375Srdivacky
1713202375Srdivacky  // If we aren't dealing with a constant on the RHS, exit early
1714202375Srdivacky  ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1715202375Srdivacky  if (!CI)
1716202375Srdivacky    return 0;
1717202375Srdivacky
1718202375Srdivacky  // Compute the constant that would happen if we truncated to SrcTy then
1719202375Srdivacky  // reextended to DestTy.
1720202375Srdivacky  Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1721202375Srdivacky  Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1722202375Srdivacky                                                Res1, DestTy);
1723202375Srdivacky
1724202375Srdivacky  // If the re-extended constant didn't change...
1725202375Srdivacky  if (Res2 == CI) {
1726202375Srdivacky    // Deal with equality cases early.
1727202375Srdivacky    if (ICI.isEquality())
1728202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1729202375Srdivacky
1730202375Srdivacky    // A signed comparison of sign extended values simplifies into a
1731202375Srdivacky    // signed comparison.
1732202375Srdivacky    if (isSignedExt && isSignedCmp)
1733202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1734202375Srdivacky
1735202375Srdivacky    // The other three cases all fold into an unsigned comparison.
1736202375Srdivacky    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1737202375Srdivacky  }
1738202375Srdivacky
1739226633Sdim  // The re-extended constant changed so the constant cannot be represented
1740202375Srdivacky  // in the shorter type. Consequently, we cannot emit a simple comparison.
1741218893Sdim  // All the cases that fold to true or false will have already been handled
1742218893Sdim  // by SimplifyICmpInst, so only deal with the tricky case.
1743202375Srdivacky
1744218893Sdim  if (isSignedCmp || !isSignedExt)
1745218893Sdim    return 0;
1746202375Srdivacky
1747202375Srdivacky  // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1748202375Srdivacky  // should have been folded away previously and not enter in here.
1749202375Srdivacky
1750218893Sdim  // We're performing an unsigned comp with a sign extended value.
1751218893Sdim  // This is true if the input is >= 0. [aka >s -1]
1752218893Sdim  Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1753218893Sdim  Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1754218893Sdim
1755202375Srdivacky  // Finally, return the value computed.
1756218893Sdim  if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1757202375Srdivacky    return ReplaceInstUsesWith(ICI, Result);
1758202375Srdivacky
1759218893Sdim  assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1760202375Srdivacky  return BinaryOperator::CreateNot(Result);
1761202375Srdivacky}
1762202375Srdivacky
1763218893Sdim/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1764218893Sdim///   I = icmp ugt (add (add A, B), CI2), CI1
1765218893Sdim/// If this is of the form:
1766218893Sdim///   sum = a + b
1767218893Sdim///   if (sum+128 >u 255)
1768218893Sdim/// Then replace it with llvm.sadd.with.overflow.i8.
1769218893Sdim///
1770218893Sdimstatic Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1771218893Sdim                                          ConstantInt *CI2, ConstantInt *CI1,
1772218893Sdim                                          InstCombiner &IC) {
1773218893Sdim  // The transformation we're trying to do here is to transform this into an
1774218893Sdim  // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1775218893Sdim  // with a narrower add, and discard the add-with-constant that is part of the
1776218893Sdim  // range check (if we can't eliminate it, this isn't profitable).
1777226633Sdim
1778218893Sdim  // In order to eliminate the add-with-constant, the compare can be its only
1779218893Sdim  // use.
1780218893Sdim  Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1781218893Sdim  if (!AddWithCst->hasOneUse()) return 0;
1782226633Sdim
1783218893Sdim  // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1784218893Sdim  if (!CI2->getValue().isPowerOf2()) return 0;
1785218893Sdim  unsigned NewWidth = CI2->getValue().countTrailingZeros();
1786218893Sdim  if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1787226633Sdim
1788218893Sdim  // The width of the new add formed is 1 more than the bias.
1789218893Sdim  ++NewWidth;
1790226633Sdim
1791218893Sdim  // Check to see that CI1 is an all-ones value with NewWidth bits.
1792218893Sdim  if (CI1->getBitWidth() == NewWidth ||
1793218893Sdim      CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1794218893Sdim    return 0;
1795226633Sdim
1796234353Sdim  // This is only really a signed overflow check if the inputs have been
1797234353Sdim  // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1798234353Sdim  // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1799234353Sdim  unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1800234353Sdim  if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1801234353Sdim      IC.ComputeNumSignBits(B) < NeededSignBits)
1802234353Sdim    return 0;
1803234353Sdim
1804226633Sdim  // In order to replace the original add with a narrower
1805218893Sdim  // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1806218893Sdim  // and truncates that discard the high bits of the add.  Verify that this is
1807218893Sdim  // the case.
1808218893Sdim  Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1809218893Sdim  for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1810218893Sdim       UI != E; ++UI) {
1811218893Sdim    if (*UI == AddWithCst) continue;
1812226633Sdim
1813218893Sdim    // Only accept truncates for now.  We would really like a nice recursive
1814218893Sdim    // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1815218893Sdim    // chain to see which bits of a value are actually demanded.  If the
1816218893Sdim    // original add had another add which was then immediately truncated, we
1817218893Sdim    // could still do the transformation.
1818218893Sdim    TruncInst *TI = dyn_cast<TruncInst>(*UI);
1819218893Sdim    if (TI == 0 ||
1820218893Sdim        TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1821218893Sdim  }
1822226633Sdim
1823218893Sdim  // If the pattern matches, truncate the inputs to the narrower type and
1824218893Sdim  // use the sadd_with_overflow intrinsic to efficiently compute both the
1825218893Sdim  // result and the overflow bit.
1826218893Sdim  Module *M = I.getParent()->getParent()->getParent();
1827226633Sdim
1828224145Sdim  Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1829218893Sdim  Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1830224145Sdim                                       NewType);
1831202375Srdivacky
1832218893Sdim  InstCombiner::BuilderTy *Builder = IC.Builder;
1833226633Sdim
1834218893Sdim  // Put the new code above the original add, in case there are any uses of the
1835218893Sdim  // add between the add and the compare.
1836218893Sdim  Builder->SetInsertPoint(OrigAdd);
1837226633Sdim
1838218893Sdim  Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1839218893Sdim  Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1840218893Sdim  CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1841218893Sdim  Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1842218893Sdim  Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1843226633Sdim
1844218893Sdim  // The inner add was the result of the narrow add, zero extended to the
1845218893Sdim  // wider type.  Replace it with the result computed by the intrinsic.
1846218893Sdim  IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1847226633Sdim
1848218893Sdim  // The original icmp gets replaced with the overflow value.
1849218893Sdim  return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1850218893Sdim}
1851202375Srdivacky
1852218893Sdimstatic Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1853218893Sdim                                     InstCombiner &IC) {
1854218893Sdim  // Don't bother doing this transformation for pointers, don't do it for
1855218893Sdim  // vectors.
1856218893Sdim  if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1857226633Sdim
1858218893Sdim  // If the add is a constant expr, then we don't bother transforming it.
1859218893Sdim  Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1860218893Sdim  if (OrigAdd == 0) return 0;
1861226633Sdim
1862218893Sdim  Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1863226633Sdim
1864218893Sdim  // Put the new code above the original add, in case there are any uses of the
1865218893Sdim  // add between the add and the compare.
1866218893Sdim  InstCombiner::BuilderTy *Builder = IC.Builder;
1867218893Sdim  Builder->SetInsertPoint(OrigAdd);
1868218893Sdim
1869218893Sdim  Module *M = I.getParent()->getParent()->getParent();
1870224145Sdim  Type *Ty = LHS->getType();
1871224145Sdim  Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1872218893Sdim  CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1873218893Sdim  Value *Add = Builder->CreateExtractValue(Call, 0);
1874218893Sdim
1875218893Sdim  IC.ReplaceInstUsesWith(*OrigAdd, Add);
1876218893Sdim
1877218893Sdim  // The original icmp gets replaced with the overflow value.
1878218893Sdim  return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1879218893Sdim}
1880218893Sdim
1881218893Sdim// DemandedBitsLHSMask - When performing a comparison against a constant,
1882218893Sdim// it is possible that not all the bits in the LHS are demanded.  This helper
1883218893Sdim// method computes the mask that IS demanded.
1884218893Sdimstatic APInt DemandedBitsLHSMask(ICmpInst &I,
1885218893Sdim                                 unsigned BitWidth, bool isSignCheck) {
1886218893Sdim  if (isSignCheck)
1887218893Sdim    return APInt::getSignBit(BitWidth);
1888226633Sdim
1889218893Sdim  ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1890218893Sdim  if (!CI) return APInt::getAllOnesValue(BitWidth);
1891218893Sdim  const APInt &RHS = CI->getValue();
1892226633Sdim
1893218893Sdim  switch (I.getPredicate()) {
1894226633Sdim  // For a UGT comparison, we don't care about any bits that
1895218893Sdim  // correspond to the trailing ones of the comparand.  The value of these
1896218893Sdim  // bits doesn't impact the outcome of the comparison, because any value
1897218893Sdim  // greater than the RHS must differ in a bit higher than these due to carry.
1898218893Sdim  case ICmpInst::ICMP_UGT: {
1899218893Sdim    unsigned trailingOnes = RHS.countTrailingOnes();
1900218893Sdim    APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1901218893Sdim    return ~lowBitsSet;
1902218893Sdim  }
1903226633Sdim
1904218893Sdim  // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1905218893Sdim  // Any value less than the RHS must differ in a higher bit because of carries.
1906218893Sdim  case ICmpInst::ICMP_ULT: {
1907218893Sdim    unsigned trailingZeros = RHS.countTrailingZeros();
1908218893Sdim    APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1909218893Sdim    return ~lowBitsSet;
1910218893Sdim  }
1911226633Sdim
1912218893Sdim  default:
1913218893Sdim    return APInt::getAllOnesValue(BitWidth);
1914218893Sdim  }
1915226633Sdim
1916218893Sdim}
1917218893Sdim
1918202375SrdivackyInstruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1919202375Srdivacky  bool Changed = false;
1920203954Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1921226633Sdim
1922202375Srdivacky  /// Orders the operands of the compare so that they are listed from most
1923202375Srdivacky  /// complex to least complex.  This puts constants before unary operators,
1924202375Srdivacky  /// before binary operators.
1925203954Srdivacky  if (getComplexity(Op0) < getComplexity(Op1)) {
1926202375Srdivacky    I.swapOperands();
1927203954Srdivacky    std::swap(Op0, Op1);
1928202375Srdivacky    Changed = true;
1929202375Srdivacky  }
1930226633Sdim
1931202375Srdivacky  if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1932202375Srdivacky    return ReplaceInstUsesWith(I, V);
1933202375Srdivacky
1934234353Sdim  // comparing -val or val with non-zero is the same as just comparing val
1935234353Sdim  // ie, abs(val) != 0 -> val != 0
1936234353Sdim  if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1937234353Sdim  {
1938234353Sdim    Value *Cond, *SelectTrue, *SelectFalse;
1939234353Sdim    if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
1940234353Sdim                            m_Value(SelectFalse)))) {
1941234353Sdim      if (Value *V = dyn_castNegVal(SelectTrue)) {
1942234353Sdim        if (V == SelectFalse)
1943234353Sdim          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1944234353Sdim      }
1945234353Sdim      else if (Value *V = dyn_castNegVal(SelectFalse)) {
1946234353Sdim        if (V == SelectTrue)
1947234353Sdim          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1948234353Sdim      }
1949234353Sdim    }
1950234353Sdim  }
1951234353Sdim
1952226633Sdim  Type *Ty = Op0->getType();
1953226633Sdim
1954202375Srdivacky  // icmp's with boolean values can always be turned into bitwise operations
1955203954Srdivacky  if (Ty->isIntegerTy(1)) {
1956202375Srdivacky    switch (I.getPredicate()) {
1957202375Srdivacky    default: llvm_unreachable("Invalid icmp instruction!");
1958202375Srdivacky    case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
1959202375Srdivacky      Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1960202375Srdivacky      return BinaryOperator::CreateNot(Xor);
1961202375Srdivacky    }
1962202375Srdivacky    case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
1963202375Srdivacky      return BinaryOperator::CreateXor(Op0, Op1);
1964202375Srdivacky
1965202375Srdivacky    case ICmpInst::ICMP_UGT:
1966202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
1967202375Srdivacky      // FALL THROUGH
1968202375Srdivacky    case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
1969202375Srdivacky      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1970202375Srdivacky      return BinaryOperator::CreateAnd(Not, Op1);
1971202375Srdivacky    }
1972202375Srdivacky    case ICmpInst::ICMP_SGT:
1973202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
1974202375Srdivacky      // FALL THROUGH
1975202375Srdivacky    case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
1976202375Srdivacky      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1977202375Srdivacky      return BinaryOperator::CreateAnd(Not, Op0);
1978202375Srdivacky    }
1979202375Srdivacky    case ICmpInst::ICMP_UGE:
1980202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
1981202375Srdivacky      // FALL THROUGH
1982202375Srdivacky    case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
1983202375Srdivacky      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1984202375Srdivacky      return BinaryOperator::CreateOr(Not, Op1);
1985202375Srdivacky    }
1986202375Srdivacky    case ICmpInst::ICMP_SGE:
1987202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
1988202375Srdivacky      // FALL THROUGH
1989202375Srdivacky    case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
1990202375Srdivacky      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1991202375Srdivacky      return BinaryOperator::CreateOr(Not, Op0);
1992202375Srdivacky    }
1993202375Srdivacky    }
1994202375Srdivacky  }
1995202375Srdivacky
1996202375Srdivacky  unsigned BitWidth = 0;
1997218893Sdim  if (Ty->isIntOrIntVectorTy())
1998218893Sdim    BitWidth = Ty->getScalarSizeInBits();
1999218893Sdim  else if (TD)  // Pointers require TD info to get their size.
2000202375Srdivacky    BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
2001226633Sdim
2002202375Srdivacky  bool isSignBit = false;
2003202375Srdivacky
2004202375Srdivacky  // See if we are doing a comparison with a constant.
2005202375Srdivacky  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2006202375Srdivacky    Value *A = 0, *B = 0;
2007226633Sdim
2008218893Sdim    // Match the following pattern, which is a common idiom when writing
2009218893Sdim    // overflow-safe integer arithmetic function.  The source performs an
2010218893Sdim    // addition in wider type, and explicitly checks for overflow using
2011218893Sdim    // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
2012218893Sdim    // sadd_with_overflow intrinsic.
2013218893Sdim    //
2014218893Sdim    // TODO: This could probably be generalized to handle other overflow-safe
2015226633Sdim    // operations if we worked out the formulas to compute the appropriate
2016218893Sdim    // magic constants.
2017226633Sdim    //
2018218893Sdim    // sum = a + b
2019218893Sdim    // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
2020218893Sdim    {
2021218893Sdim    ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
2022218893Sdim    if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2023218893Sdim        match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
2024218893Sdim      if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
2025218893Sdim        return Res;
2026218893Sdim    }
2027226633Sdim
2028202375Srdivacky    // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2029202375Srdivacky    if (I.isEquality() && CI->isZero() &&
2030202375Srdivacky        match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2031202375Srdivacky      // (icmp cond A B) if cond is equality
2032202375Srdivacky      return new ICmpInst(I.getPredicate(), A, B);
2033202375Srdivacky    }
2034226633Sdim
2035202375Srdivacky    // If we have an icmp le or icmp ge instruction, turn it into the
2036202375Srdivacky    // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
2037202375Srdivacky    // them being folded in the code below.  The SimplifyICmpInst code has
2038202375Srdivacky    // already handled the edge cases for us, so we just assert on them.
2039202375Srdivacky    switch (I.getPredicate()) {
2040202375Srdivacky    default: break;
2041202375Srdivacky    case ICmpInst::ICMP_ULE:
2042202375Srdivacky      assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
2043202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
2044202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
2045202375Srdivacky    case ICmpInst::ICMP_SLE:
2046202375Srdivacky      assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
2047202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2048202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
2049202375Srdivacky    case ICmpInst::ICMP_UGE:
2050221345Sdim      assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
2051202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
2052202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
2053202375Srdivacky    case ICmpInst::ICMP_SGE:
2054221345Sdim      assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
2055202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2056202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
2057202375Srdivacky    }
2058226633Sdim
2059202375Srdivacky    // If this comparison is a normal comparison, it demands all
2060202375Srdivacky    // bits, if it is a sign bit comparison, it only demands the sign bit.
2061202375Srdivacky    bool UnusedBit;
2062202375Srdivacky    isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2063202375Srdivacky  }
2064202375Srdivacky
2065202375Srdivacky  // See if we can fold the comparison based on range information we can get
2066202375Srdivacky  // by checking whether bits are known to be zero or one in the input.
2067202375Srdivacky  if (BitWidth != 0) {
2068202375Srdivacky    APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2069202375Srdivacky    APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2070202375Srdivacky
2071202375Srdivacky    if (SimplifyDemandedBits(I.getOperandUse(0),
2072218893Sdim                             DemandedBitsLHSMask(I, BitWidth, isSignBit),
2073202375Srdivacky                             Op0KnownZero, Op0KnownOne, 0))
2074202375Srdivacky      return &I;
2075202375Srdivacky    if (SimplifyDemandedBits(I.getOperandUse(1),
2076202375Srdivacky                             APInt::getAllOnesValue(BitWidth),
2077202375Srdivacky                             Op1KnownZero, Op1KnownOne, 0))
2078202375Srdivacky      return &I;
2079202375Srdivacky
2080202375Srdivacky    // Given the known and unknown bits, compute a range that the LHS could be
2081202375Srdivacky    // in.  Compute the Min, Max and RHS values based on the known bits. For the
2082202375Srdivacky    // EQ and NE we use unsigned values.
2083202375Srdivacky    APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2084202375Srdivacky    APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2085202375Srdivacky    if (I.isSigned()) {
2086202375Srdivacky      ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2087202375Srdivacky                                             Op0Min, Op0Max);
2088202375Srdivacky      ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2089202375Srdivacky                                             Op1Min, Op1Max);
2090202375Srdivacky    } else {
2091202375Srdivacky      ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2092202375Srdivacky                                               Op0Min, Op0Max);
2093202375Srdivacky      ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2094202375Srdivacky                                               Op1Min, Op1Max);
2095202375Srdivacky    }
2096202375Srdivacky
2097202375Srdivacky    // If Min and Max are known to be the same, then SimplifyDemandedBits
2098202375Srdivacky    // figured out that the LHS is a constant.  Just constant fold this now so
2099202375Srdivacky    // that code below can assume that Min != Max.
2100202375Srdivacky    if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2101202375Srdivacky      return new ICmpInst(I.getPredicate(),
2102221345Sdim                          ConstantInt::get(Op0->getType(), Op0Min), Op1);
2103202375Srdivacky    if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2104202375Srdivacky      return new ICmpInst(I.getPredicate(), Op0,
2105221345Sdim                          ConstantInt::get(Op1->getType(), Op1Min));
2106202375Srdivacky
2107202375Srdivacky    // Based on the range information we know about the LHS, see if we can
2108221345Sdim    // simplify this comparison.  For example, (x&4) < 8 is always true.
2109202375Srdivacky    switch (I.getPredicate()) {
2110202375Srdivacky    default: llvm_unreachable("Unknown icmp opcode!");
2111218893Sdim    case ICmpInst::ICMP_EQ: {
2112202375Srdivacky      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2113221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2114226633Sdim
2115218893Sdim      // If all bits are known zero except for one, then we know at most one
2116218893Sdim      // bit is set.   If the comparison is against zero, then this is a check
2117218893Sdim      // to see if *that* bit is set.
2118218893Sdim      APInt Op0KnownZeroInverted = ~Op0KnownZero;
2119218893Sdim      if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2120218893Sdim        // If the LHS is an AND with the same constant, look through it.
2121218893Sdim        Value *LHS = 0;
2122218893Sdim        ConstantInt *LHSC = 0;
2123218893Sdim        if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2124218893Sdim            LHSC->getValue() != Op0KnownZeroInverted)
2125218893Sdim          LHS = Op0;
2126226633Sdim
2127218893Sdim        // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2128218893Sdim        // then turn "((1 << x)&8) == 0" into "x != 3".
2129218893Sdim        Value *X = 0;
2130218893Sdim        if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2131218893Sdim          unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2132218893Sdim          return new ICmpInst(ICmpInst::ICMP_NE, X,
2133218893Sdim                              ConstantInt::get(X->getType(), CmpVal));
2134218893Sdim        }
2135226633Sdim
2136218893Sdim        // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2137218893Sdim        // then turn "((8 >>u x)&1) == 0" into "x != 3".
2138218893Sdim        const APInt *CI;
2139218893Sdim        if (Op0KnownZeroInverted == 1 &&
2140218893Sdim            match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2141218893Sdim          return new ICmpInst(ICmpInst::ICMP_NE, X,
2142218893Sdim                              ConstantInt::get(X->getType(),
2143218893Sdim                                               CI->countTrailingZeros()));
2144218893Sdim      }
2145226633Sdim
2146202375Srdivacky      break;
2147218893Sdim    }
2148218893Sdim    case ICmpInst::ICMP_NE: {
2149202375Srdivacky      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2150221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2151226633Sdim
2152218893Sdim      // If all bits are known zero except for one, then we know at most one
2153218893Sdim      // bit is set.   If the comparison is against zero, then this is a check
2154218893Sdim      // to see if *that* bit is set.
2155218893Sdim      APInt Op0KnownZeroInverted = ~Op0KnownZero;
2156218893Sdim      if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2157218893Sdim        // If the LHS is an AND with the same constant, look through it.
2158218893Sdim        Value *LHS = 0;
2159218893Sdim        ConstantInt *LHSC = 0;
2160218893Sdim        if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2161218893Sdim            LHSC->getValue() != Op0KnownZeroInverted)
2162218893Sdim          LHS = Op0;
2163226633Sdim
2164218893Sdim        // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2165218893Sdim        // then turn "((1 << x)&8) != 0" into "x == 3".
2166218893Sdim        Value *X = 0;
2167218893Sdim        if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2168218893Sdim          unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2169218893Sdim          return new ICmpInst(ICmpInst::ICMP_EQ, X,
2170218893Sdim                              ConstantInt::get(X->getType(), CmpVal));
2171218893Sdim        }
2172226633Sdim
2173218893Sdim        // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2174218893Sdim        // then turn "((8 >>u x)&1) != 0" into "x == 3".
2175218893Sdim        const APInt *CI;
2176218893Sdim        if (Op0KnownZeroInverted == 1 &&
2177218893Sdim            match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2178218893Sdim          return new ICmpInst(ICmpInst::ICMP_EQ, X,
2179218893Sdim                              ConstantInt::get(X->getType(),
2180218893Sdim                                               CI->countTrailingZeros()));
2181218893Sdim      }
2182226633Sdim
2183202375Srdivacky      break;
2184218893Sdim    }
2185202375Srdivacky    case ICmpInst::ICMP_ULT:
2186202375Srdivacky      if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
2187221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2188202375Srdivacky      if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
2189221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2190202375Srdivacky      if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
2191202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2192202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2193202375Srdivacky        if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
2194202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2195202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
2196202375Srdivacky
2197202375Srdivacky        // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
2198202375Srdivacky        if (CI->isMinValue(true))
2199202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2200202375Srdivacky                           Constant::getAllOnesValue(Op0->getType()));
2201202375Srdivacky      }
2202202375Srdivacky      break;
2203202375Srdivacky    case ICmpInst::ICMP_UGT:
2204202375Srdivacky      if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2205221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2206202375Srdivacky      if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2207221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2208202375Srdivacky
2209202375Srdivacky      if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2210202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2211202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2212202375Srdivacky        if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2213202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2214202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
2215202375Srdivacky
2216202375Srdivacky        // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2217202375Srdivacky        if (CI->isMaxValue(true))
2218202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2219202375Srdivacky                              Constant::getNullValue(Op0->getType()));
2220202375Srdivacky      }
2221202375Srdivacky      break;
2222202375Srdivacky    case ICmpInst::ICMP_SLT:
2223202375Srdivacky      if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2224221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2225202375Srdivacky      if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2226221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2227202375Srdivacky      if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2228202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2229202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2230202375Srdivacky        if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2231202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2232202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()-1));
2233202375Srdivacky      }
2234202375Srdivacky      break;
2235202375Srdivacky    case ICmpInst::ICMP_SGT:
2236202375Srdivacky      if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2237221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2238202375Srdivacky      if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2239221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2240202375Srdivacky
2241202375Srdivacky      if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2242202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2243202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2244202375Srdivacky        if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2245202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2246202375Srdivacky                          ConstantInt::get(CI->getContext(), CI->getValue()+1));
2247202375Srdivacky      }
2248202375Srdivacky      break;
2249202375Srdivacky    case ICmpInst::ICMP_SGE:
2250202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2251202375Srdivacky      if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2252221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2253202375Srdivacky      if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2254221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2255202375Srdivacky      break;
2256202375Srdivacky    case ICmpInst::ICMP_SLE:
2257202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2258202375Srdivacky      if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2259221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2260202375Srdivacky      if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2261221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2262202375Srdivacky      break;
2263202375Srdivacky    case ICmpInst::ICMP_UGE:
2264202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2265202375Srdivacky      if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2266221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2267202375Srdivacky      if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2268221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2269202375Srdivacky      break;
2270202375Srdivacky    case ICmpInst::ICMP_ULE:
2271202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2272202375Srdivacky      if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2273221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2274202375Srdivacky      if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2275221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2276202375Srdivacky      break;
2277202375Srdivacky    }
2278202375Srdivacky
2279202375Srdivacky    // Turn a signed comparison into an unsigned one if both operands
2280202375Srdivacky    // are known to have the same sign.
2281202375Srdivacky    if (I.isSigned() &&
2282202375Srdivacky        ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2283202375Srdivacky         (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2284202375Srdivacky      return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2285202375Srdivacky  }
2286202375Srdivacky
2287202375Srdivacky  // Test if the ICmpInst instruction is used exclusively by a select as
2288202375Srdivacky  // part of a minimum or maximum operation. If so, refrain from doing
2289202375Srdivacky  // any other folding. This helps out other analyses which understand
2290202375Srdivacky  // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2291202375Srdivacky  // and CodeGen. And in this case, at least one of the comparison
2292202375Srdivacky  // operands has at least one user besides the compare (the select),
2293202375Srdivacky  // which would often largely negate the benefit of folding anyway.
2294202375Srdivacky  if (I.hasOneUse())
2295202375Srdivacky    if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2296202375Srdivacky      if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2297202375Srdivacky          (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2298202375Srdivacky        return 0;
2299202375Srdivacky
2300202375Srdivacky  // See if we are doing a comparison between a constant and an instruction that
2301202375Srdivacky  // can be folded into the comparison.
2302202375Srdivacky  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2303226633Sdim    // Since the RHS is a ConstantInt (CI), if the left hand side is an
2304226633Sdim    // instruction, see if that instruction also has constants so that the
2305226633Sdim    // instruction can be folded into the icmp
2306202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2307202375Srdivacky      if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2308202375Srdivacky        return Res;
2309202375Srdivacky  }
2310202375Srdivacky
2311202375Srdivacky  // Handle icmp with constant (but not simple integer constant) RHS
2312202375Srdivacky  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2313202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2314202375Srdivacky      switch (LHSI->getOpcode()) {
2315202375Srdivacky      case Instruction::GetElementPtr:
2316202375Srdivacky          // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2317202375Srdivacky        if (RHSC->isNullValue() &&
2318202375Srdivacky            cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2319202375Srdivacky          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2320202375Srdivacky                  Constant::getNullValue(LHSI->getOperand(0)->getType()));
2321202375Srdivacky        break;
2322202375Srdivacky      case Instruction::PHI:
2323202375Srdivacky        // Only fold icmp into the PHI if the phi and icmp are in the same
2324202375Srdivacky        // block.  If in the same block, we're encouraging jump threading.  If
2325202375Srdivacky        // not, we are just pessimizing the code by making an i1 phi.
2326202375Srdivacky        if (LHSI->getParent() == I.getParent())
2327218893Sdim          if (Instruction *NV = FoldOpIntoPhi(I))
2328202375Srdivacky            return NV;
2329202375Srdivacky        break;
2330202375Srdivacky      case Instruction::Select: {
2331202375Srdivacky        // If either operand of the select is a constant, we can fold the
2332202375Srdivacky        // comparison into the select arms, which will cause one to be
2333202375Srdivacky        // constant folded and the select turned into a bitwise or.
2334202375Srdivacky        Value *Op1 = 0, *Op2 = 0;
2335202375Srdivacky        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2336202375Srdivacky          Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2337202375Srdivacky        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2338202375Srdivacky          Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2339202375Srdivacky
2340202375Srdivacky        // We only want to perform this transformation if it will not lead to
2341202375Srdivacky        // additional code. This is true if either both sides of the select
2342202375Srdivacky        // fold to a constant (in which case the icmp is replaced with a select
2343202375Srdivacky        // which will usually simplify) or this is the only user of the
2344202375Srdivacky        // select (in which case we are trading a select+icmp for a simpler
2345202375Srdivacky        // select+icmp).
2346202375Srdivacky        if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2347202375Srdivacky          if (!Op1)
2348202375Srdivacky            Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2349202375Srdivacky                                      RHSC, I.getName());
2350202375Srdivacky          if (!Op2)
2351202375Srdivacky            Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2352202375Srdivacky                                      RHSC, I.getName());
2353202375Srdivacky          return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2354202375Srdivacky        }
2355202375Srdivacky        break;
2356202375Srdivacky      }
2357202375Srdivacky      case Instruction::IntToPtr:
2358202375Srdivacky        // icmp pred inttoptr(X), null -> icmp pred X, 0
2359202375Srdivacky        if (RHSC->isNullValue() && TD &&
2360226633Sdim            TD->getIntPtrType(RHSC->getContext()) ==
2361202375Srdivacky               LHSI->getOperand(0)->getType())
2362202375Srdivacky          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2363202375Srdivacky                        Constant::getNullValue(LHSI->getOperand(0)->getType()));
2364202375Srdivacky        break;
2365202375Srdivacky
2366202375Srdivacky      case Instruction::Load:
2367202375Srdivacky        // Try to optimize things like "A[i] > 4" to index computations.
2368202375Srdivacky        if (GetElementPtrInst *GEP =
2369202375Srdivacky              dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2370202375Srdivacky          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2371202375Srdivacky            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2372202375Srdivacky                !cast<LoadInst>(LHSI)->isVolatile())
2373202375Srdivacky              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2374202375Srdivacky                return Res;
2375202375Srdivacky        }
2376202375Srdivacky        break;
2377202375Srdivacky      }
2378202375Srdivacky  }
2379202375Srdivacky
2380202375Srdivacky  // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2381202375Srdivacky  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2382202375Srdivacky    if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2383202375Srdivacky      return NI;
2384202375Srdivacky  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2385202375Srdivacky    if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2386202375Srdivacky                           ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2387202375Srdivacky      return NI;
2388202375Srdivacky
2389202375Srdivacky  // Test to see if the operands of the icmp are casted versions of other
2390202375Srdivacky  // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2391202375Srdivacky  // now.
2392202375Srdivacky  if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2393226633Sdim    if (Op0->getType()->isPointerTy() &&
2394226633Sdim        (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2395202375Srdivacky      // We keep moving the cast from the left operand over to the right
2396202375Srdivacky      // operand, where it can often be eliminated completely.
2397202375Srdivacky      Op0 = CI->getOperand(0);
2398202375Srdivacky
2399202375Srdivacky      // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2400202375Srdivacky      // so eliminate it as well.
2401202375Srdivacky      if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2402202375Srdivacky        Op1 = CI2->getOperand(0);
2403202375Srdivacky
2404202375Srdivacky      // If Op1 is a constant, we can fold the cast into the constant.
2405202375Srdivacky      if (Op0->getType() != Op1->getType()) {
2406202375Srdivacky        if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2407202375Srdivacky          Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2408202375Srdivacky        } else {
2409202375Srdivacky          // Otherwise, cast the RHS right before the icmp
2410202375Srdivacky          Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2411202375Srdivacky        }
2412202375Srdivacky      }
2413202375Srdivacky      return new ICmpInst(I.getPredicate(), Op0, Op1);
2414202375Srdivacky    }
2415202375Srdivacky  }
2416226633Sdim
2417202375Srdivacky  if (isa<CastInst>(Op0)) {
2418202375Srdivacky    // Handle the special case of: icmp (cast bool to X), <cst>
2419202375Srdivacky    // This comes up when you have code like
2420202375Srdivacky    //   int X = A < B;
2421202375Srdivacky    //   if (X) ...
2422202375Srdivacky    // For generality, we handle any zero-extension of any operand comparison
2423202375Srdivacky    // with a constant or another cast from the same type.
2424202375Srdivacky    if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2425202375Srdivacky      if (Instruction *R = visitICmpInstWithCastAndCast(I))
2426202375Srdivacky        return R;
2427202375Srdivacky  }
2428218893Sdim
2429218893Sdim  // Special logic for binary operators.
2430218893Sdim  BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2431218893Sdim  BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2432218893Sdim  if (BO0 || BO1) {
2433218893Sdim    CmpInst::Predicate Pred = I.getPredicate();
2434218893Sdim    bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2435218893Sdim    if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2436218893Sdim      NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2437218893Sdim        (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2438218893Sdim        (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2439218893Sdim    if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2440218893Sdim      NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2441218893Sdim        (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2442218893Sdim        (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2443218893Sdim
2444218893Sdim    // Analyze the case when either Op0 or Op1 is an add instruction.
2445218893Sdim    // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2446218893Sdim    Value *A = 0, *B = 0, *C = 0, *D = 0;
2447218893Sdim    if (BO0 && BO0->getOpcode() == Instruction::Add)
2448218893Sdim      A = BO0->getOperand(0), B = BO0->getOperand(1);
2449218893Sdim    if (BO1 && BO1->getOpcode() == Instruction::Add)
2450218893Sdim      C = BO1->getOperand(0), D = BO1->getOperand(1);
2451218893Sdim
2452218893Sdim    // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2453218893Sdim    if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2454218893Sdim      return new ICmpInst(Pred, A == Op1 ? B : A,
2455218893Sdim                          Constant::getNullValue(Op1->getType()));
2456218893Sdim
2457218893Sdim    // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2458218893Sdim    if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2459218893Sdim      return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2460218893Sdim                          C == Op0 ? D : C);
2461218893Sdim
2462218893Sdim    // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2463218893Sdim    if (A && C && (A == C || A == D || B == C || B == D) &&
2464218893Sdim        NoOp0WrapProblem && NoOp1WrapProblem &&
2465218893Sdim        // Try not to increase register pressure.
2466218893Sdim        BO0->hasOneUse() && BO1->hasOneUse()) {
2467218893Sdim      // Determine Y and Z in the form icmp (X+Y), (X+Z).
2468243830Sdim      Value *Y, *Z;
2469243830Sdim      if (A == C) {
2470243830Sdim        // C + B == C + D  ->  B == D
2471243830Sdim        Y = B;
2472243830Sdim        Z = D;
2473243830Sdim      } else if (A == D) {
2474243830Sdim        // D + B == C + D  ->  B == C
2475243830Sdim        Y = B;
2476243830Sdim        Z = C;
2477243830Sdim      } else if (B == C) {
2478243830Sdim        // A + C == C + D  ->  A == D
2479243830Sdim        Y = A;
2480243830Sdim        Z = D;
2481243830Sdim      } else {
2482243830Sdim        assert(B == D);
2483243830Sdim        // A + D == C + D  ->  A == C
2484243830Sdim        Y = A;
2485243830Sdim        Z = C;
2486243830Sdim      }
2487218893Sdim      return new ICmpInst(Pred, Y, Z);
2488218893Sdim    }
2489218893Sdim
2490251662Sdim    // icmp slt (X + -1), Y -> icmp sle X, Y
2491251662Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2492251662Sdim        match(B, m_AllOnes()))
2493251662Sdim      return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2494251662Sdim
2495251662Sdim    // icmp sge (X + -1), Y -> icmp sgt X, Y
2496251662Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2497251662Sdim        match(B, m_AllOnes()))
2498251662Sdim      return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2499251662Sdim
2500251662Sdim    // icmp sle (X + 1), Y -> icmp slt X, Y
2501251662Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2502251662Sdim        match(B, m_One()))
2503251662Sdim      return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2504251662Sdim
2505251662Sdim    // icmp sgt (X + 1), Y -> icmp sge X, Y
2506251662Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2507251662Sdim        match(B, m_One()))
2508251662Sdim      return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2509251662Sdim
2510251662Sdim    // if C1 has greater magnitude than C2:
2511251662Sdim    //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2512251662Sdim    //  s.t. C3 = C1 - C2
2513251662Sdim    //
2514251662Sdim    // if C2 has greater magnitude than C1:
2515251662Sdim    //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2516251662Sdim    //  s.t. C3 = C2 - C1
2517251662Sdim    if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2518251662Sdim        (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2519251662Sdim      if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2520251662Sdim        if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2521251662Sdim          const APInt &AP1 = C1->getValue();
2522251662Sdim          const APInt &AP2 = C2->getValue();
2523251662Sdim          if (AP1.isNegative() == AP2.isNegative()) {
2524251662Sdim            APInt AP1Abs = C1->getValue().abs();
2525251662Sdim            APInt AP2Abs = C2->getValue().abs();
2526251662Sdim            if (AP1Abs.uge(AP2Abs)) {
2527251662Sdim              ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2528251662Sdim              Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2529251662Sdim              return new ICmpInst(Pred, NewAdd, C);
2530251662Sdim            } else {
2531251662Sdim              ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2532251662Sdim              Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2533251662Sdim              return new ICmpInst(Pred, A, NewAdd);
2534251662Sdim            }
2535251662Sdim          }
2536251662Sdim        }
2537251662Sdim
2538251662Sdim
2539218893Sdim    // Analyze the case when either Op0 or Op1 is a sub instruction.
2540218893Sdim    // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2541218893Sdim    A = 0; B = 0; C = 0; D = 0;
2542218893Sdim    if (BO0 && BO0->getOpcode() == Instruction::Sub)
2543218893Sdim      A = BO0->getOperand(0), B = BO0->getOperand(1);
2544218893Sdim    if (BO1 && BO1->getOpcode() == Instruction::Sub)
2545218893Sdim      C = BO1->getOperand(0), D = BO1->getOperand(1);
2546218893Sdim
2547218893Sdim    // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2548218893Sdim    if (A == Op1 && NoOp0WrapProblem)
2549218893Sdim      return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2550218893Sdim
2551218893Sdim    // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2552218893Sdim    if (C == Op0 && NoOp1WrapProblem)
2553218893Sdim      return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2554218893Sdim
2555218893Sdim    // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2556218893Sdim    if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2557218893Sdim        // Try not to increase register pressure.
2558218893Sdim        BO0->hasOneUse() && BO1->hasOneUse())
2559218893Sdim      return new ICmpInst(Pred, A, C);
2560218893Sdim
2561218893Sdim    // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2562218893Sdim    if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2563218893Sdim        // Try not to increase register pressure.
2564218893Sdim        BO0->hasOneUse() && BO1->hasOneUse())
2565218893Sdim      return new ICmpInst(Pred, D, B);
2566218893Sdim
2567221345Sdim    BinaryOperator *SRem = NULL;
2568221345Sdim    // icmp (srem X, Y), Y
2569221345Sdim    if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2570221345Sdim        Op1 == BO0->getOperand(1))
2571221345Sdim      SRem = BO0;
2572221345Sdim    // icmp Y, (srem X, Y)
2573221345Sdim    else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2574221345Sdim             Op0 == BO1->getOperand(1))
2575221345Sdim      SRem = BO1;
2576221345Sdim    if (SRem) {
2577221345Sdim      // We don't check hasOneUse to avoid increasing register pressure because
2578221345Sdim      // the value we use is the same value this instruction was already using.
2579221345Sdim      switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2580221345Sdim        default: break;
2581221345Sdim        case ICmpInst::ICMP_EQ:
2582221345Sdim          return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2583221345Sdim        case ICmpInst::ICMP_NE:
2584221345Sdim          return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2585221345Sdim        case ICmpInst::ICMP_SGT:
2586221345Sdim        case ICmpInst::ICMP_SGE:
2587221345Sdim          return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2588221345Sdim                              Constant::getAllOnesValue(SRem->getType()));
2589221345Sdim        case ICmpInst::ICMP_SLT:
2590221345Sdim        case ICmpInst::ICMP_SLE:
2591221345Sdim          return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2592221345Sdim                              Constant::getNullValue(SRem->getType()));
2593221345Sdim      }
2594221345Sdim    }
2595221345Sdim
2596218893Sdim    if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2597218893Sdim        BO0->hasOneUse() && BO1->hasOneUse() &&
2598218893Sdim        BO0->getOperand(1) == BO1->getOperand(1)) {
2599218893Sdim      switch (BO0->getOpcode()) {
2600218893Sdim      default: break;
2601218893Sdim      case Instruction::Add:
2602218893Sdim      case Instruction::Sub:
2603218893Sdim      case Instruction::Xor:
2604218893Sdim        if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2605218893Sdim          return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2606218893Sdim                              BO1->getOperand(0));
2607218893Sdim        // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2608218893Sdim        if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2609218893Sdim          if (CI->getValue().isSignBit()) {
2610218893Sdim            ICmpInst::Predicate Pred = I.isSigned()
2611218893Sdim                                           ? I.getUnsignedPredicate()
2612218893Sdim                                           : I.getSignedPredicate();
2613218893Sdim            return new ICmpInst(Pred, BO0->getOperand(0),
2614218893Sdim                                BO1->getOperand(0));
2615202375Srdivacky          }
2616226633Sdim
2617224145Sdim          if (CI->isMaxValue(true)) {
2618218893Sdim            ICmpInst::Predicate Pred = I.isSigned()
2619218893Sdim                                           ? I.getUnsignedPredicate()
2620218893Sdim                                           : I.getSignedPredicate();
2621218893Sdim            Pred = I.getSwappedPredicate(Pred);
2622218893Sdim            return new ICmpInst(Pred, BO0->getOperand(0),
2623218893Sdim                                BO1->getOperand(0));
2624218893Sdim          }
2625218893Sdim        }
2626218893Sdim        break;
2627218893Sdim      case Instruction::Mul:
2628218893Sdim        if (!I.isEquality())
2629202375Srdivacky          break;
2630202375Srdivacky
2631218893Sdim        if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2632218893Sdim          // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2633218893Sdim          // Mask = -1 >> count-trailing-zeros(Cst).
2634218893Sdim          if (!CI->isZero() && !CI->isOne()) {
2635218893Sdim            const APInt &AP = CI->getValue();
2636226633Sdim            ConstantInt *Mask = ConstantInt::get(I.getContext(),
2637218893Sdim                                    APInt::getLowBitsSet(AP.getBitWidth(),
2638218893Sdim                                                         AP.getBitWidth() -
2639218893Sdim                                                    AP.countTrailingZeros()));
2640218893Sdim            Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2641218893Sdim            Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2642218893Sdim            return new ICmpInst(I.getPredicate(), And1, And2);
2643202375Srdivacky          }
2644202375Srdivacky        }
2645218893Sdim        break;
2646221345Sdim      case Instruction::UDiv:
2647221345Sdim      case Instruction::LShr:
2648221345Sdim        if (I.isSigned())
2649221345Sdim          break;
2650221345Sdim        // fall-through
2651221345Sdim      case Instruction::SDiv:
2652221345Sdim      case Instruction::AShr:
2653223017Sdim        if (!BO0->isExact() || !BO1->isExact())
2654221345Sdim          break;
2655221345Sdim        return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2656221345Sdim                            BO1->getOperand(0));
2657221345Sdim      case Instruction::Shl: {
2658221345Sdim        bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2659221345Sdim        bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2660221345Sdim        if (!NUW && !NSW)
2661221345Sdim          break;
2662221345Sdim        if (!NSW && I.isSigned())
2663221345Sdim          break;
2664221345Sdim        return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2665221345Sdim                            BO1->getOperand(0));
2666202375Srdivacky      }
2667221345Sdim      }
2668202375Srdivacky    }
2669202375Srdivacky  }
2670226633Sdim
2671202375Srdivacky  { Value *A, *B;
2672251662Sdim    // Transform (A & ~B) == 0 --> (A & B) != 0
2673251662Sdim    // and       (A & ~B) != 0 --> (A & B) == 0
2674251662Sdim    // if A is a power of 2.
2675251662Sdim    if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2676251662Sdim        match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2677251662Sdim      return new ICmpInst(I.getInversePredicate(),
2678251662Sdim                          Builder->CreateAnd(A, B),
2679251662Sdim                          Op1);
2680251662Sdim
2681218893Sdim    // ~x < ~y --> y < x
2682218893Sdim    // ~x < cst --> ~cst < x
2683218893Sdim    if (match(Op0, m_Not(m_Value(A)))) {
2684218893Sdim      if (match(Op1, m_Not(m_Value(B))))
2685218893Sdim        return new ICmpInst(I.getPredicate(), B, A);
2686218893Sdim      if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2687218893Sdim        return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2688218893Sdim    }
2689218893Sdim
2690218893Sdim    // (a+b) <u a  --> llvm.uadd.with.overflow.
2691218893Sdim    // (a+b) <u b  --> llvm.uadd.with.overflow.
2692218893Sdim    if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2693226633Sdim        match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2694218893Sdim        (Op1 == A || Op1 == B))
2695218893Sdim      if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2696218893Sdim        return R;
2697226633Sdim
2698218893Sdim    // a >u (a+b)  --> llvm.uadd.with.overflow.
2699218893Sdim    // b >u (a+b)  --> llvm.uadd.with.overflow.
2700218893Sdim    if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2701218893Sdim        match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2702218893Sdim        (Op0 == A || Op0 == B))
2703218893Sdim      if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2704218893Sdim        return R;
2705202375Srdivacky  }
2706226633Sdim
2707202375Srdivacky  if (I.isEquality()) {
2708202375Srdivacky    Value *A, *B, *C, *D;
2709218893Sdim
2710202375Srdivacky    if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2711202375Srdivacky      if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2712202375Srdivacky        Value *OtherVal = A == Op1 ? B : A;
2713202375Srdivacky        return new ICmpInst(I.getPredicate(), OtherVal,
2714202375Srdivacky                            Constant::getNullValue(A->getType()));
2715202375Srdivacky      }
2716202375Srdivacky
2717202375Srdivacky      if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2718202375Srdivacky        // A^c1 == C^c2 --> A == C^(c1^c2)
2719202375Srdivacky        ConstantInt *C1, *C2;
2720202375Srdivacky        if (match(B, m_ConstantInt(C1)) &&
2721202375Srdivacky            match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2722202375Srdivacky          Constant *NC = ConstantInt::get(I.getContext(),
2723202375Srdivacky                                          C1->getValue() ^ C2->getValue());
2724226633Sdim          Value *Xor = Builder->CreateXor(C, NC);
2725202375Srdivacky          return new ICmpInst(I.getPredicate(), A, Xor);
2726202375Srdivacky        }
2727226633Sdim
2728202375Srdivacky        // A^B == A^D -> B == D
2729202375Srdivacky        if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2730202375Srdivacky        if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2731202375Srdivacky        if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2732202375Srdivacky        if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2733202375Srdivacky      }
2734202375Srdivacky    }
2735226633Sdim
2736202375Srdivacky    if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2737202375Srdivacky        (A == Op0 || B == Op0)) {
2738202375Srdivacky      // A == (A^B)  ->  B == 0
2739202375Srdivacky      Value *OtherVal = A == Op0 ? B : A;
2740202375Srdivacky      return new ICmpInst(I.getPredicate(), OtherVal,
2741202375Srdivacky                          Constant::getNullValue(A->getType()));
2742202375Srdivacky    }
2743202375Srdivacky
2744202375Srdivacky    // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2745226633Sdim    if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2746221345Sdim        match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2747202375Srdivacky      Value *X = 0, *Y = 0, *Z = 0;
2748226633Sdim
2749202375Srdivacky      if (A == C) {
2750202375Srdivacky        X = B; Y = D; Z = A;
2751202375Srdivacky      } else if (A == D) {
2752202375Srdivacky        X = B; Y = C; Z = A;
2753202375Srdivacky      } else if (B == C) {
2754202375Srdivacky        X = A; Y = D; Z = B;
2755202375Srdivacky      } else if (B == D) {
2756202375Srdivacky        X = A; Y = C; Z = B;
2757202375Srdivacky      }
2758226633Sdim
2759202375Srdivacky      if (X) {   // Build (X^Y) & Z
2760226633Sdim        Op1 = Builder->CreateXor(X, Y);
2761226633Sdim        Op1 = Builder->CreateAnd(Op1, Z);
2762202375Srdivacky        I.setOperand(0, Op1);
2763202375Srdivacky        I.setOperand(1, Constant::getNullValue(Op1->getType()));
2764202375Srdivacky        return &I;
2765202375Srdivacky      }
2766202375Srdivacky    }
2767226633Sdim
2768239462Sdim    // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
2769239462Sdim    // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
2770239462Sdim    ConstantInt *Cst1;
2771239462Sdim    if ((Op0->hasOneUse() &&
2772239462Sdim         match(Op0, m_ZExt(m_Value(A))) &&
2773239462Sdim         match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2774239462Sdim        (Op1->hasOneUse() &&
2775239462Sdim         match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2776239462Sdim         match(Op1, m_ZExt(m_Value(A))))) {
2777239462Sdim      APInt Pow2 = Cst1->getValue() + 1;
2778239462Sdim      if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2779239462Sdim          Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2780239462Sdim        return new ICmpInst(I.getPredicate(), A,
2781239462Sdim                            Builder->CreateTrunc(B, A->getType()));
2782239462Sdim    }
2783239462Sdim
2784221345Sdim    // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2785221345Sdim    // "icmp (and X, mask), cst"
2786221345Sdim    uint64_t ShAmt = 0;
2787221345Sdim    if (Op0->hasOneUse() &&
2788221345Sdim        match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2789221345Sdim                                           m_ConstantInt(ShAmt))))) &&
2790221345Sdim        match(Op1, m_ConstantInt(Cst1)) &&
2791221345Sdim        // Only do this when A has multiple uses.  This is most important to do
2792221345Sdim        // when it exposes other optimizations.
2793221345Sdim        !A->hasOneUse()) {
2794221345Sdim      unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2795226633Sdim
2796221345Sdim      if (ShAmt < ASize) {
2797221345Sdim        APInt MaskV =
2798221345Sdim          APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2799221345Sdim        MaskV <<= ShAmt;
2800226633Sdim
2801221345Sdim        APInt CmpV = Cst1->getValue().zext(ASize);
2802221345Sdim        CmpV <<= ShAmt;
2803226633Sdim
2804221345Sdim        Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2805221345Sdim        return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2806221345Sdim      }
2807221345Sdim    }
2808202375Srdivacky  }
2809226633Sdim
2810202375Srdivacky  {
2811202375Srdivacky    Value *X; ConstantInt *Cst;
2812202375Srdivacky    // icmp X+Cst, X
2813202375Srdivacky    if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2814202375Srdivacky      return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2815202375Srdivacky
2816202375Srdivacky    // icmp X, X+Cst
2817202375Srdivacky    if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2818202375Srdivacky      return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2819202375Srdivacky  }
2820202375Srdivacky  return Changed ? &I : 0;
2821202375Srdivacky}
2822202375Srdivacky
2823202375Srdivacky
2824202375Srdivacky
2825202375Srdivacky
2826202375Srdivacky
2827202375Srdivacky
2828202375Srdivacky/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2829202375Srdivacky///
2830202375SrdivackyInstruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2831202375Srdivacky                                                Instruction *LHSI,
2832202375Srdivacky                                                Constant *RHSC) {
2833202375Srdivacky  if (!isa<ConstantFP>(RHSC)) return 0;
2834202375Srdivacky  const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2835226633Sdim
2836202375Srdivacky  // Get the width of the mantissa.  We don't want to hack on conversions that
2837202375Srdivacky  // might lose information from the integer, e.g. "i64 -> float"
2838202375Srdivacky  int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2839202375Srdivacky  if (MantissaWidth == -1) return 0;  // Unknown.
2840226633Sdim
2841202375Srdivacky  // Check to see that the input is converted from an integer type that is small
2842202375Srdivacky  // enough that preserves all bits.  TODO: check here for "known" sign bits.
2843202375Srdivacky  // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2844202375Srdivacky  unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2845226633Sdim
2846202375Srdivacky  // If this is a uitofp instruction, we need an extra bit to hold the sign.
2847202375Srdivacky  bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2848202375Srdivacky  if (LHSUnsigned)
2849202375Srdivacky    ++InputSize;
2850226633Sdim
2851202375Srdivacky  // If the conversion would lose info, don't hack on this.
2852202375Srdivacky  if ((int)InputSize > MantissaWidth)
2853202375Srdivacky    return 0;
2854226633Sdim
2855202375Srdivacky  // Otherwise, we can potentially simplify the comparison.  We know that it
2856202375Srdivacky  // will always come through as an integer value and we know the constant is
2857202375Srdivacky  // not a NAN (it would have been previously simplified).
2858202375Srdivacky  assert(!RHS.isNaN() && "NaN comparison not already folded!");
2859226633Sdim
2860202375Srdivacky  ICmpInst::Predicate Pred;
2861202375Srdivacky  switch (I.getPredicate()) {
2862202375Srdivacky  default: llvm_unreachable("Unexpected predicate!");
2863202375Srdivacky  case FCmpInst::FCMP_UEQ:
2864202375Srdivacky  case FCmpInst::FCMP_OEQ:
2865202375Srdivacky    Pred = ICmpInst::ICMP_EQ;
2866202375Srdivacky    break;
2867202375Srdivacky  case FCmpInst::FCMP_UGT:
2868202375Srdivacky  case FCmpInst::FCMP_OGT:
2869202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2870202375Srdivacky    break;
2871202375Srdivacky  case FCmpInst::FCMP_UGE:
2872202375Srdivacky  case FCmpInst::FCMP_OGE:
2873202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2874202375Srdivacky    break;
2875202375Srdivacky  case FCmpInst::FCMP_ULT:
2876202375Srdivacky  case FCmpInst::FCMP_OLT:
2877202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2878202375Srdivacky    break;
2879202375Srdivacky  case FCmpInst::FCMP_ULE:
2880202375Srdivacky  case FCmpInst::FCMP_OLE:
2881202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2882202375Srdivacky    break;
2883202375Srdivacky  case FCmpInst::FCMP_UNE:
2884202375Srdivacky  case FCmpInst::FCMP_ONE:
2885202375Srdivacky    Pred = ICmpInst::ICMP_NE;
2886202375Srdivacky    break;
2887202375Srdivacky  case FCmpInst::FCMP_ORD:
2888202375Srdivacky    return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2889202375Srdivacky  case FCmpInst::FCMP_UNO:
2890202375Srdivacky    return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2891202375Srdivacky  }
2892226633Sdim
2893226633Sdim  IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2894226633Sdim
2895202375Srdivacky  // Now we know that the APFloat is a normal number, zero or inf.
2896226633Sdim
2897202375Srdivacky  // See if the FP constant is too large for the integer.  For example,
2898202375Srdivacky  // comparing an i8 to 300.0.
2899202375Srdivacky  unsigned IntWidth = IntTy->getScalarSizeInBits();
2900226633Sdim
2901202375Srdivacky  if (!LHSUnsigned) {
2902202375Srdivacky    // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
2903202375Srdivacky    // and large values.
2904202375Srdivacky    APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2905202375Srdivacky    SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2906202375Srdivacky                          APFloat::rmNearestTiesToEven);
2907202375Srdivacky    if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
2908202375Srdivacky      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
2909202375Srdivacky          Pred == ICmpInst::ICMP_SLE)
2910202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2911202375Srdivacky      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2912202375Srdivacky    }
2913202375Srdivacky  } else {
2914202375Srdivacky    // If the RHS value is > UnsignedMax, fold the comparison. This handles
2915202375Srdivacky    // +INF and large values.
2916202375Srdivacky    APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2917202375Srdivacky    UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2918202375Srdivacky                          APFloat::rmNearestTiesToEven);
2919202375Srdivacky    if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
2920202375Srdivacky      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
2921202375Srdivacky          Pred == ICmpInst::ICMP_ULE)
2922202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2923202375Srdivacky      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2924202375Srdivacky    }
2925202375Srdivacky  }
2926226633Sdim
2927202375Srdivacky  if (!LHSUnsigned) {
2928202375Srdivacky    // See if the RHS value is < SignedMin.
2929202375Srdivacky    APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2930202375Srdivacky    SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2931202375Srdivacky                          APFloat::rmNearestTiesToEven);
2932202375Srdivacky    if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2933202375Srdivacky      if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2934202375Srdivacky          Pred == ICmpInst::ICMP_SGE)
2935202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2936202375Srdivacky      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2937202375Srdivacky    }
2938234353Sdim  } else {
2939234353Sdim    // See if the RHS value is < UnsignedMin.
2940234353Sdim    APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2941234353Sdim    SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
2942234353Sdim                          APFloat::rmNearestTiesToEven);
2943234353Sdim    if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
2944234353Sdim      if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
2945234353Sdim          Pred == ICmpInst::ICMP_UGE)
2946234353Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2947234353Sdim      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2948234353Sdim    }
2949202375Srdivacky  }
2950202375Srdivacky
2951202375Srdivacky  // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2952202375Srdivacky  // [0, UMAX], but it may still be fractional.  See if it is fractional by
2953202375Srdivacky  // casting the FP value to the integer value and back, checking for equality.
2954202375Srdivacky  // Don't do this for zero, because -0.0 is not fractional.
2955202375Srdivacky  Constant *RHSInt = LHSUnsigned
2956202375Srdivacky    ? ConstantExpr::getFPToUI(RHSC, IntTy)
2957202375Srdivacky    : ConstantExpr::getFPToSI(RHSC, IntTy);
2958202375Srdivacky  if (!RHS.isZero()) {
2959202375Srdivacky    bool Equal = LHSUnsigned
2960202375Srdivacky      ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2961202375Srdivacky      : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2962202375Srdivacky    if (!Equal) {
2963202375Srdivacky      // If we had a comparison against a fractional value, we have to adjust
2964202375Srdivacky      // the compare predicate and sometimes the value.  RHSC is rounded towards
2965202375Srdivacky      // zero at this point.
2966202375Srdivacky      switch (Pred) {
2967202375Srdivacky      default: llvm_unreachable("Unexpected integer comparison!");
2968202375Srdivacky      case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
2969202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2970202375Srdivacky      case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
2971202375Srdivacky        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2972202375Srdivacky      case ICmpInst::ICMP_ULE:
2973202375Srdivacky        // (float)int <= 4.4   --> int <= 4
2974202375Srdivacky        // (float)int <= -4.4  --> false
2975202375Srdivacky        if (RHS.isNegative())
2976202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2977202375Srdivacky        break;
2978202375Srdivacky      case ICmpInst::ICMP_SLE:
2979202375Srdivacky        // (float)int <= 4.4   --> int <= 4
2980202375Srdivacky        // (float)int <= -4.4  --> int < -4
2981202375Srdivacky        if (RHS.isNegative())
2982202375Srdivacky          Pred = ICmpInst::ICMP_SLT;
2983202375Srdivacky        break;
2984202375Srdivacky      case ICmpInst::ICMP_ULT:
2985202375Srdivacky        // (float)int < -4.4   --> false
2986202375Srdivacky        // (float)int < 4.4    --> int <= 4
2987202375Srdivacky        if (RHS.isNegative())
2988202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2989202375Srdivacky        Pred = ICmpInst::ICMP_ULE;
2990202375Srdivacky        break;
2991202375Srdivacky      case ICmpInst::ICMP_SLT:
2992202375Srdivacky        // (float)int < -4.4   --> int < -4
2993202375Srdivacky        // (float)int < 4.4    --> int <= 4
2994202375Srdivacky        if (!RHS.isNegative())
2995202375Srdivacky          Pred = ICmpInst::ICMP_SLE;
2996202375Srdivacky        break;
2997202375Srdivacky      case ICmpInst::ICMP_UGT:
2998202375Srdivacky        // (float)int > 4.4    --> int > 4
2999202375Srdivacky        // (float)int > -4.4   --> true
3000202375Srdivacky        if (RHS.isNegative())
3001202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
3002202375Srdivacky        break;
3003202375Srdivacky      case ICmpInst::ICMP_SGT:
3004202375Srdivacky        // (float)int > 4.4    --> int > 4
3005202375Srdivacky        // (float)int > -4.4   --> int >= -4
3006202375Srdivacky        if (RHS.isNegative())
3007202375Srdivacky          Pred = ICmpInst::ICMP_SGE;
3008202375Srdivacky        break;
3009202375Srdivacky      case ICmpInst::ICMP_UGE:
3010202375Srdivacky        // (float)int >= -4.4   --> true
3011202375Srdivacky        // (float)int >= 4.4    --> int > 4
3012239462Sdim        if (RHS.isNegative())
3013202375Srdivacky          return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
3014202375Srdivacky        Pred = ICmpInst::ICMP_UGT;
3015202375Srdivacky        break;
3016202375Srdivacky      case ICmpInst::ICMP_SGE:
3017202375Srdivacky        // (float)int >= -4.4   --> int >= -4
3018202375Srdivacky        // (float)int >= 4.4    --> int > 4
3019202375Srdivacky        if (!RHS.isNegative())
3020202375Srdivacky          Pred = ICmpInst::ICMP_SGT;
3021202375Srdivacky        break;
3022202375Srdivacky      }
3023202375Srdivacky    }
3024202375Srdivacky  }
3025202375Srdivacky
3026202375Srdivacky  // Lower this FP comparison into an appropriate integer version of the
3027202375Srdivacky  // comparison.
3028202375Srdivacky  return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3029202375Srdivacky}
3030202375Srdivacky
3031202375SrdivackyInstruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3032202375Srdivacky  bool Changed = false;
3033226633Sdim
3034202375Srdivacky  /// Orders the operands of the compare so that they are listed from most
3035202375Srdivacky  /// complex to least complex.  This puts constants before unary operators,
3036202375Srdivacky  /// before binary operators.
3037202375Srdivacky  if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3038202375Srdivacky    I.swapOperands();
3039202375Srdivacky    Changed = true;
3040202375Srdivacky  }
3041202375Srdivacky
3042202375Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3043226633Sdim
3044202375Srdivacky  if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3045202375Srdivacky    return ReplaceInstUsesWith(I, V);
3046202375Srdivacky
3047202375Srdivacky  // Simplify 'fcmp pred X, X'
3048202375Srdivacky  if (Op0 == Op1) {
3049202375Srdivacky    switch (I.getPredicate()) {
3050202375Srdivacky    default: llvm_unreachable("Unknown predicate!");
3051202375Srdivacky    case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
3052202375Srdivacky    case FCmpInst::FCMP_ULT:    // True if unordered or less than
3053202375Srdivacky    case FCmpInst::FCMP_UGT:    // True if unordered or greater than
3054202375Srdivacky    case FCmpInst::FCMP_UNE:    // True if unordered or not equal
3055202375Srdivacky      // Canonicalize these to be 'fcmp uno %X, 0.0'.
3056202375Srdivacky      I.setPredicate(FCmpInst::FCMP_UNO);
3057202375Srdivacky      I.setOperand(1, Constant::getNullValue(Op0->getType()));
3058202375Srdivacky      return &I;
3059226633Sdim
3060202375Srdivacky    case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
3061202375Srdivacky    case FCmpInst::FCMP_OEQ:    // True if ordered and equal
3062202375Srdivacky    case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
3063202375Srdivacky    case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
3064202375Srdivacky      // Canonicalize these to be 'fcmp ord %X, 0.0'.
3065202375Srdivacky      I.setPredicate(FCmpInst::FCMP_ORD);
3066202375Srdivacky      I.setOperand(1, Constant::getNullValue(Op0->getType()));
3067202375Srdivacky      return &I;
3068202375Srdivacky    }
3069202375Srdivacky  }
3070226633Sdim
3071202375Srdivacky  // Handle fcmp with constant RHS
3072202375Srdivacky  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3073202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3074202375Srdivacky      switch (LHSI->getOpcode()) {
3075221345Sdim      case Instruction::FPExt: {
3076221345Sdim        // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3077221345Sdim        FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3078221345Sdim        ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3079221345Sdim        if (!RHSF)
3080221345Sdim          break;
3081221345Sdim
3082221345Sdim        const fltSemantics *Sem;
3083221345Sdim        // FIXME: This shouldn't be here.
3084234353Sdim        if (LHSExt->getSrcTy()->isHalfTy())
3085234353Sdim          Sem = &APFloat::IEEEhalf;
3086234353Sdim        else if (LHSExt->getSrcTy()->isFloatTy())
3087221345Sdim          Sem = &APFloat::IEEEsingle;
3088221345Sdim        else if (LHSExt->getSrcTy()->isDoubleTy())
3089221345Sdim          Sem = &APFloat::IEEEdouble;
3090221345Sdim        else if (LHSExt->getSrcTy()->isFP128Ty())
3091221345Sdim          Sem = &APFloat::IEEEquad;
3092221345Sdim        else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3093221345Sdim          Sem = &APFloat::x87DoubleExtended;
3094243830Sdim        else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3095243830Sdim          Sem = &APFloat::PPCDoubleDouble;
3096221345Sdim        else
3097221345Sdim          break;
3098221345Sdim
3099221345Sdim        bool Lossy;
3100221345Sdim        APFloat F = RHSF->getValueAPF();
3101221345Sdim        F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3102221345Sdim
3103226633Sdim        // Avoid lossy conversions and denormals. Zero is a special case
3104226633Sdim        // that's OK to convert.
3105226633Sdim        APFloat Fabs = F;
3106226633Sdim        Fabs.clearSign();
3107221345Sdim        if (!Lossy &&
3108226633Sdim            ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3109226633Sdim                 APFloat::cmpLessThan) || Fabs.isZero()))
3110226633Sdim
3111221345Sdim          return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3112221345Sdim                              ConstantFP::get(RHSC->getContext(), F));
3113221345Sdim        break;
3114221345Sdim      }
3115202375Srdivacky      case Instruction::PHI:
3116202375Srdivacky        // Only fold fcmp into the PHI if the phi and fcmp are in the same
3117202375Srdivacky        // block.  If in the same block, we're encouraging jump threading.  If
3118202375Srdivacky        // not, we are just pessimizing the code by making an i1 phi.
3119202375Srdivacky        if (LHSI->getParent() == I.getParent())
3120218893Sdim          if (Instruction *NV = FoldOpIntoPhi(I))
3121202375Srdivacky            return NV;
3122202375Srdivacky        break;
3123202375Srdivacky      case Instruction::SIToFP:
3124202375Srdivacky      case Instruction::UIToFP:
3125202375Srdivacky        if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3126202375Srdivacky          return NV;
3127202375Srdivacky        break;
3128202375Srdivacky      case Instruction::Select: {
3129202375Srdivacky        // If either operand of the select is a constant, we can fold the
3130202375Srdivacky        // comparison into the select arms, which will cause one to be
3131202375Srdivacky        // constant folded and the select turned into a bitwise or.
3132202375Srdivacky        Value *Op1 = 0, *Op2 = 0;
3133202375Srdivacky        if (LHSI->hasOneUse()) {
3134202375Srdivacky          if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3135202375Srdivacky            // Fold the known value into the constant operand.
3136202375Srdivacky            Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3137202375Srdivacky            // Insert a new FCmp of the other select operand.
3138202375Srdivacky            Op2 = Builder->CreateFCmp(I.getPredicate(),
3139202375Srdivacky                                      LHSI->getOperand(2), RHSC, I.getName());
3140202375Srdivacky          } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3141202375Srdivacky            // Fold the known value into the constant operand.
3142202375Srdivacky            Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3143202375Srdivacky            // Insert a new FCmp of the other select operand.
3144202375Srdivacky            Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3145202375Srdivacky                                      RHSC, I.getName());
3146202375Srdivacky          }
3147202375Srdivacky        }
3148202375Srdivacky
3149202375Srdivacky        if (Op1)
3150202375Srdivacky          return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3151202375Srdivacky        break;
3152202375Srdivacky      }
3153221345Sdim      case Instruction::FSub: {
3154221345Sdim        // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3155221345Sdim        Value *Op;
3156221345Sdim        if (match(LHSI, m_FNeg(m_Value(Op))))
3157221345Sdim          return new FCmpInst(I.getSwappedPredicate(), Op,
3158221345Sdim                              ConstantExpr::getFNeg(RHSC));
3159221345Sdim        break;
3160221345Sdim      }
3161204642Srdivacky      case Instruction::Load:
3162204642Srdivacky        if (GetElementPtrInst *GEP =
3163204642Srdivacky            dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3164204642Srdivacky          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3165204642Srdivacky            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3166204642Srdivacky                !cast<LoadInst>(LHSI)->isVolatile())
3167204642Srdivacky              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3168204642Srdivacky                return Res;
3169204642Srdivacky        }
3170204642Srdivacky        break;
3171243830Sdim      case Instruction::Call: {
3172243830Sdim        CallInst *CI = cast<CallInst>(LHSI);
3173243830Sdim        LibFunc::Func Func;
3174243830Sdim        // Various optimization for fabs compared with zero.
3175243830Sdim        if (RHSC->isNullValue() && CI->getCalledFunction() &&
3176243830Sdim            TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3177243830Sdim            TLI->has(Func)) {
3178243830Sdim          if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3179243830Sdim              Func == LibFunc::fabsl) {
3180243830Sdim            switch (I.getPredicate()) {
3181243830Sdim            default: break;
3182243830Sdim            // fabs(x) < 0 --> false
3183243830Sdim            case FCmpInst::FCMP_OLT:
3184243830Sdim              return ReplaceInstUsesWith(I, Builder->getFalse());
3185243830Sdim            // fabs(x) > 0 --> x != 0
3186243830Sdim            case FCmpInst::FCMP_OGT:
3187243830Sdim              return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3188243830Sdim                                  RHSC);
3189243830Sdim            // fabs(x) <= 0 --> x == 0
3190243830Sdim            case FCmpInst::FCMP_OLE:
3191243830Sdim              return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3192243830Sdim                                  RHSC);
3193243830Sdim            // fabs(x) >= 0 --> !isnan(x)
3194243830Sdim            case FCmpInst::FCMP_OGE:
3195243830Sdim              return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3196243830Sdim                                  RHSC);
3197243830Sdim            // fabs(x) == 0 --> x == 0
3198243830Sdim            // fabs(x) != 0 --> x != 0
3199243830Sdim            case FCmpInst::FCMP_OEQ:
3200243830Sdim            case FCmpInst::FCMP_UEQ:
3201243830Sdim            case FCmpInst::FCMP_ONE:
3202243830Sdim            case FCmpInst::FCMP_UNE:
3203243830Sdim              return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3204243830Sdim                                  RHSC);
3205243830Sdim            }
3206243830Sdim          }
3207243830Sdim        }
3208202375Srdivacky      }
3209243830Sdim      }
3210202375Srdivacky  }
3211202375Srdivacky
3212221345Sdim  // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
3213221345Sdim  Value *X, *Y;
3214221345Sdim  if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
3215221345Sdim    return new FCmpInst(I.getSwappedPredicate(), X, Y);
3216221345Sdim
3217221345Sdim  // fcmp (fpext x), (fpext y) -> fcmp x, y
3218221345Sdim  if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3219221345Sdim    if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3220221345Sdim      if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3221221345Sdim        return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3222221345Sdim                            RHSExt->getOperand(0));
3223221345Sdim
3224202375Srdivacky  return Changed ? &I : 0;
3225202375Srdivacky}
3226