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