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