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