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