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