LLVM API Documentation

InstCombineCompares.cpp
Go to the documentation of this file.
00001 //===- InstCombineCompares.cpp --------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitICmp and visitFCmp functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombineInternal.h"
00015 #include "llvm/ADT/APSInt.h"
00016 #include "llvm/ADT/Statistic.h"
00017 #include "llvm/Analysis/ConstantFolding.h"
00018 #include "llvm/Analysis/InstructionSimplify.h"
00019 #include "llvm/Analysis/MemoryBuiltins.h"
00020 #include "llvm/IR/ConstantRange.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/GetElementPtrTypeIterator.h"
00023 #include "llvm/IR/IntrinsicInst.h"
00024 #include "llvm/IR/PatternMatch.h"
00025 #include "llvm/Support/CommandLine.h"
00026 #include "llvm/Support/Debug.h"
00027 #include "llvm/Analysis/TargetLibraryInfo.h"
00028 
00029 using namespace llvm;
00030 using namespace PatternMatch;
00031 
00032 #define DEBUG_TYPE "instcombine"
00033 
00034 // How many times is a select replaced by one of its operands?
00035 STATISTIC(NumSel, "Number of select opts");
00036 
00037 // Initialization Routines
00038 
00039 static ConstantInt *getOne(Constant *C) {
00040   return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
00041 }
00042 
00043 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
00044   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
00045 }
00046 
00047 static bool HasAddOverflow(ConstantInt *Result,
00048                            ConstantInt *In1, ConstantInt *In2,
00049                            bool IsSigned) {
00050   if (!IsSigned)
00051     return Result->getValue().ult(In1->getValue());
00052 
00053   if (In2->isNegative())
00054     return Result->getValue().sgt(In1->getValue());
00055   return Result->getValue().slt(In1->getValue());
00056 }
00057 
00058 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
00059 /// overflowed for this type.
00060 static bool AddWithOverflow(Constant *&Result, Constant *In1,
00061                             Constant *In2, bool IsSigned = false) {
00062   Result = ConstantExpr::getAdd(In1, In2);
00063 
00064   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
00065     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
00066       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
00067       if (HasAddOverflow(ExtractElement(Result, Idx),
00068                          ExtractElement(In1, Idx),
00069                          ExtractElement(In2, Idx),
00070                          IsSigned))
00071         return true;
00072     }
00073     return false;
00074   }
00075 
00076   return HasAddOverflow(cast<ConstantInt>(Result),
00077                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
00078                         IsSigned);
00079 }
00080 
00081 static bool HasSubOverflow(ConstantInt *Result,
00082                            ConstantInt *In1, ConstantInt *In2,
00083                            bool IsSigned) {
00084   if (!IsSigned)
00085     return Result->getValue().ugt(In1->getValue());
00086 
00087   if (In2->isNegative())
00088     return Result->getValue().slt(In1->getValue());
00089 
00090   return Result->getValue().sgt(In1->getValue());
00091 }
00092 
00093 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
00094 /// overflowed for this type.
00095 static bool SubWithOverflow(Constant *&Result, Constant *In1,
00096                             Constant *In2, bool IsSigned = false) {
00097   Result = ConstantExpr::getSub(In1, In2);
00098 
00099   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
00100     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
00101       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
00102       if (HasSubOverflow(ExtractElement(Result, Idx),
00103                          ExtractElement(In1, Idx),
00104                          ExtractElement(In2, Idx),
00105                          IsSigned))
00106         return true;
00107     }
00108     return false;
00109   }
00110 
00111   return HasSubOverflow(cast<ConstantInt>(Result),
00112                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
00113                         IsSigned);
00114 }
00115 
00116 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
00117 /// comparison only checks the sign bit.  If it only checks the sign bit, set
00118 /// TrueIfSigned if the result of the comparison is true when the input value is
00119 /// signed.
00120 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
00121                            bool &TrueIfSigned) {
00122   switch (pred) {
00123   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
00124     TrueIfSigned = true;
00125     return RHS->isZero();
00126   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
00127     TrueIfSigned = true;
00128     return RHS->isAllOnesValue();
00129   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
00130     TrueIfSigned = false;
00131     return RHS->isAllOnesValue();
00132   case ICmpInst::ICMP_UGT:
00133     // True if LHS u> RHS and RHS == high-bit-mask - 1
00134     TrueIfSigned = true;
00135     return RHS->isMaxValue(true);
00136   case ICmpInst::ICMP_UGE:
00137     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
00138     TrueIfSigned = true;
00139     return RHS->getValue().isSignBit();
00140   default:
00141     return false;
00142   }
00143 }
00144 
00145 /// Returns true if the exploded icmp can be expressed as a signed comparison
00146 /// to zero and updates the predicate accordingly.
00147 /// The signedness of the comparison is preserved.
00148 static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
00149   if (!ICmpInst::isSigned(pred))
00150     return false;
00151 
00152   if (RHS->isZero())
00153     return ICmpInst::isRelational(pred);
00154 
00155   if (RHS->isOne()) {
00156     if (pred == ICmpInst::ICMP_SLT) {
00157       pred = ICmpInst::ICMP_SLE;
00158       return true;
00159     }
00160   } else if (RHS->isAllOnesValue()) {
00161     if (pred == ICmpInst::ICMP_SGT) {
00162       pred = ICmpInst::ICMP_SGE;
00163       return true;
00164     }
00165   }
00166 
00167   return false;
00168 }
00169 
00170 // isHighOnes - Return true if the constant is of the form 1+0+.
00171 // This is the same as lowones(~X).
00172 static bool isHighOnes(const ConstantInt *CI) {
00173   return (~CI->getValue() + 1).isPowerOf2();
00174 }
00175 
00176 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
00177 /// set of known zero and one bits, compute the maximum and minimum values that
00178 /// could have the specified known zero and known one bits, returning them in
00179 /// min/max.
00180 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
00181                                                    const APInt& KnownOne,
00182                                                    APInt& Min, APInt& Max) {
00183   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
00184          KnownZero.getBitWidth() == Min.getBitWidth() &&
00185          KnownZero.getBitWidth() == Max.getBitWidth() &&
00186          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
00187   APInt UnknownBits = ~(KnownZero|KnownOne);
00188 
00189   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
00190   // bit if it is unknown.
00191   Min = KnownOne;
00192   Max = KnownOne|UnknownBits;
00193 
00194   if (UnknownBits.isNegative()) { // Sign bit is unknown
00195     Min.setBit(Min.getBitWidth()-1);
00196     Max.clearBit(Max.getBitWidth()-1);
00197   }
00198 }
00199 
00200 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
00201 // a set of known zero and one bits, compute the maximum and minimum values that
00202 // could have the specified known zero and known one bits, returning them in
00203 // min/max.
00204 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
00205                                                      const APInt &KnownOne,
00206                                                      APInt &Min, APInt &Max) {
00207   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
00208          KnownZero.getBitWidth() == Min.getBitWidth() &&
00209          KnownZero.getBitWidth() == Max.getBitWidth() &&
00210          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
00211   APInt UnknownBits = ~(KnownZero|KnownOne);
00212 
00213   // The minimum value is when the unknown bits are all zeros.
00214   Min = KnownOne;
00215   // The maximum value is when the unknown bits are all ones.
00216   Max = KnownOne|UnknownBits;
00217 }
00218 
00219 
00220 
00221 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
00222 ///   cmp pred (load (gep GV, ...)), cmpcst
00223 /// where GV is a global variable with a constant initializer.  Try to simplify
00224 /// this into some simple computation that does not need the load.  For example
00225 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
00226 ///
00227 /// If AndCst is non-null, then the loaded value is masked with that constant
00228 /// before doing the comparison.  This handles cases like "A[i]&4 == 0".
00229 Instruction *InstCombiner::
00230 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
00231                              CmpInst &ICI, ConstantInt *AndCst) {
00232   // We need TD information to know the pointer size unless this is inbounds.
00233   if (!GEP->isInBounds() && !DL)
00234     return nullptr;
00235 
00236   Constant *Init = GV->getInitializer();
00237   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
00238     return nullptr;
00239 
00240   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
00241   if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
00242 
00243   // There are many forms of this optimization we can handle, for now, just do
00244   // the simple index into a single-dimensional array.
00245   //
00246   // Require: GEP GV, 0, i {{, constant indices}}
00247   if (GEP->getNumOperands() < 3 ||
00248       !isa<ConstantInt>(GEP->getOperand(1)) ||
00249       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
00250       isa<Constant>(GEP->getOperand(2)))
00251     return nullptr;
00252 
00253   // Check that indices after the variable are constants and in-range for the
00254   // type they index.  Collect the indices.  This is typically for arrays of
00255   // structs.
00256   SmallVector<unsigned, 4> LaterIndices;
00257 
00258   Type *EltTy = Init->getType()->getArrayElementType();
00259   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
00260     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
00261     if (!Idx) return nullptr;  // Variable index.
00262 
00263     uint64_t IdxVal = Idx->getZExtValue();
00264     if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
00265 
00266     if (StructType *STy = dyn_cast<StructType>(EltTy))
00267       EltTy = STy->getElementType(IdxVal);
00268     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
00269       if (IdxVal >= ATy->getNumElements()) return nullptr;
00270       EltTy = ATy->getElementType();
00271     } else {
00272       return nullptr; // Unknown type.
00273     }
00274 
00275     LaterIndices.push_back(IdxVal);
00276   }
00277 
00278   enum { Overdefined = -3, Undefined = -2 };
00279 
00280   // Variables for our state machines.
00281 
00282   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
00283   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
00284   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
00285   // undefined, otherwise set to the first true element.  SecondTrueElement is
00286   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
00287   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
00288 
00289   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
00290   // form "i != 47 & i != 87".  Same state transitions as for true elements.
00291   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
00292 
00293   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
00294   /// define a state machine that triggers for ranges of values that the index
00295   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
00296   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
00297   /// index in the range (inclusive).  We use -2 for undefined here because we
00298   /// use relative comparisons and don't want 0-1 to match -1.
00299   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
00300 
00301   // MagicBitvector - This is a magic bitvector where we set a bit if the
00302   // comparison is true for element 'i'.  If there are 64 elements or less in
00303   // the array, this will fully represent all the comparison results.
00304   uint64_t MagicBitvector = 0;
00305 
00306 
00307   // Scan the array and see if one of our patterns matches.
00308   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
00309   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
00310     Constant *Elt = Init->getAggregateElement(i);
00311     if (!Elt) return nullptr;
00312 
00313     // If this is indexing an array of structures, get the structure element.
00314     if (!LaterIndices.empty())
00315       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
00316 
00317     // If the element is masked, handle it.
00318     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
00319 
00320     // Find out if the comparison would be true or false for the i'th element.
00321     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
00322                                                   CompareRHS, DL, TLI);
00323     // If the result is undef for this element, ignore it.
00324     if (isa<UndefValue>(C)) {
00325       // Extend range state machines to cover this element in case there is an
00326       // undef in the middle of the range.
00327       if (TrueRangeEnd == (int)i-1)
00328         TrueRangeEnd = i;
00329       if (FalseRangeEnd == (int)i-1)
00330         FalseRangeEnd = i;
00331       continue;
00332     }
00333 
00334     // If we can't compute the result for any of the elements, we have to give
00335     // up evaluating the entire conditional.
00336     if (!isa<ConstantInt>(C)) return nullptr;
00337 
00338     // Otherwise, we know if the comparison is true or false for this element,
00339     // update our state machines.
00340     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
00341 
00342     // State machine for single/double/range index comparison.
00343     if (IsTrueForElt) {
00344       // Update the TrueElement state machine.
00345       if (FirstTrueElement == Undefined)
00346         FirstTrueElement = TrueRangeEnd = i;  // First true element.
00347       else {
00348         // Update double-compare state machine.
00349         if (SecondTrueElement == Undefined)
00350           SecondTrueElement = i;
00351         else
00352           SecondTrueElement = Overdefined;
00353 
00354         // Update range state machine.
00355         if (TrueRangeEnd == (int)i-1)
00356           TrueRangeEnd = i;
00357         else
00358           TrueRangeEnd = Overdefined;
00359       }
00360     } else {
00361       // Update the FalseElement state machine.
00362       if (FirstFalseElement == Undefined)
00363         FirstFalseElement = FalseRangeEnd = i; // First false element.
00364       else {
00365         // Update double-compare state machine.
00366         if (SecondFalseElement == Undefined)
00367           SecondFalseElement = i;
00368         else
00369           SecondFalseElement = Overdefined;
00370 
00371         // Update range state machine.
00372         if (FalseRangeEnd == (int)i-1)
00373           FalseRangeEnd = i;
00374         else
00375           FalseRangeEnd = Overdefined;
00376       }
00377     }
00378 
00379 
00380     // If this element is in range, update our magic bitvector.
00381     if (i < 64 && IsTrueForElt)
00382       MagicBitvector |= 1ULL << i;
00383 
00384     // If all of our states become overdefined, bail out early.  Since the
00385     // predicate is expensive, only check it every 8 elements.  This is only
00386     // really useful for really huge arrays.
00387     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
00388         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
00389         FalseRangeEnd == Overdefined)
00390       return nullptr;
00391   }
00392 
00393   // Now that we've scanned the entire array, emit our new comparison(s).  We
00394   // order the state machines in complexity of the generated code.
00395   Value *Idx = GEP->getOperand(2);
00396 
00397   // If the index is larger than the pointer size of the target, truncate the
00398   // index down like the GEP would do implicitly.  We don't have to do this for
00399   // an inbounds GEP because the index can't be out of range.
00400   if (!GEP->isInBounds()) {
00401     Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
00402     unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
00403     if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
00404       Idx = Builder->CreateTrunc(Idx, IntPtrTy);
00405   }
00406 
00407   // If the comparison is only true for one or two elements, emit direct
00408   // comparisons.
00409   if (SecondTrueElement != Overdefined) {
00410     // None true -> false.
00411     if (FirstTrueElement == Undefined)
00412       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00413 
00414     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
00415 
00416     // True for one element -> 'i == 47'.
00417     if (SecondTrueElement == Undefined)
00418       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
00419 
00420     // True for two elements -> 'i == 47 | i == 72'.
00421     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
00422     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
00423     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
00424     return BinaryOperator::CreateOr(C1, C2);
00425   }
00426 
00427   // If the comparison is only false for one or two elements, emit direct
00428   // comparisons.
00429   if (SecondFalseElement != Overdefined) {
00430     // None false -> true.
00431     if (FirstFalseElement == Undefined)
00432       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00433 
00434     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
00435 
00436     // False for one element -> 'i != 47'.
00437     if (SecondFalseElement == Undefined)
00438       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
00439 
00440     // False for two elements -> 'i != 47 & i != 72'.
00441     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
00442     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
00443     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
00444     return BinaryOperator::CreateAnd(C1, C2);
00445   }
00446 
00447   // If the comparison can be replaced with a range comparison for the elements
00448   // where it is true, emit the range check.
00449   if (TrueRangeEnd != Overdefined) {
00450     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
00451 
00452     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
00453     if (FirstTrueElement) {
00454       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
00455       Idx = Builder->CreateAdd(Idx, Offs);
00456     }
00457 
00458     Value *End = ConstantInt::get(Idx->getType(),
00459                                   TrueRangeEnd-FirstTrueElement+1);
00460     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
00461   }
00462 
00463   // False range check.
00464   if (FalseRangeEnd != Overdefined) {
00465     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
00466     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
00467     if (FirstFalseElement) {
00468       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
00469       Idx = Builder->CreateAdd(Idx, Offs);
00470     }
00471 
00472     Value *End = ConstantInt::get(Idx->getType(),
00473                                   FalseRangeEnd-FirstFalseElement);
00474     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
00475   }
00476 
00477 
00478   // If a magic bitvector captures the entire comparison state
00479   // of this load, replace it with computation that does:
00480   //   ((magic_cst >> i) & 1) != 0
00481   {
00482     Type *Ty = nullptr;
00483 
00484     // Look for an appropriate type:
00485     // - The type of Idx if the magic fits
00486     // - The smallest fitting legal type if we have a DataLayout
00487     // - Default to i32
00488     if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
00489       Ty = Idx->getType();
00490     else if (DL)
00491       Ty = DL->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
00492     else if (ArrayElementCount <= 32)
00493       Ty = Type::getInt32Ty(Init->getContext());
00494 
00495     if (Ty) {
00496       Value *V = Builder->CreateIntCast(Idx, Ty, false);
00497       V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
00498       V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
00499       return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
00500     }
00501   }
00502 
00503   return nullptr;
00504 }
00505 
00506 
00507 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
00508 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
00509 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
00510 /// be complex, and scales are involved.  The above expression would also be
00511 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
00512 /// This later form is less amenable to optimization though, and we are allowed
00513 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
00514 ///
00515 /// If we can't emit an optimized form for this expression, this returns null.
00516 ///
00517 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
00518   const DataLayout &DL = *IC.getDataLayout();
00519   gep_type_iterator GTI = gep_type_begin(GEP);
00520 
00521   // Check to see if this gep only has a single variable index.  If so, and if
00522   // any constant indices are a multiple of its scale, then we can compute this
00523   // in terms of the scale of the variable index.  For example, if the GEP
00524   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
00525   // because the expression will cross zero at the same point.
00526   unsigned i, e = GEP->getNumOperands();
00527   int64_t Offset = 0;
00528   for (i = 1; i != e; ++i, ++GTI) {
00529     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
00530       // Compute the aggregate offset of constant indices.
00531       if (CI->isZero()) continue;
00532 
00533       // Handle a struct index, which adds its field offset to the pointer.
00534       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00535         Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
00536       } else {
00537         uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
00538         Offset += Size*CI->getSExtValue();
00539       }
00540     } else {
00541       // Found our variable index.
00542       break;
00543     }
00544   }
00545 
00546   // If there are no variable indices, we must have a constant offset, just
00547   // evaluate it the general way.
00548   if (i == e) return nullptr;
00549 
00550   Value *VariableIdx = GEP->getOperand(i);
00551   // Determine the scale factor of the variable element.  For example, this is
00552   // 4 if the variable index is into an array of i32.
00553   uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
00554 
00555   // Verify that there are no other variable indices.  If so, emit the hard way.
00556   for (++i, ++GTI; i != e; ++i, ++GTI) {
00557     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
00558     if (!CI) return nullptr;
00559 
00560     // Compute the aggregate offset of constant indices.
00561     if (CI->isZero()) continue;
00562 
00563     // Handle a struct index, which adds its field offset to the pointer.
00564     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00565       Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
00566     } else {
00567       uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
00568       Offset += Size*CI->getSExtValue();
00569     }
00570   }
00571 
00572 
00573 
00574   // Okay, we know we have a single variable index, which must be a
00575   // pointer/array/vector index.  If there is no offset, life is simple, return
00576   // the index.
00577   Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
00578   unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
00579   if (Offset == 0) {
00580     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
00581     // we don't need to bother extending: the extension won't affect where the
00582     // computation crosses zero.
00583     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
00584       VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
00585     }
00586     return VariableIdx;
00587   }
00588 
00589   // Otherwise, there is an index.  The computation we will do will be modulo
00590   // the pointer size, so get it.
00591   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
00592 
00593   Offset &= PtrSizeMask;
00594   VariableScale &= PtrSizeMask;
00595 
00596   // To do this transformation, any constant index must be a multiple of the
00597   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
00598   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
00599   // multiple of the variable scale.
00600   int64_t NewOffs = Offset / (int64_t)VariableScale;
00601   if (Offset != NewOffs*(int64_t)VariableScale)
00602     return nullptr;
00603 
00604   // Okay, we can do this evaluation.  Start by converting the index to intptr.
00605   if (VariableIdx->getType() != IntPtrTy)
00606     VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
00607                                             true /*Signed*/);
00608   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
00609   return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
00610 }
00611 
00612 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
00613 /// else.  At this point we know that the GEP is on the LHS of the comparison.
00614 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
00615                                        ICmpInst::Predicate Cond,
00616                                        Instruction &I) {
00617   // Don't transform signed compares of GEPs into index compares. Even if the
00618   // GEP is inbounds, the final add of the base pointer can have signed overflow
00619   // and would change the result of the icmp.
00620   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
00621   // the maximum signed value for the pointer type.
00622   if (ICmpInst::isSigned(Cond))
00623     return nullptr;
00624 
00625   // Look through bitcasts and addrspacecasts. We do not however want to remove
00626   // 0 GEPs.
00627   if (!isa<GetElementPtrInst>(RHS))
00628     RHS = RHS->stripPointerCasts();
00629 
00630   Value *PtrBase = GEPLHS->getOperand(0);
00631   if (DL && PtrBase == RHS && GEPLHS->isInBounds()) {
00632     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
00633     // This transformation (ignoring the base and scales) is valid because we
00634     // know pointers can't overflow since the gep is inbounds.  See if we can
00635     // output an optimized form.
00636     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
00637 
00638     // If not, synthesize the offset the hard way.
00639     if (!Offset)
00640       Offset = EmitGEPOffset(GEPLHS);
00641     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
00642                         Constant::getNullValue(Offset->getType()));
00643   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
00644     // If the base pointers are different, but the indices are the same, just
00645     // compare the base pointer.
00646     if (PtrBase != GEPRHS->getOperand(0)) {
00647       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
00648       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
00649                         GEPRHS->getOperand(0)->getType();
00650       if (IndicesTheSame)
00651         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
00652           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
00653             IndicesTheSame = false;
00654             break;
00655           }
00656 
00657       // If all indices are the same, just compare the base pointers.
00658       if (IndicesTheSame)
00659         return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
00660 
00661       // If we're comparing GEPs with two base pointers that only differ in type
00662       // and both GEPs have only constant indices or just one use, then fold
00663       // the compare with the adjusted indices.
00664       if (DL && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
00665           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
00666           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
00667           PtrBase->stripPointerCasts() ==
00668             GEPRHS->getOperand(0)->stripPointerCasts()) {
00669         Value *LOffset = EmitGEPOffset(GEPLHS);
00670         Value *ROffset = EmitGEPOffset(GEPRHS);
00671 
00672         // If we looked through an addrspacecast between different sized address
00673         // spaces, the LHS and RHS pointers are different sized
00674         // integers. Truncate to the smaller one.
00675         Type *LHSIndexTy = LOffset->getType();
00676         Type *RHSIndexTy = ROffset->getType();
00677         if (LHSIndexTy != RHSIndexTy) {
00678           if (LHSIndexTy->getPrimitiveSizeInBits() <
00679               RHSIndexTy->getPrimitiveSizeInBits()) {
00680             ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
00681           } else
00682             LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
00683         }
00684 
00685         Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
00686                                          LOffset, ROffset);
00687         return ReplaceInstUsesWith(I, Cmp);
00688       }
00689 
00690       // Otherwise, the base pointers are different and the indices are
00691       // different, bail out.
00692       return nullptr;
00693     }
00694 
00695     // If one of the GEPs has all zero indices, recurse.
00696     if (GEPLHS->hasAllZeroIndices())
00697       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
00698                          ICmpInst::getSwappedPredicate(Cond), I);
00699 
00700     // If the other GEP has all zero indices, recurse.
00701     if (GEPRHS->hasAllZeroIndices())
00702       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
00703 
00704     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
00705     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
00706       // If the GEPs only differ by one index, compare it.
00707       unsigned NumDifferences = 0;  // Keep track of # differences.
00708       unsigned DiffOperand = 0;     // The operand that differs.
00709       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
00710         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
00711           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
00712                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
00713             // Irreconcilable differences.
00714             NumDifferences = 2;
00715             break;
00716           } else {
00717             if (NumDifferences++) break;
00718             DiffOperand = i;
00719           }
00720         }
00721 
00722       if (NumDifferences == 0)   // SAME GEP?
00723         return ReplaceInstUsesWith(I, // No comparison is needed here.
00724                              Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
00725 
00726       else if (NumDifferences == 1 && GEPsInBounds) {
00727         Value *LHSV = GEPLHS->getOperand(DiffOperand);
00728         Value *RHSV = GEPRHS->getOperand(DiffOperand);
00729         // Make sure we do a signed comparison here.
00730         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
00731       }
00732     }
00733 
00734     // Only lower this if the icmp is the only user of the GEP or if we expect
00735     // the result to fold to a constant!
00736     if (DL &&
00737         GEPsInBounds &&
00738         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
00739         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
00740       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
00741       Value *L = EmitGEPOffset(GEPLHS);
00742       Value *R = EmitGEPOffset(GEPRHS);
00743       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
00744     }
00745   }
00746   return nullptr;
00747 }
00748 
00749 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
00750 Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
00751                                             Value *X, ConstantInt *CI,
00752                                             ICmpInst::Predicate Pred) {
00753   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
00754   // so the values can never be equal.  Similarly for all other "or equals"
00755   // operators.
00756 
00757   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
00758   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
00759   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
00760   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
00761     Value *R =
00762       ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
00763     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
00764   }
00765 
00766   // (X+1) >u X        --> X <u (0-1)        --> X != 255
00767   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
00768   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
00769   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
00770     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
00771 
00772   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
00773   ConstantInt *SMax = ConstantInt::get(X->getContext(),
00774                                        APInt::getSignedMaxValue(BitWidth));
00775 
00776   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
00777   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
00778   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
00779   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
00780   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
00781   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
00782   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
00783     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
00784 
00785   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
00786   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
00787   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
00788   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
00789   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
00790   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
00791 
00792   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
00793   Constant *C = Builder->getInt(CI->getValue()-1);
00794   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
00795 }
00796 
00797 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
00798 /// and CmpRHS are both known to be integer constants.
00799 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
00800                                           ConstantInt *DivRHS) {
00801   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
00802   const APInt &CmpRHSV = CmpRHS->getValue();
00803 
00804   // FIXME: If the operand types don't match the type of the divide
00805   // then don't attempt this transform. The code below doesn't have the
00806   // logic to deal with a signed divide and an unsigned compare (and
00807   // vice versa). This is because (x /s C1) <s C2  produces different
00808   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
00809   // (x /u C1) <u C2.  Simply casting the operands and result won't
00810   // work. :(  The if statement below tests that condition and bails
00811   // if it finds it.
00812   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
00813   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
00814     return nullptr;
00815   if (DivRHS->isZero())
00816     return nullptr; // The ProdOV computation fails on divide by zero.
00817   if (DivIsSigned && DivRHS->isAllOnesValue())
00818     return nullptr; // The overflow computation also screws up here
00819   if (DivRHS->isOne()) {
00820     // This eliminates some funny cases with INT_MIN.
00821     ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
00822     return &ICI;
00823   }
00824 
00825   // Compute Prod = CI * DivRHS. We are essentially solving an equation
00826   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
00827   // C2 (CI). By solving for X we can turn this into a range check
00828   // instead of computing a divide.
00829   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
00830 
00831   // Determine if the product overflows by seeing if the product is
00832   // not equal to the divide. Make sure we do the same kind of divide
00833   // as in the LHS instruction that we're folding.
00834   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
00835                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
00836 
00837   // Get the ICmp opcode
00838   ICmpInst::Predicate Pred = ICI.getPredicate();
00839 
00840   /// If the division is known to be exact, then there is no remainder from the
00841   /// divide, so the covered range size is unit, otherwise it is the divisor.
00842   ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
00843 
00844   // Figure out the interval that is being checked.  For example, a comparison
00845   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
00846   // Compute this interval based on the constants involved and the signedness of
00847   // the compare/divide.  This computes a half-open interval, keeping track of
00848   // whether either value in the interval overflows.  After analysis each
00849   // overflow variable is set to 0 if it's corresponding bound variable is valid
00850   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
00851   int LoOverflow = 0, HiOverflow = 0;
00852   Constant *LoBound = nullptr, *HiBound = nullptr;
00853 
00854   if (!DivIsSigned) {  // udiv
00855     // e.g. X/5 op 3  --> [15, 20)
00856     LoBound = Prod;
00857     HiOverflow = LoOverflow = ProdOV;
00858     if (!HiOverflow) {
00859       // If this is not an exact divide, then many values in the range collapse
00860       // to the same result value.
00861       HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
00862     }
00863 
00864   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
00865     if (CmpRHSV == 0) {       // (X / pos) op 0
00866       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
00867       LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
00868       HiBound = RangeSize;
00869     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
00870       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
00871       HiOverflow = LoOverflow = ProdOV;
00872       if (!HiOverflow)
00873         HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
00874     } else {                       // (X / pos) op neg
00875       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
00876       HiBound = AddOne(Prod);
00877       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
00878       if (!LoOverflow) {
00879         ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
00880         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
00881       }
00882     }
00883   } else if (DivRHS->isNegative()) { // Divisor is < 0.
00884     if (DivI->isExact())
00885       RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
00886     if (CmpRHSV == 0) {       // (X / neg) op 0
00887       // e.g. X/-5 op 0  --> [-4, 5)
00888       LoBound = AddOne(RangeSize);
00889       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
00890       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
00891         HiOverflow = 1;            // [INTMIN+1, overflow)
00892         HiBound = nullptr;         // e.g. X/INTMIN = 0 --> X > INTMIN
00893       }
00894     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
00895       // e.g. X/-5 op 3  --> [-19, -14)
00896       HiBound = AddOne(Prod);
00897       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
00898       if (!LoOverflow)
00899         LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
00900     } else {                       // (X / neg) op neg
00901       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
00902       LoOverflow = HiOverflow = ProdOV;
00903       if (!HiOverflow)
00904         HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
00905     }
00906 
00907     // Dividing by a negative swaps the condition.  LT <-> GT
00908     Pred = ICmpInst::getSwappedPredicate(Pred);
00909   }
00910 
00911   Value *X = DivI->getOperand(0);
00912   switch (Pred) {
00913   default: llvm_unreachable("Unhandled icmp opcode!");
00914   case ICmpInst::ICMP_EQ:
00915     if (LoOverflow && HiOverflow)
00916       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00917     if (HiOverflow)
00918       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
00919                           ICmpInst::ICMP_UGE, X, LoBound);
00920     if (LoOverflow)
00921       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
00922                           ICmpInst::ICMP_ULT, X, HiBound);
00923     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
00924                                                     DivIsSigned, true));
00925   case ICmpInst::ICMP_NE:
00926     if (LoOverflow && HiOverflow)
00927       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00928     if (HiOverflow)
00929       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
00930                           ICmpInst::ICMP_ULT, X, LoBound);
00931     if (LoOverflow)
00932       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
00933                           ICmpInst::ICMP_UGE, X, HiBound);
00934     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
00935                                                     DivIsSigned, false));
00936   case ICmpInst::ICMP_ULT:
00937   case ICmpInst::ICMP_SLT:
00938     if (LoOverflow == +1)   // Low bound is greater than input range.
00939       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00940     if (LoOverflow == -1)   // Low bound is less than input range.
00941       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00942     return new ICmpInst(Pred, X, LoBound);
00943   case ICmpInst::ICMP_UGT:
00944   case ICmpInst::ICMP_SGT:
00945     if (HiOverflow == +1)       // High bound greater than input range.
00946       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00947     if (HiOverflow == -1)       // High bound less than input range.
00948       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00949     if (Pred == ICmpInst::ICMP_UGT)
00950       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
00951     return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
00952   }
00953 }
00954 
00955 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
00956 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
00957                                           ConstantInt *ShAmt) {
00958   const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
00959 
00960   // Check that the shift amount is in range.  If not, don't perform
00961   // undefined shifts.  When the shift is visited it will be
00962   // simplified.
00963   uint32_t TypeBits = CmpRHSV.getBitWidth();
00964   uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
00965   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
00966     return nullptr;
00967 
00968   if (!ICI.isEquality()) {
00969     // If we have an unsigned comparison and an ashr, we can't simplify this.
00970     // Similarly for signed comparisons with lshr.
00971     if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
00972       return nullptr;
00973 
00974     // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
00975     // by a power of 2.  Since we already have logic to simplify these,
00976     // transform to div and then simplify the resultant comparison.
00977     if (Shr->getOpcode() == Instruction::AShr &&
00978         (!Shr->isExact() || ShAmtVal == TypeBits - 1))
00979       return nullptr;
00980 
00981     // Revisit the shift (to delete it).
00982     Worklist.Add(Shr);
00983 
00984     Constant *DivCst =
00985       ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
00986 
00987     Value *Tmp =
00988       Shr->getOpcode() == Instruction::AShr ?
00989       Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
00990       Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
00991 
00992     ICI.setOperand(0, Tmp);
00993 
00994     // If the builder folded the binop, just return it.
00995     BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
00996     if (!TheDiv)
00997       return &ICI;
00998 
00999     // Otherwise, fold this div/compare.
01000     assert(TheDiv->getOpcode() == Instruction::SDiv ||
01001            TheDiv->getOpcode() == Instruction::UDiv);
01002 
01003     Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
01004     assert(Res && "This div/cst should have folded!");
01005     return Res;
01006   }
01007 
01008 
01009   // If we are comparing against bits always shifted out, the
01010   // comparison cannot succeed.
01011   APInt Comp = CmpRHSV << ShAmtVal;
01012   ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
01013   if (Shr->getOpcode() == Instruction::LShr)
01014     Comp = Comp.lshr(ShAmtVal);
01015   else
01016     Comp = Comp.ashr(ShAmtVal);
01017 
01018   if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
01019     bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
01020     Constant *Cst = Builder->getInt1(IsICMP_NE);
01021     return ReplaceInstUsesWith(ICI, Cst);
01022   }
01023 
01024   // Otherwise, check to see if the bits shifted out are known to be zero.
01025   // If so, we can compare against the unshifted value:
01026   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
01027   if (Shr->hasOneUse() && Shr->isExact())
01028     return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
01029 
01030   if (Shr->hasOneUse()) {
01031     // Otherwise strength reduce the shift into an and.
01032     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
01033     Constant *Mask = Builder->getInt(Val);
01034 
01035     Value *And = Builder->CreateAnd(Shr->getOperand(0),
01036                                     Mask, Shr->getName()+".mask");
01037     return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
01038   }
01039   return nullptr;
01040 }
01041 
01042 /// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
01043 /// (icmp eq/ne A, Log2(const2/const1)) ->
01044 /// (icmp eq/ne A, Log2(const2) - Log2(const1)).
01045 Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
01046                                              ConstantInt *CI1,
01047                                              ConstantInt *CI2) {
01048   assert(I.isEquality() && "Cannot fold icmp gt/lt");
01049 
01050   auto getConstant = [&I, this](bool IsTrue) {
01051     if (I.getPredicate() == I.ICMP_NE)
01052       IsTrue = !IsTrue;
01053     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
01054   };
01055 
01056   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
01057     if (I.getPredicate() == I.ICMP_NE)
01058       Pred = CmpInst::getInversePredicate(Pred);
01059     return new ICmpInst(Pred, LHS, RHS);
01060   };
01061 
01062   APInt AP1 = CI1->getValue();
01063   APInt AP2 = CI2->getValue();
01064 
01065   // Don't bother doing any work for cases which InstSimplify handles.
01066   if (AP2 == 0)
01067     return nullptr;
01068   bool IsAShr = isa<AShrOperator>(Op);
01069   if (IsAShr) {
01070     if (AP2.isAllOnesValue())
01071       return nullptr;
01072     if (AP2.isNegative() != AP1.isNegative())
01073       return nullptr;
01074     if (AP2.sgt(AP1))
01075       return nullptr;
01076   }
01077 
01078   if (!AP1)
01079     // 'A' must be large enough to shift out the highest set bit.
01080     return getICmp(I.ICMP_UGT, A,
01081                    ConstantInt::get(A->getType(), AP2.logBase2()));
01082 
01083   if (AP1 == AP2)
01084     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
01085 
01086   // Get the distance between the highest bit that's set.
01087   int Shift;
01088   // Both the constants are negative, take their positive to calculate log.
01089   if (IsAShr && AP1.isNegative())
01090     // Get the ones' complement of AP2 and AP1 when computing the distance.
01091     Shift = (~AP2).logBase2() - (~AP1).logBase2();
01092   else
01093     Shift = AP2.logBase2() - AP1.logBase2();
01094 
01095   if (Shift > 0) {
01096     if (IsAShr ? AP1 == AP2.ashr(Shift) : AP1 == AP2.lshr(Shift))
01097       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
01098   }
01099   // Shifting const2 will never be equal to const1.
01100   return getConstant(false);
01101 }
01102 
01103 /// FoldICmpCstShlCst - Handle "(icmp eq/ne (shl const2, A), const1)" ->
01104 /// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
01105 Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
01106                                              ConstantInt *CI1,
01107                                              ConstantInt *CI2) {
01108   assert(I.isEquality() && "Cannot fold icmp gt/lt");
01109 
01110   auto getConstant = [&I, this](bool IsTrue) {
01111     if (I.getPredicate() == I.ICMP_NE)
01112       IsTrue = !IsTrue;
01113     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
01114   };
01115 
01116   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
01117     if (I.getPredicate() == I.ICMP_NE)
01118       Pred = CmpInst::getInversePredicate(Pred);
01119     return new ICmpInst(Pred, LHS, RHS);
01120   };
01121 
01122   APInt AP1 = CI1->getValue();
01123   APInt AP2 = CI2->getValue();
01124 
01125   // Don't bother doing any work for cases which InstSimplify handles.
01126   if (AP2 == 0)
01127     return nullptr;
01128 
01129   unsigned AP2TrailingZeros = AP2.countTrailingZeros();
01130 
01131   if (!AP1 && AP2TrailingZeros != 0)
01132     return getICmp(I.ICMP_UGE, A,
01133                    ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
01134 
01135   if (AP1 == AP2)
01136     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
01137 
01138   // Get the distance between the lowest bits that are set.
01139   int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
01140 
01141   if (Shift > 0 && AP2.shl(Shift) == AP1)
01142     return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
01143 
01144   // Shifting const2 will never be equal to const1.
01145   return getConstant(false);
01146 }
01147 
01148 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
01149 ///
01150 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
01151                                                           Instruction *LHSI,
01152                                                           ConstantInt *RHS) {
01153   const APInt &RHSV = RHS->getValue();
01154 
01155   switch (LHSI->getOpcode()) {
01156   case Instruction::Trunc:
01157     if (ICI.isEquality() && LHSI->hasOneUse()) {
01158       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
01159       // of the high bits truncated out of x are known.
01160       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
01161              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
01162       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
01163       computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
01164 
01165       // If all the high bits are known, we can do this xform.
01166       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
01167         // Pull in the high bits from known-ones set.
01168         APInt NewRHS = RHS->getValue().zext(SrcBits);
01169         NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
01170         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
01171                             Builder->getInt(NewRHS));
01172       }
01173     }
01174     break;
01175 
01176   case Instruction::Xor:         // (icmp pred (xor X, XorCst), CI)
01177     if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
01178       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
01179       // fold the xor.
01180       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
01181           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
01182         Value *CompareVal = LHSI->getOperand(0);
01183 
01184         // If the sign bit of the XorCst is not set, there is no change to
01185         // the operation, just stop using the Xor.
01186         if (!XorCst->isNegative()) {
01187           ICI.setOperand(0, CompareVal);
01188           Worklist.Add(LHSI);
01189           return &ICI;
01190         }
01191 
01192         // Was the old condition true if the operand is positive?
01193         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
01194 
01195         // If so, the new one isn't.
01196         isTrueIfPositive ^= true;
01197 
01198         if (isTrueIfPositive)
01199           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
01200                               SubOne(RHS));
01201         else
01202           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
01203                               AddOne(RHS));
01204       }
01205 
01206       if (LHSI->hasOneUse()) {
01207         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
01208         if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
01209           const APInt &SignBit = XorCst->getValue();
01210           ICmpInst::Predicate Pred = ICI.isSigned()
01211                                          ? ICI.getUnsignedPredicate()
01212                                          : ICI.getSignedPredicate();
01213           return new ICmpInst(Pred, LHSI->getOperand(0),
01214                               Builder->getInt(RHSV ^ SignBit));
01215         }
01216 
01217         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
01218         if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
01219           const APInt &NotSignBit = XorCst->getValue();
01220           ICmpInst::Predicate Pred = ICI.isSigned()
01221                                          ? ICI.getUnsignedPredicate()
01222                                          : ICI.getSignedPredicate();
01223           Pred = ICI.getSwappedPredicate(Pred);
01224           return new ICmpInst(Pred, LHSI->getOperand(0),
01225                               Builder->getInt(RHSV ^ NotSignBit));
01226         }
01227       }
01228 
01229       // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
01230       //   iff -C is a power of 2
01231       if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
01232           XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
01233         return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
01234 
01235       // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
01236       //   iff -C is a power of 2
01237       if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
01238           XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
01239         return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
01240     }
01241     break;
01242   case Instruction::And:         // (icmp pred (and X, AndCst), RHS)
01243     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
01244         LHSI->getOperand(0)->hasOneUse()) {
01245       ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
01246 
01247       // If the LHS is an AND of a truncating cast, we can widen the
01248       // and/compare to be the input width without changing the value
01249       // produced, eliminating a cast.
01250       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
01251         // We can do this transformation if either the AND constant does not
01252         // have its sign bit set or if it is an equality comparison.
01253         // Extending a relational comparison when we're checking the sign
01254         // bit would not work.
01255         if (ICI.isEquality() ||
01256             (!AndCst->isNegative() && RHSV.isNonNegative())) {
01257           Value *NewAnd =
01258             Builder->CreateAnd(Cast->getOperand(0),
01259                                ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
01260           NewAnd->takeName(LHSI);
01261           return new ICmpInst(ICI.getPredicate(), NewAnd,
01262                               ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
01263         }
01264       }
01265 
01266       // If the LHS is an AND of a zext, and we have an equality compare, we can
01267       // shrink the and/compare to the smaller type, eliminating the cast.
01268       if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
01269         IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
01270         // Make sure we don't compare the upper bits, SimplifyDemandedBits
01271         // should fold the icmp to true/false in that case.
01272         if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
01273           Value *NewAnd =
01274             Builder->CreateAnd(Cast->getOperand(0),
01275                                ConstantExpr::getTrunc(AndCst, Ty));
01276           NewAnd->takeName(LHSI);
01277           return new ICmpInst(ICI.getPredicate(), NewAnd,
01278                               ConstantExpr::getTrunc(RHS, Ty));
01279         }
01280       }
01281 
01282       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
01283       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
01284       // happens a LOT in code produced by the C front-end, for bitfield
01285       // access.
01286       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
01287       if (Shift && !Shift->isShift())
01288         Shift = nullptr;
01289 
01290       ConstantInt *ShAmt;
01291       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
01292 
01293       // This seemingly simple opportunity to fold away a shift turns out to
01294       // be rather complicated. See PR17827
01295       // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
01296       if (ShAmt) {
01297         bool CanFold = false;
01298         unsigned ShiftOpcode = Shift->getOpcode();
01299         if (ShiftOpcode == Instruction::AShr) {
01300           // There may be some constraints that make this possible,
01301           // but nothing simple has been discovered yet.
01302           CanFold = false;
01303         } else if (ShiftOpcode == Instruction::Shl) {
01304           // For a left shift, we can fold if the comparison is not signed.
01305           // We can also fold a signed comparison if the mask value and
01306           // comparison value are not negative. These constraints may not be
01307           // obvious, but we can prove that they are correct using an SMT
01308           // solver.
01309           if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
01310             CanFold = true;
01311         } else if (ShiftOpcode == Instruction::LShr) {
01312           // For a logical right shift, we can fold if the comparison is not
01313           // signed. We can also fold a signed comparison if the shifted mask
01314           // value and the shifted comparison value are not negative.
01315           // These constraints may not be obvious, but we can prove that they
01316           // are correct using an SMT solver.
01317           if (!ICI.isSigned())
01318             CanFold = true;
01319           else {
01320             ConstantInt *ShiftedAndCst =
01321               cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
01322             ConstantInt *ShiftedRHSCst =
01323               cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
01324             
01325             if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
01326               CanFold = true;
01327           }
01328         }
01329 
01330         if (CanFold) {
01331           Constant *NewCst;
01332           if (ShiftOpcode == Instruction::Shl)
01333             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
01334           else
01335             NewCst = ConstantExpr::getShl(RHS, ShAmt);
01336 
01337           // Check to see if we are shifting out any of the bits being
01338           // compared.
01339           if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
01340             // If we shifted bits out, the fold is not going to work out.
01341             // As a special case, check to see if this means that the
01342             // result is always true or false now.
01343             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
01344               return ReplaceInstUsesWith(ICI, Builder->getFalse());
01345             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
01346               return ReplaceInstUsesWith(ICI, Builder->getTrue());
01347           } else {
01348             ICI.setOperand(1, NewCst);
01349             Constant *NewAndCst;
01350             if (ShiftOpcode == Instruction::Shl)
01351               NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
01352             else
01353               NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
01354             LHSI->setOperand(1, NewAndCst);
01355             LHSI->setOperand(0, Shift->getOperand(0));
01356             Worklist.Add(Shift); // Shift is dead.
01357             return &ICI;
01358           }
01359         }
01360       }
01361 
01362       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
01363       // preferable because it allows the C<<Y expression to be hoisted out
01364       // of a loop if Y is invariant and X is not.
01365       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
01366           ICI.isEquality() && !Shift->isArithmeticShift() &&
01367           !isa<Constant>(Shift->getOperand(0))) {
01368         // Compute C << Y.
01369         Value *NS;
01370         if (Shift->getOpcode() == Instruction::LShr) {
01371           NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
01372         } else {
01373           // Insert a logical shift.
01374           NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
01375         }
01376 
01377         // Compute X & (C << Y).
01378         Value *NewAnd =
01379           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
01380 
01381         ICI.setOperand(0, NewAnd);
01382         return &ICI;
01383       }
01384 
01385       // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
01386       //    (icmp pred (and X, (or (shl 1, Y), 1), 0))
01387       //
01388       // iff pred isn't signed
01389       {
01390         Value *X, *Y, *LShr;
01391         if (!ICI.isSigned() && RHSV == 0) {
01392           if (match(LHSI->getOperand(1), m_One())) {
01393             Constant *One = cast<Constant>(LHSI->getOperand(1));
01394             Value *Or = LHSI->getOperand(0);
01395             if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
01396                 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
01397               unsigned UsesRemoved = 0;
01398               if (LHSI->hasOneUse())
01399                 ++UsesRemoved;
01400               if (Or->hasOneUse())
01401                 ++UsesRemoved;
01402               if (LShr->hasOneUse())
01403                 ++UsesRemoved;
01404               Value *NewOr = nullptr;
01405               // Compute X & ((1 << Y) | 1)
01406               if (auto *C = dyn_cast<Constant>(Y)) {
01407                 if (UsesRemoved >= 1)
01408                   NewOr =
01409                       ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
01410               } else {
01411                 if (UsesRemoved >= 3)
01412                   NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
01413                                                                LShr->getName(),
01414                                                                /*HasNUW=*/true),
01415                                             One, Or->getName());
01416               }
01417               if (NewOr) {
01418                 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
01419                 ICI.setOperand(0, NewAnd);
01420                 return &ICI;
01421               }
01422             }
01423           }
01424         }
01425       }
01426 
01427       // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
01428       // bit set in (X & AndCst) will produce a result greater than RHSV.
01429       if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
01430         unsigned NTZ = AndCst->getValue().countTrailingZeros();
01431         if ((NTZ < AndCst->getBitWidth()) &&
01432             APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
01433           return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
01434                               Constant::getNullValue(RHS->getType()));
01435       }
01436     }
01437 
01438     // Try to optimize things like "A[i]&42 == 0" to index computations.
01439     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
01440       if (GetElementPtrInst *GEP =
01441           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
01442         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
01443           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
01444               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
01445             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
01446             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
01447               return Res;
01448           }
01449     }
01450 
01451     // X & -C == -C -> X >  u ~C
01452     // X & -C != -C -> X <= u ~C
01453     //   iff C is a power of 2
01454     if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
01455       return new ICmpInst(
01456           ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
01457                                                   : ICmpInst::ICMP_ULE,
01458           LHSI->getOperand(0), SubOne(RHS));
01459     break;
01460 
01461   case Instruction::Or: {
01462     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
01463       break;
01464     Value *P, *Q;
01465     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
01466       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
01467       // -> and (icmp eq P, null), (icmp eq Q, null).
01468       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
01469                                         Constant::getNullValue(P->getType()));
01470       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
01471                                         Constant::getNullValue(Q->getType()));
01472       Instruction *Op;
01473       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
01474         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
01475       else
01476         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
01477       return Op;
01478     }
01479     break;
01480   }
01481 
01482   case Instruction::Mul: {       // (icmp pred (mul X, Val), CI)
01483     ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
01484     if (!Val) break;
01485 
01486     // If this is a signed comparison to 0 and the mul is sign preserving,
01487     // use the mul LHS operand instead.
01488     ICmpInst::Predicate pred = ICI.getPredicate();
01489     if (isSignTest(pred, RHS) && !Val->isZero() &&
01490         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
01491       return new ICmpInst(Val->isNegative() ?
01492                           ICmpInst::getSwappedPredicate(pred) : pred,
01493                           LHSI->getOperand(0),
01494                           Constant::getNullValue(RHS->getType()));
01495 
01496     break;
01497   }
01498 
01499   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
01500     uint32_t TypeBits = RHSV.getBitWidth();
01501     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
01502     if (!ShAmt) {
01503       Value *X;
01504       // (1 << X) pred P2 -> X pred Log2(P2)
01505       if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
01506         bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
01507         ICmpInst::Predicate Pred = ICI.getPredicate();
01508         if (ICI.isUnsigned()) {
01509           if (!RHSVIsPowerOf2) {
01510             // (1 << X) <  30 -> X <= 4
01511             // (1 << X) <= 30 -> X <= 4
01512             // (1 << X) >= 30 -> X >  4
01513             // (1 << X) >  30 -> X >  4
01514             if (Pred == ICmpInst::ICMP_ULT)
01515               Pred = ICmpInst::ICMP_ULE;
01516             else if (Pred == ICmpInst::ICMP_UGE)
01517               Pred = ICmpInst::ICMP_UGT;
01518           }
01519           unsigned RHSLog2 = RHSV.logBase2();
01520 
01521           // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
01522           // (1 << X) <  2147483648 -> X <  31 -> X != 31
01523           if (RHSLog2 == TypeBits-1) {
01524             if (Pred == ICmpInst::ICMP_UGE)
01525               Pred = ICmpInst::ICMP_EQ;
01526             else if (Pred == ICmpInst::ICMP_ULT)
01527               Pred = ICmpInst::ICMP_NE;
01528           }
01529 
01530           return new ICmpInst(Pred, X,
01531                               ConstantInt::get(RHS->getType(), RHSLog2));
01532         } else if (ICI.isSigned()) {
01533           if (RHSV.isAllOnesValue()) {
01534             // (1 << X) <= -1 -> X == 31
01535             if (Pred == ICmpInst::ICMP_SLE)
01536               return new ICmpInst(ICmpInst::ICMP_EQ, X,
01537                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01538 
01539             // (1 << X) >  -1 -> X != 31
01540             if (Pred == ICmpInst::ICMP_SGT)
01541               return new ICmpInst(ICmpInst::ICMP_NE, X,
01542                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01543           } else if (!RHSV) {
01544             // (1 << X) <  0 -> X == 31
01545             // (1 << X) <= 0 -> X == 31
01546             if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
01547               return new ICmpInst(ICmpInst::ICMP_EQ, X,
01548                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01549 
01550             // (1 << X) >= 0 -> X != 31
01551             // (1 << X) >  0 -> X != 31
01552             if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
01553               return new ICmpInst(ICmpInst::ICMP_NE, X,
01554                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01555           }
01556         } else if (ICI.isEquality()) {
01557           if (RHSVIsPowerOf2)
01558             return new ICmpInst(
01559                 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
01560         }
01561       }
01562       break;
01563     }
01564 
01565     // Check that the shift amount is in range.  If not, don't perform
01566     // undefined shifts.  When the shift is visited it will be
01567     // simplified.
01568     if (ShAmt->uge(TypeBits))
01569       break;
01570 
01571     if (ICI.isEquality()) {
01572       // If we are comparing against bits always shifted out, the
01573       // comparison cannot succeed.
01574       Constant *Comp =
01575         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
01576                                                                  ShAmt);
01577       if (Comp != RHS) {// Comparing against a bit that we know is zero.
01578         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
01579         Constant *Cst = Builder->getInt1(IsICMP_NE);
01580         return ReplaceInstUsesWith(ICI, Cst);
01581       }
01582 
01583       // If the shift is NUW, then it is just shifting out zeros, no need for an
01584       // AND.
01585       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
01586         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
01587                             ConstantExpr::getLShr(RHS, ShAmt));
01588 
01589       // If the shift is NSW and we compare to 0, then it is just shifting out
01590       // sign bits, no need for an AND either.
01591       if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
01592         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
01593                             ConstantExpr::getLShr(RHS, ShAmt));
01594 
01595       if (LHSI->hasOneUse()) {
01596         // Otherwise strength reduce the shift into an and.
01597         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
01598         Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
01599                                                           TypeBits - ShAmtVal));
01600 
01601         Value *And =
01602           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
01603         return new ICmpInst(ICI.getPredicate(), And,
01604                             ConstantExpr::getLShr(RHS, ShAmt));
01605       }
01606     }
01607 
01608     // If this is a signed comparison to 0 and the shift is sign preserving,
01609     // use the shift LHS operand instead.
01610     ICmpInst::Predicate pred = ICI.getPredicate();
01611     if (isSignTest(pred, RHS) &&
01612         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
01613       return new ICmpInst(pred,
01614                           LHSI->getOperand(0),
01615                           Constant::getNullValue(RHS->getType()));
01616 
01617     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
01618     bool TrueIfSigned = false;
01619     if (LHSI->hasOneUse() &&
01620         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
01621       // (X << 31) <s 0  --> (X&1) != 0
01622       Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
01623                                         APInt::getOneBitSet(TypeBits,
01624                                             TypeBits-ShAmt->getZExtValue()-1));
01625       Value *And =
01626         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
01627       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
01628                           And, Constant::getNullValue(And->getType()));
01629     }
01630 
01631     // Transform (icmp pred iM (shl iM %v, N), CI)
01632     // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
01633     // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
01634     // This enables to get rid of the shift in favor of a trunc which can be
01635     // free on the target. It has the additional benefit of comparing to a
01636     // smaller constant, which will be target friendly.
01637     unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
01638     if (LHSI->hasOneUse() &&
01639         Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
01640       Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
01641       Constant *NCI = ConstantExpr::getTrunc(
01642                         ConstantExpr::getAShr(RHS,
01643                           ConstantInt::get(RHS->getType(), Amt)),
01644                         NTy);
01645       return new ICmpInst(ICI.getPredicate(),
01646                           Builder->CreateTrunc(LHSI->getOperand(0), NTy),
01647                           NCI);
01648     }
01649 
01650     break;
01651   }
01652 
01653   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
01654   case Instruction::AShr: {
01655     // Handle equality comparisons of shift-by-constant.
01656     BinaryOperator *BO = cast<BinaryOperator>(LHSI);
01657     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
01658       if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
01659         return Res;
01660     }
01661 
01662     // Handle exact shr's.
01663     if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
01664       if (RHSV.isMinValue())
01665         return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
01666     }
01667     break;
01668   }
01669 
01670   case Instruction::SDiv:
01671   case Instruction::UDiv:
01672     // Fold: icmp pred ([us]div X, C1), C2 -> range test
01673     // Fold this div into the comparison, producing a range check.
01674     // Determine, based on the divide type, what the range is being
01675     // checked.  If there is an overflow on the low or high side, remember
01676     // it, otherwise compute the range [low, hi) bounding the new value.
01677     // See: InsertRangeTest above for the kinds of replacements possible.
01678     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
01679       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
01680                                           DivRHS))
01681         return R;
01682     break;
01683 
01684   case Instruction::Sub: {
01685     ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
01686     if (!LHSC) break;
01687     const APInt &LHSV = LHSC->getValue();
01688 
01689     // C1-X <u C2 -> (X|(C2-1)) == C1
01690     //   iff C1 & (C2-1) == C2-1
01691     //       C2 is a power of 2
01692     if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
01693         RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
01694       return new ICmpInst(ICmpInst::ICMP_EQ,
01695                           Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
01696                           LHSC);
01697 
01698     // C1-X >u C2 -> (X|C2) != C1
01699     //   iff C1 & C2 == C2
01700     //       C2+1 is a power of 2
01701     if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
01702         (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
01703       return new ICmpInst(ICmpInst::ICMP_NE,
01704                           Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
01705     break;
01706   }
01707 
01708   case Instruction::Add:
01709     // Fold: icmp pred (add X, C1), C2
01710     if (!ICI.isEquality()) {
01711       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
01712       if (!LHSC) break;
01713       const APInt &LHSV = LHSC->getValue();
01714 
01715       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
01716                             .subtract(LHSV);
01717 
01718       if (ICI.isSigned()) {
01719         if (CR.getLower().isSignBit()) {
01720           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
01721                               Builder->getInt(CR.getUpper()));
01722         } else if (CR.getUpper().isSignBit()) {
01723           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
01724                               Builder->getInt(CR.getLower()));
01725         }
01726       } else {
01727         if (CR.getLower().isMinValue()) {
01728           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
01729                               Builder->getInt(CR.getUpper()));
01730         } else if (CR.getUpper().isMinValue()) {
01731           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
01732                               Builder->getInt(CR.getLower()));
01733         }
01734       }
01735 
01736       // X-C1 <u C2 -> (X & -C2) == C1
01737       //   iff C1 & (C2-1) == 0
01738       //       C2 is a power of 2
01739       if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
01740           RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
01741         return new ICmpInst(ICmpInst::ICMP_EQ,
01742                             Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
01743                             ConstantExpr::getNeg(LHSC));
01744 
01745       // X-C1 >u C2 -> (X & ~C2) != C1
01746       //   iff C1 & C2 == 0
01747       //       C2+1 is a power of 2
01748       if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
01749           (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
01750         return new ICmpInst(ICmpInst::ICMP_NE,
01751                             Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
01752                             ConstantExpr::getNeg(LHSC));
01753     }
01754     break;
01755   }
01756 
01757   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
01758   if (ICI.isEquality()) {
01759     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
01760 
01761     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
01762     // the second operand is a constant, simplify a bit.
01763     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
01764       switch (BO->getOpcode()) {
01765       case Instruction::SRem:
01766         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
01767         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
01768           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
01769           if (V.sgt(1) && V.isPowerOf2()) {
01770             Value *NewRem =
01771               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
01772                                   BO->getName());
01773             return new ICmpInst(ICI.getPredicate(), NewRem,
01774                                 Constant::getNullValue(BO->getType()));
01775           }
01776         }
01777         break;
01778       case Instruction::Add:
01779         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
01780         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01781           if (BO->hasOneUse())
01782             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01783                                 ConstantExpr::getSub(RHS, BOp1C));
01784         } else if (RHSV == 0) {
01785           // Replace ((add A, B) != 0) with (A != -B) if A or B is
01786           // efficiently invertible, or if the add has just this one use.
01787           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
01788 
01789           if (Value *NegVal = dyn_castNegVal(BOp1))
01790             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
01791           if (Value *NegVal = dyn_castNegVal(BOp0))
01792             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
01793           if (BO->hasOneUse()) {
01794             Value *Neg = Builder->CreateNeg(BOp1);
01795             Neg->takeName(BO);
01796             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
01797           }
01798         }
01799         break;
01800       case Instruction::Xor:
01801         // For the xor case, we can xor two constants together, eliminating
01802         // the explicit xor.
01803         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
01804           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01805                               ConstantExpr::getXor(RHS, BOC));
01806         } else if (RHSV == 0) {
01807           // Replace ((xor A, B) != 0) with (A != B)
01808           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01809                               BO->getOperand(1));
01810         }
01811         break;
01812       case Instruction::Sub:
01813         // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
01814         if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
01815           if (BO->hasOneUse())
01816             return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
01817                                 ConstantExpr::getSub(BOp0C, RHS));
01818         } else if (RHSV == 0) {
01819           // Replace ((sub A, B) != 0) with (A != B)
01820           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01821                               BO->getOperand(1));
01822         }
01823         break;
01824       case Instruction::Or:
01825         // If bits are being or'd in that are not present in the constant we
01826         // are comparing against, then the comparison could never succeed!
01827         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01828           Constant *NotCI = ConstantExpr::getNot(RHS);
01829           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
01830             return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
01831         }
01832         break;
01833 
01834       case Instruction::And:
01835         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01836           // If bits are being compared against that are and'd out, then the
01837           // comparison can never succeed!
01838           if ((RHSV & ~BOC->getValue()) != 0)
01839             return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
01840 
01841           // If we have ((X & C) == C), turn it into ((X & C) != 0).
01842           if (RHS == BOC && RHSV.isPowerOf2())
01843             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
01844                                 ICmpInst::ICMP_NE, LHSI,
01845                                 Constant::getNullValue(RHS->getType()));
01846 
01847           // Don't perform the following transforms if the AND has multiple uses
01848           if (!BO->hasOneUse())
01849             break;
01850 
01851           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
01852           if (BOC->getValue().isSignBit()) {
01853             Value *X = BO->getOperand(0);
01854             Constant *Zero = Constant::getNullValue(X->getType());
01855             ICmpInst::Predicate pred = isICMP_NE ?
01856               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
01857             return new ICmpInst(pred, X, Zero);
01858           }
01859 
01860           // ((X & ~7) == 0) --> X < 8
01861           if (RHSV == 0 && isHighOnes(BOC)) {
01862             Value *X = BO->getOperand(0);
01863             Constant *NegX = ConstantExpr::getNeg(BOC);
01864             ICmpInst::Predicate pred = isICMP_NE ?
01865               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
01866             return new ICmpInst(pred, X, NegX);
01867           }
01868         }
01869         break;
01870       case Instruction::Mul:
01871         if (RHSV == 0 && BO->hasNoSignedWrap()) {
01872           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01873             // The trivial case (mul X, 0) is handled by InstSimplify
01874             // General case : (mul X, C) != 0 iff X != 0
01875             //                (mul X, C) == 0 iff X == 0
01876             if (!BOC->isZero())
01877               return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01878                                   Constant::getNullValue(RHS->getType()));
01879           }
01880         }
01881         break;
01882       default: break;
01883       }
01884     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
01885       // Handle icmp {eq|ne} <intrinsic>, intcst.
01886       switch (II->getIntrinsicID()) {
01887       case Intrinsic::bswap:
01888         Worklist.Add(II);
01889         ICI.setOperand(0, II->getArgOperand(0));
01890         ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
01891         return &ICI;
01892       case Intrinsic::ctlz:
01893       case Intrinsic::cttz:
01894         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
01895         if (RHSV == RHS->getType()->getBitWidth()) {
01896           Worklist.Add(II);
01897           ICI.setOperand(0, II->getArgOperand(0));
01898           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
01899           return &ICI;
01900         }
01901         break;
01902       case Intrinsic::ctpop:
01903         // popcount(A) == 0  ->  A == 0 and likewise for !=
01904         if (RHS->isZero()) {
01905           Worklist.Add(II);
01906           ICI.setOperand(0, II->getArgOperand(0));
01907           ICI.setOperand(1, RHS);
01908           return &ICI;
01909         }
01910         break;
01911       default:
01912         break;
01913       }
01914     }
01915   }
01916   return nullptr;
01917 }
01918 
01919 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
01920 /// We only handle extending casts so far.
01921 ///
01922 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
01923   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
01924   Value *LHSCIOp        = LHSCI->getOperand(0);
01925   Type *SrcTy     = LHSCIOp->getType();
01926   Type *DestTy    = LHSCI->getType();
01927   Value *RHSCIOp;
01928 
01929   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
01930   // integer type is the same size as the pointer type.
01931   if (DL && LHSCI->getOpcode() == Instruction::PtrToInt &&
01932       DL->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
01933     Value *RHSOp = nullptr;
01934     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
01935       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
01936     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
01937       RHSOp = RHSC->getOperand(0);
01938       // If the pointer types don't match, insert a bitcast.
01939       if (LHSCIOp->getType() != RHSOp->getType())
01940         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
01941     }
01942 
01943     if (RHSOp)
01944       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
01945   }
01946 
01947   // The code below only handles extension cast instructions, so far.
01948   // Enforce this.
01949   if (LHSCI->getOpcode() != Instruction::ZExt &&
01950       LHSCI->getOpcode() != Instruction::SExt)
01951     return nullptr;
01952 
01953   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
01954   bool isSignedCmp = ICI.isSigned();
01955 
01956   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
01957     // Not an extension from the same type?
01958     RHSCIOp = CI->getOperand(0);
01959     if (RHSCIOp->getType() != LHSCIOp->getType())
01960       return nullptr;
01961 
01962     // If the signedness of the two casts doesn't agree (i.e. one is a sext
01963     // and the other is a zext), then we can't handle this.
01964     if (CI->getOpcode() != LHSCI->getOpcode())
01965       return nullptr;
01966 
01967     // Deal with equality cases early.
01968     if (ICI.isEquality())
01969       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
01970 
01971     // A signed comparison of sign extended values simplifies into a
01972     // signed comparison.
01973     if (isSignedCmp && isSignedExt)
01974       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
01975 
01976     // The other three cases all fold into an unsigned comparison.
01977     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
01978   }
01979 
01980   // If we aren't dealing with a constant on the RHS, exit early
01981   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
01982   if (!CI)
01983     return nullptr;
01984 
01985   // Compute the constant that would happen if we truncated to SrcTy then
01986   // reextended to DestTy.
01987   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
01988   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
01989                                                 Res1, DestTy);
01990 
01991   // If the re-extended constant didn't change...
01992   if (Res2 == CI) {
01993     // Deal with equality cases early.
01994     if (ICI.isEquality())
01995       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
01996 
01997     // A signed comparison of sign extended values simplifies into a
01998     // signed comparison.
01999     if (isSignedExt && isSignedCmp)
02000       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
02001 
02002     // The other three cases all fold into an unsigned comparison.
02003     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
02004   }
02005 
02006   // The re-extended constant changed so the constant cannot be represented
02007   // in the shorter type. Consequently, we cannot emit a simple comparison.
02008   // All the cases that fold to true or false will have already been handled
02009   // by SimplifyICmpInst, so only deal with the tricky case.
02010 
02011   if (isSignedCmp || !isSignedExt)
02012     return nullptr;
02013 
02014   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
02015   // should have been folded away previously and not enter in here.
02016 
02017   // We're performing an unsigned comp with a sign extended value.
02018   // This is true if the input is >= 0. [aka >s -1]
02019   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
02020   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
02021 
02022   // Finally, return the value computed.
02023   if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
02024     return ReplaceInstUsesWith(ICI, Result);
02025 
02026   assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
02027   return BinaryOperator::CreateNot(Result);
02028 }
02029 
02030 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
02031 ///   I = icmp ugt (add (add A, B), CI2), CI1
02032 /// If this is of the form:
02033 ///   sum = a + b
02034 ///   if (sum+128 >u 255)
02035 /// Then replace it with llvm.sadd.with.overflow.i8.
02036 ///
02037 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
02038                                           ConstantInt *CI2, ConstantInt *CI1,
02039                                           InstCombiner &IC) {
02040   // The transformation we're trying to do here is to transform this into an
02041   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
02042   // with a narrower add, and discard the add-with-constant that is part of the
02043   // range check (if we can't eliminate it, this isn't profitable).
02044 
02045   // In order to eliminate the add-with-constant, the compare can be its only
02046   // use.
02047   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
02048   if (!AddWithCst->hasOneUse()) return nullptr;
02049 
02050   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
02051   if (!CI2->getValue().isPowerOf2()) return nullptr;
02052   unsigned NewWidth = CI2->getValue().countTrailingZeros();
02053   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
02054 
02055   // The width of the new add formed is 1 more than the bias.
02056   ++NewWidth;
02057 
02058   // Check to see that CI1 is an all-ones value with NewWidth bits.
02059   if (CI1->getBitWidth() == NewWidth ||
02060       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
02061     return nullptr;
02062 
02063   // This is only really a signed overflow check if the inputs have been
02064   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
02065   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
02066   unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
02067   if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
02068       IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
02069     return nullptr;
02070 
02071   // In order to replace the original add with a narrower
02072   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
02073   // and truncates that discard the high bits of the add.  Verify that this is
02074   // the case.
02075   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
02076   for (User *U : OrigAdd->users()) {
02077     if (U == AddWithCst) continue;
02078 
02079     // Only accept truncates for now.  We would really like a nice recursive
02080     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
02081     // chain to see which bits of a value are actually demanded.  If the
02082     // original add had another add which was then immediately truncated, we
02083     // could still do the transformation.
02084     TruncInst *TI = dyn_cast<TruncInst>(U);
02085     if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
02086       return nullptr;
02087   }
02088 
02089   // If the pattern matches, truncate the inputs to the narrower type and
02090   // use the sadd_with_overflow intrinsic to efficiently compute both the
02091   // result and the overflow bit.
02092   Module *M = I.getParent()->getParent()->getParent();
02093 
02094   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
02095   Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
02096                                        NewType);
02097 
02098   InstCombiner::BuilderTy *Builder = IC.Builder;
02099 
02100   // Put the new code above the original add, in case there are any uses of the
02101   // add between the add and the compare.
02102   Builder->SetInsertPoint(OrigAdd);
02103 
02104   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
02105   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
02106   CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
02107   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
02108   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
02109 
02110   // The inner add was the result of the narrow add, zero extended to the
02111   // wider type.  Replace it with the result computed by the intrinsic.
02112   IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
02113 
02114   // The original icmp gets replaced with the overflow value.
02115   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
02116 }
02117 
02118 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
02119                                      InstCombiner &IC) {
02120   // Don't bother doing this transformation for pointers, don't do it for
02121   // vectors.
02122   if (!isa<IntegerType>(OrigAddV->getType())) return nullptr;
02123 
02124   // If the add is a constant expr, then we don't bother transforming it.
02125   Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
02126   if (!OrigAdd) return nullptr;
02127 
02128   Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
02129 
02130   // Put the new code above the original add, in case there are any uses of the
02131   // add between the add and the compare.
02132   InstCombiner::BuilderTy *Builder = IC.Builder;
02133   Builder->SetInsertPoint(OrigAdd);
02134 
02135   Module *M = I.getParent()->getParent()->getParent();
02136   Type *Ty = LHS->getType();
02137   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
02138   CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
02139   Value *Add = Builder->CreateExtractValue(Call, 0);
02140 
02141   IC.ReplaceInstUsesWith(*OrigAdd, Add);
02142 
02143   // The original icmp gets replaced with the overflow value.
02144   return ExtractValueInst::Create(Call, 1, "uadd.overflow");
02145 }
02146 
02147 /// \brief Recognize and process idiom involving test for multiplication
02148 /// overflow.
02149 ///
02150 /// The caller has matched a pattern of the form:
02151 ///   I = cmp u (mul(zext A, zext B), V
02152 /// The function checks if this is a test for overflow and if so replaces
02153 /// multiplication with call to 'mul.with.overflow' intrinsic.
02154 ///
02155 /// \param I Compare instruction.
02156 /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
02157 ///               the compare instruction.  Must be of integer type.
02158 /// \param OtherVal The other argument of compare instruction.
02159 /// \returns Instruction which must replace the compare instruction, NULL if no
02160 ///          replacement required.
02161 static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
02162                                          Value *OtherVal, InstCombiner &IC) {
02163   // Don't bother doing this transformation for pointers, don't do it for
02164   // vectors.
02165   if (!isa<IntegerType>(MulVal->getType()))
02166     return nullptr;
02167 
02168   assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
02169   assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
02170   Instruction *MulInstr = cast<Instruction>(MulVal);
02171   assert(MulInstr->getOpcode() == Instruction::Mul);
02172 
02173   auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
02174        *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
02175   assert(LHS->getOpcode() == Instruction::ZExt);
02176   assert(RHS->getOpcode() == Instruction::ZExt);
02177   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
02178 
02179   // Calculate type and width of the result produced by mul.with.overflow.
02180   Type *TyA = A->getType(), *TyB = B->getType();
02181   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
02182            WidthB = TyB->getPrimitiveSizeInBits();
02183   unsigned MulWidth;
02184   Type *MulType;
02185   if (WidthB > WidthA) {
02186     MulWidth = WidthB;
02187     MulType = TyB;
02188   } else {
02189     MulWidth = WidthA;
02190     MulType = TyA;
02191   }
02192 
02193   // In order to replace the original mul with a narrower mul.with.overflow,
02194   // all uses must ignore upper bits of the product.  The number of used low
02195   // bits must be not greater than the width of mul.with.overflow.
02196   if (MulVal->hasNUsesOrMore(2))
02197     for (User *U : MulVal->users()) {
02198       if (U == &I)
02199         continue;
02200       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
02201         // Check if truncation ignores bits above MulWidth.
02202         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
02203         if (TruncWidth > MulWidth)
02204           return nullptr;
02205       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
02206         // Check if AND ignores bits above MulWidth.
02207         if (BO->getOpcode() != Instruction::And)
02208           return nullptr;
02209         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
02210           const APInt &CVal = CI->getValue();
02211           if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
02212             return nullptr;
02213         }
02214       } else {
02215         // Other uses prohibit this transformation.
02216         return nullptr;
02217       }
02218     }
02219 
02220   // Recognize patterns
02221   switch (I.getPredicate()) {
02222   case ICmpInst::ICMP_EQ:
02223   case ICmpInst::ICMP_NE:
02224     // Recognize pattern:
02225     //   mulval = mul(zext A, zext B)
02226     //   cmp eq/neq mulval, zext trunc mulval
02227     if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
02228       if (Zext->hasOneUse()) {
02229         Value *ZextArg = Zext->getOperand(0);
02230         if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
02231           if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
02232             break; //Recognized
02233       }
02234 
02235     // Recognize pattern:
02236     //   mulval = mul(zext A, zext B)
02237     //   cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
02238     ConstantInt *CI;
02239     Value *ValToMask;
02240     if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
02241       if (ValToMask != MulVal)
02242         return nullptr;
02243       const APInt &CVal = CI->getValue() + 1;
02244       if (CVal.isPowerOf2()) {
02245         unsigned MaskWidth = CVal.logBase2();
02246         if (MaskWidth == MulWidth)
02247           break; // Recognized
02248       }
02249     }
02250     return nullptr;
02251 
02252   case ICmpInst::ICMP_UGT:
02253     // Recognize pattern:
02254     //   mulval = mul(zext A, zext B)
02255     //   cmp ugt mulval, max
02256     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02257       APInt MaxVal = APInt::getMaxValue(MulWidth);
02258       MaxVal = MaxVal.zext(CI->getBitWidth());
02259       if (MaxVal.eq(CI->getValue()))
02260         break; // Recognized
02261     }
02262     return nullptr;
02263 
02264   case ICmpInst::ICMP_UGE:
02265     // Recognize pattern:
02266     //   mulval = mul(zext A, zext B)
02267     //   cmp uge mulval, max+1
02268     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02269       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
02270       if (MaxVal.eq(CI->getValue()))
02271         break; // Recognized
02272     }
02273     return nullptr;
02274 
02275   case ICmpInst::ICMP_ULE:
02276     // Recognize pattern:
02277     //   mulval = mul(zext A, zext B)
02278     //   cmp ule mulval, max
02279     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02280       APInt MaxVal = APInt::getMaxValue(MulWidth);
02281       MaxVal = MaxVal.zext(CI->getBitWidth());
02282       if (MaxVal.eq(CI->getValue()))
02283         break; // Recognized
02284     }
02285     return nullptr;
02286 
02287   case ICmpInst::ICMP_ULT:
02288     // Recognize pattern:
02289     //   mulval = mul(zext A, zext B)
02290     //   cmp ule mulval, max + 1
02291     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02292       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
02293       if (MaxVal.eq(CI->getValue()))
02294         break; // Recognized
02295     }
02296     return nullptr;
02297 
02298   default:
02299     return nullptr;
02300   }
02301 
02302   InstCombiner::BuilderTy *Builder = IC.Builder;
02303   Builder->SetInsertPoint(MulInstr);
02304   Module *M = I.getParent()->getParent()->getParent();
02305 
02306   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
02307   Value *MulA = A, *MulB = B;
02308   if (WidthA < MulWidth)
02309     MulA = Builder->CreateZExt(A, MulType);
02310   if (WidthB < MulWidth)
02311     MulB = Builder->CreateZExt(B, MulType);
02312   Value *F =
02313       Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
02314   CallInst *Call = Builder->CreateCall2(F, MulA, MulB, "umul");
02315   IC.Worklist.Add(MulInstr);
02316 
02317   // If there are uses of mul result other than the comparison, we know that
02318   // they are truncation or binary AND. Change them to use result of
02319   // mul.with.overflow and adjust properly mask/size.
02320   if (MulVal->hasNUsesOrMore(2)) {
02321     Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
02322     for (User *U : MulVal->users()) {
02323       if (U == &I || U == OtherVal)
02324         continue;
02325       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
02326         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
02327           IC.ReplaceInstUsesWith(*TI, Mul);
02328         else
02329           TI->setOperand(0, Mul);
02330       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
02331         assert(BO->getOpcode() == Instruction::And);
02332         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
02333         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
02334         APInt ShortMask = CI->getValue().trunc(MulWidth);
02335         Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
02336         Instruction *Zext =
02337             cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
02338         IC.Worklist.Add(Zext);
02339         IC.ReplaceInstUsesWith(*BO, Zext);
02340       } else {
02341         llvm_unreachable("Unexpected Binary operation");
02342       }
02343       IC.Worklist.Add(cast<Instruction>(U));
02344     }
02345   }
02346   if (isa<Instruction>(OtherVal))
02347     IC.Worklist.Add(cast<Instruction>(OtherVal));
02348 
02349   // The original icmp gets replaced with the overflow value, maybe inverted
02350   // depending on predicate.
02351   bool Inverse = false;
02352   switch (I.getPredicate()) {
02353   case ICmpInst::ICMP_NE:
02354     break;
02355   case ICmpInst::ICMP_EQ:
02356     Inverse = true;
02357     break;
02358   case ICmpInst::ICMP_UGT:
02359   case ICmpInst::ICMP_UGE:
02360     if (I.getOperand(0) == MulVal)
02361       break;
02362     Inverse = true;
02363     break;
02364   case ICmpInst::ICMP_ULT:
02365   case ICmpInst::ICMP_ULE:
02366     if (I.getOperand(1) == MulVal)
02367       break;
02368     Inverse = true;
02369     break;
02370   default:
02371     llvm_unreachable("Unexpected predicate");
02372   }
02373   if (Inverse) {
02374     Value *Res = Builder->CreateExtractValue(Call, 1);
02375     return BinaryOperator::CreateNot(Res);
02376   }
02377 
02378   return ExtractValueInst::Create(Call, 1);
02379 }
02380 
02381 // DemandedBitsLHSMask - When performing a comparison against a constant,
02382 // it is possible that not all the bits in the LHS are demanded.  This helper
02383 // method computes the mask that IS demanded.
02384 static APInt DemandedBitsLHSMask(ICmpInst &I,
02385                                  unsigned BitWidth, bool isSignCheck) {
02386   if (isSignCheck)
02387     return APInt::getSignBit(BitWidth);
02388 
02389   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
02390   if (!CI) return APInt::getAllOnesValue(BitWidth);
02391   const APInt &RHS = CI->getValue();
02392 
02393   switch (I.getPredicate()) {
02394   // For a UGT comparison, we don't care about any bits that
02395   // correspond to the trailing ones of the comparand.  The value of these
02396   // bits doesn't impact the outcome of the comparison, because any value
02397   // greater than the RHS must differ in a bit higher than these due to carry.
02398   case ICmpInst::ICMP_UGT: {
02399     unsigned trailingOnes = RHS.countTrailingOnes();
02400     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
02401     return ~lowBitsSet;
02402   }
02403 
02404   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
02405   // Any value less than the RHS must differ in a higher bit because of carries.
02406   case ICmpInst::ICMP_ULT: {
02407     unsigned trailingZeros = RHS.countTrailingZeros();
02408     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
02409     return ~lowBitsSet;
02410   }
02411 
02412   default:
02413     return APInt::getAllOnesValue(BitWidth);
02414   }
02415 
02416 }
02417 
02418 /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
02419 /// should be swapped.
02420 /// The decision is based on how many times these two operands are reused
02421 /// as subtract operands and their positions in those instructions.
02422 /// The rational is that several architectures use the same instruction for
02423 /// both subtract and cmp, thus it is better if the order of those operands
02424 /// match.
02425 /// \return true if Op0 and Op1 should be swapped.
02426 static bool swapMayExposeCSEOpportunities(const Value * Op0,
02427                                           const Value * Op1) {
02428   // Filter out pointer value as those cannot appears directly in subtract.
02429   // FIXME: we may want to go through inttoptrs or bitcasts.
02430   if (Op0->getType()->isPointerTy())
02431     return false;
02432   // Count every uses of both Op0 and Op1 in a subtract.
02433   // Each time Op0 is the first operand, count -1: swapping is bad, the
02434   // subtract has already the same layout as the compare.
02435   // Each time Op0 is the second operand, count +1: swapping is good, the
02436   // subtract has a different layout as the compare.
02437   // At the end, if the benefit is greater than 0, Op0 should come second to
02438   // expose more CSE opportunities.
02439   int GlobalSwapBenefits = 0;
02440   for (const User *U : Op0->users()) {
02441     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
02442     if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
02443       continue;
02444     // If Op0 is the first argument, this is not beneficial to swap the
02445     // arguments.
02446     int LocalSwapBenefits = -1;
02447     unsigned Op1Idx = 1;
02448     if (BinOp->getOperand(Op1Idx) == Op0) {
02449       Op1Idx = 0;
02450       LocalSwapBenefits = 1;
02451     }
02452     if (BinOp->getOperand(Op1Idx) != Op1)
02453       continue;
02454     GlobalSwapBenefits += LocalSwapBenefits;
02455   }
02456   return GlobalSwapBenefits > 0;
02457 }
02458 
02459 /// \brief Check that one use is in the same block as the definition and all
02460 /// other uses are in blocks dominated by a given block
02461 ///
02462 /// \param DI Definition
02463 /// \param UI Use
02464 /// \param DB Block that must dominate all uses of \p DI outside
02465 ///           the parent block
02466 /// \return true when \p UI is the only use of \p DI in the parent block
02467 /// and all other uses of \p DI are in blocks dominated by \p DB.
02468 ///
02469 bool InstCombiner::dominatesAllUses(const Instruction *DI,
02470                                     const Instruction *UI,
02471                                     const BasicBlock *DB) const {
02472   assert(DI && UI && "Instruction not defined\n");
02473   // ignore incomplete definitions
02474   if (!DI->getParent())
02475     return false;
02476   // DI and UI must be in the same block
02477   if (DI->getParent() != UI->getParent())
02478     return false;
02479   // Protect from self-referencing blocks
02480   if (DI->getParent() == DB)
02481     return false;
02482   // DominatorTree available?
02483   if (!DT)
02484     return false;
02485   for (const User *U : DI->users()) {
02486     auto *Usr = cast<Instruction>(U);
02487     if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
02488       return false;
02489   }
02490   return true;
02491 }
02492 
02493 ///
02494 /// true when the instruction sequence within a block is select-cmp-br.
02495 ///
02496 static bool isChainSelectCmpBranch(const SelectInst *SI) {
02497   const BasicBlock *BB = SI->getParent();
02498   if (!BB)
02499     return false;
02500   auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
02501   if (!BI || BI->getNumSuccessors() != 2)
02502     return false;
02503   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
02504   if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
02505     return false;
02506   return true;
02507 }
02508 
02509 ///
02510 /// \brief True when a select result is replaced by one of its operands
02511 /// in select-icmp sequence. This will eventually result in the elimination
02512 /// of the select.
02513 ///
02514 /// \param SI    Select instruction
02515 /// \param Icmp  Compare instruction
02516 /// \param SIOpd Operand that replaces the select
02517 ///
02518 /// Notes:
02519 /// - The replacement is global and requires dominator information
02520 /// - The caller is responsible for the actual replacement
02521 ///
02522 /// Example:
02523 ///
02524 /// entry:
02525 ///  %4 = select i1 %3, %C* %0, %C* null
02526 ///  %5 = icmp eq %C* %4, null
02527 ///  br i1 %5, label %9, label %7
02528 ///  ...
02529 ///  ; <label>:7                                       ; preds = %entry
02530 ///  %8 = getelementptr inbounds %C* %4, i64 0, i32 0
02531 ///  ...
02532 ///
02533 /// can be transformed to
02534 ///
02535 ///  %5 = icmp eq %C* %0, null
02536 ///  %6 = select i1 %3, i1 %5, i1 true
02537 ///  br i1 %6, label %9, label %7
02538 ///  ...
02539 ///  ; <label>:7                                       ; preds = %entry
02540 ///  %8 = getelementptr inbounds %C* %0, i64 0, i32 0  // replace by %0!
02541 ///
02542 /// Similar when the first operand of the select is a constant or/and
02543 /// the compare is for not equal rather than equal.
02544 ///
02545 /// NOTE: The function is only called when the select and compare constants
02546 /// are equal, the optimization can work only for EQ predicates. This is not a
02547 /// major restriction since a NE compare should be 'normalized' to an equal
02548 /// compare, which usually happens in the combiner and test case
02549 /// select-cmp-br.ll
02550 /// checks for it.
02551 bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
02552                                              const ICmpInst *Icmp,
02553                                              const unsigned SIOpd) {
02554   assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
02555   if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
02556     BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
02557     // The check for the unique predecessor is not the best that can be
02558     // done. But it protects efficiently against cases like  when SI's
02559     // home block has two successors, Succ and Succ1, and Succ1 predecessor
02560     // of Succ. Then SI can't be replaced by SIOpd because the use that gets
02561     // replaced can be reached on either path. So the uniqueness check
02562     // guarantees that the path all uses of SI (outside SI's parent) are on
02563     // is disjoint from all other paths out of SI. But that information
02564     // is more expensive to compute, and the trade-off here is in favor
02565     // of compile-time.
02566     if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
02567       NumSel++;
02568       SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
02569       return true;
02570     }
02571   }
02572   return false;
02573 }
02574 
02575 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
02576   bool Changed = false;
02577   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02578   unsigned Op0Cplxity = getComplexity(Op0);
02579   unsigned Op1Cplxity = getComplexity(Op1);
02580 
02581   /// Orders the operands of the compare so that they are listed from most
02582   /// complex to least complex.  This puts constants before unary operators,
02583   /// before binary operators.
02584   if (Op0Cplxity < Op1Cplxity ||
02585         (Op0Cplxity == Op1Cplxity &&
02586          swapMayExposeCSEOpportunities(Op0, Op1))) {
02587     I.swapOperands();
02588     std::swap(Op0, Op1);
02589     Changed = true;
02590   }
02591 
02592   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC))
02593     return ReplaceInstUsesWith(I, V);
02594 
02595   // comparing -val or val with non-zero is the same as just comparing val
02596   // ie, abs(val) != 0 -> val != 0
02597   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
02598   {
02599     Value *Cond, *SelectTrue, *SelectFalse;
02600     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
02601                             m_Value(SelectFalse)))) {
02602       if (Value *V = dyn_castNegVal(SelectTrue)) {
02603         if (V == SelectFalse)
02604           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
02605       }
02606       else if (Value *V = dyn_castNegVal(SelectFalse)) {
02607         if (V == SelectTrue)
02608           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
02609       }
02610     }
02611   }
02612 
02613   Type *Ty = Op0->getType();
02614 
02615   // icmp's with boolean values can always be turned into bitwise operations
02616   if (Ty->isIntegerTy(1)) {
02617     switch (I.getPredicate()) {
02618     default: llvm_unreachable("Invalid icmp instruction!");
02619     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
02620       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
02621       return BinaryOperator::CreateNot(Xor);
02622     }
02623     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
02624       return BinaryOperator::CreateXor(Op0, Op1);
02625 
02626     case ICmpInst::ICMP_UGT:
02627       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
02628       // FALL THROUGH
02629     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
02630       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
02631       return BinaryOperator::CreateAnd(Not, Op1);
02632     }
02633     case ICmpInst::ICMP_SGT:
02634       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
02635       // FALL THROUGH
02636     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
02637       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
02638       return BinaryOperator::CreateAnd(Not, Op0);
02639     }
02640     case ICmpInst::ICMP_UGE:
02641       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
02642       // FALL THROUGH
02643     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
02644       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
02645       return BinaryOperator::CreateOr(Not, Op1);
02646     }
02647     case ICmpInst::ICMP_SGE:
02648       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
02649       // FALL THROUGH
02650     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
02651       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
02652       return BinaryOperator::CreateOr(Not, Op0);
02653     }
02654     }
02655   }
02656 
02657   unsigned BitWidth = 0;
02658   if (Ty->isIntOrIntVectorTy())
02659     BitWidth = Ty->getScalarSizeInBits();
02660   else if (DL)  // Pointers require DL info to get their size.
02661     BitWidth = DL->getTypeSizeInBits(Ty->getScalarType());
02662 
02663   bool isSignBit = false;
02664 
02665   // See if we are doing a comparison with a constant.
02666   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02667     Value *A = nullptr, *B = nullptr;
02668 
02669     // Match the following pattern, which is a common idiom when writing
02670     // overflow-safe integer arithmetic function.  The source performs an
02671     // addition in wider type, and explicitly checks for overflow using
02672     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
02673     // sadd_with_overflow intrinsic.
02674     //
02675     // TODO: This could probably be generalized to handle other overflow-safe
02676     // operations if we worked out the formulas to compute the appropriate
02677     // magic constants.
02678     //
02679     // sum = a + b
02680     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
02681     {
02682     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
02683     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
02684         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
02685       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
02686         return Res;
02687     }
02688 
02689     // The following transforms are only 'worth it' if the only user of the
02690     // subtraction is the icmp.
02691     if (Op0->hasOneUse()) {
02692       // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
02693       if (I.isEquality() && CI->isZero() &&
02694           match(Op0, m_Sub(m_Value(A), m_Value(B))))
02695         return new ICmpInst(I.getPredicate(), A, B);
02696 
02697       // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
02698       if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
02699           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02700         return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
02701 
02702       // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
02703       if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
02704           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02705         return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
02706 
02707       // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
02708       if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
02709           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02710         return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
02711 
02712       // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
02713       if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
02714           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02715         return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
02716     }
02717 
02718     // If we have an icmp le or icmp ge instruction, turn it into the
02719     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
02720     // them being folded in the code below.  The SimplifyICmpInst code has
02721     // already handled the edge cases for us, so we just assert on them.
02722     switch (I.getPredicate()) {
02723     default: break;
02724     case ICmpInst::ICMP_ULE:
02725       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
02726       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
02727                           Builder->getInt(CI->getValue()+1));
02728     case ICmpInst::ICMP_SLE:
02729       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
02730       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
02731                           Builder->getInt(CI->getValue()+1));
02732     case ICmpInst::ICMP_UGE:
02733       assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
02734       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
02735                           Builder->getInt(CI->getValue()-1));
02736     case ICmpInst::ICMP_SGE:
02737       assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
02738       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
02739                           Builder->getInt(CI->getValue()-1));
02740     }
02741 
02742     if (I.isEquality()) {
02743       ConstantInt *CI2;
02744       if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
02745           match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
02746         // (icmp eq/ne (ashr/lshr const2, A), const1)
02747         if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
02748           return Inst;
02749       }
02750       if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
02751         // (icmp eq/ne (shl const2, A), const1)
02752         if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
02753           return Inst;
02754       }
02755     }
02756 
02757     // If this comparison is a normal comparison, it demands all
02758     // bits, if it is a sign bit comparison, it only demands the sign bit.
02759     bool UnusedBit;
02760     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
02761   }
02762 
02763   // See if we can fold the comparison based on range information we can get
02764   // by checking whether bits are known to be zero or one in the input.
02765   if (BitWidth != 0) {
02766     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
02767     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
02768 
02769     if (SimplifyDemandedBits(I.getOperandUse(0),
02770                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
02771                              Op0KnownZero, Op0KnownOne, 0))
02772       return &I;
02773     if (SimplifyDemandedBits(I.getOperandUse(1),
02774                              APInt::getAllOnesValue(BitWidth),
02775                              Op1KnownZero, Op1KnownOne, 0))
02776       return &I;
02777 
02778     // Given the known and unknown bits, compute a range that the LHS could be
02779     // in.  Compute the Min, Max and RHS values based on the known bits. For the
02780     // EQ and NE we use unsigned values.
02781     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
02782     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
02783     if (I.isSigned()) {
02784       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
02785                                              Op0Min, Op0Max);
02786       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
02787                                              Op1Min, Op1Max);
02788     } else {
02789       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
02790                                                Op0Min, Op0Max);
02791       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
02792                                                Op1Min, Op1Max);
02793     }
02794 
02795     // If Min and Max are known to be the same, then SimplifyDemandedBits
02796     // figured out that the LHS is a constant.  Just constant fold this now so
02797     // that code below can assume that Min != Max.
02798     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
02799       return new ICmpInst(I.getPredicate(),
02800                           ConstantInt::get(Op0->getType(), Op0Min), Op1);
02801     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
02802       return new ICmpInst(I.getPredicate(), Op0,
02803                           ConstantInt::get(Op1->getType(), Op1Min));
02804 
02805     // Based on the range information we know about the LHS, see if we can
02806     // simplify this comparison.  For example, (x&4) < 8 is always true.
02807     switch (I.getPredicate()) {
02808     default: llvm_unreachable("Unknown icmp opcode!");
02809     case ICmpInst::ICMP_EQ: {
02810       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
02811         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02812 
02813       // If all bits are known zero except for one, then we know at most one
02814       // bit is set.   If the comparison is against zero, then this is a check
02815       // to see if *that* bit is set.
02816       APInt Op0KnownZeroInverted = ~Op0KnownZero;
02817       if (~Op1KnownZero == 0) {
02818         // If the LHS is an AND with the same constant, look through it.
02819         Value *LHS = nullptr;
02820         ConstantInt *LHSC = nullptr;
02821         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
02822             LHSC->getValue() != Op0KnownZeroInverted)
02823           LHS = Op0;
02824 
02825         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
02826         // then turn "((1 << x)&8) == 0" into "x != 3".
02827         // or turn "((1 << x)&7) == 0" into "x > 2".
02828         Value *X = nullptr;
02829         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
02830           APInt ValToCheck = Op0KnownZeroInverted;
02831           if (ValToCheck.isPowerOf2()) {
02832             unsigned CmpVal = ValToCheck.countTrailingZeros();
02833             return new ICmpInst(ICmpInst::ICMP_NE, X,
02834                                 ConstantInt::get(X->getType(), CmpVal));
02835           } else if ((++ValToCheck).isPowerOf2()) {
02836             unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
02837             return new ICmpInst(ICmpInst::ICMP_UGT, X,
02838                                 ConstantInt::get(X->getType(), CmpVal));
02839           }
02840         }
02841 
02842         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
02843         // then turn "((8 >>u x)&1) == 0" into "x != 3".
02844         const APInt *CI;
02845         if (Op0KnownZeroInverted == 1 &&
02846             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
02847           return new ICmpInst(ICmpInst::ICMP_NE, X,
02848                               ConstantInt::get(X->getType(),
02849                                                CI->countTrailingZeros()));
02850       }
02851 
02852       break;
02853     }
02854     case ICmpInst::ICMP_NE: {
02855       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
02856         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02857 
02858       // If all bits are known zero except for one, then we know at most one
02859       // bit is set.   If the comparison is against zero, then this is a check
02860       // to see if *that* bit is set.
02861       APInt Op0KnownZeroInverted = ~Op0KnownZero;
02862       if (~Op1KnownZero == 0) {
02863         // If the LHS is an AND with the same constant, look through it.
02864         Value *LHS = nullptr;
02865         ConstantInt *LHSC = nullptr;
02866         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
02867             LHSC->getValue() != Op0KnownZeroInverted)
02868           LHS = Op0;
02869 
02870         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
02871         // then turn "((1 << x)&8) != 0" into "x == 3".
02872         // or turn "((1 << x)&7) != 0" into "x < 3".
02873         Value *X = nullptr;
02874         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
02875           APInt ValToCheck = Op0KnownZeroInverted;
02876           if (ValToCheck.isPowerOf2()) {
02877             unsigned CmpVal = ValToCheck.countTrailingZeros();
02878             return new ICmpInst(ICmpInst::ICMP_EQ, X,
02879                                 ConstantInt::get(X->getType(), CmpVal));
02880           } else if ((++ValToCheck).isPowerOf2()) {
02881             unsigned CmpVal = ValToCheck.countTrailingZeros();
02882             return new ICmpInst(ICmpInst::ICMP_ULT, X,
02883                                 ConstantInt::get(X->getType(), CmpVal));
02884           }
02885         }
02886 
02887         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
02888         // then turn "((8 >>u x)&1) != 0" into "x == 3".
02889         const APInt *CI;
02890         if (Op0KnownZeroInverted == 1 &&
02891             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
02892           return new ICmpInst(ICmpInst::ICMP_EQ, X,
02893                               ConstantInt::get(X->getType(),
02894                                                CI->countTrailingZeros()));
02895       }
02896 
02897       break;
02898     }
02899     case ICmpInst::ICMP_ULT:
02900       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
02901         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02902       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
02903         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02904       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
02905         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02906       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02907         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
02908           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02909                               Builder->getInt(CI->getValue()-1));
02910 
02911         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
02912         if (CI->isMinValue(true))
02913           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
02914                            Constant::getAllOnesValue(Op0->getType()));
02915       }
02916       break;
02917     case ICmpInst::ICMP_UGT:
02918       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
02919         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02920       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
02921         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02922 
02923       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
02924         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02925       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02926         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
02927           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02928                               Builder->getInt(CI->getValue()+1));
02929 
02930         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
02931         if (CI->isMaxValue(true))
02932           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
02933                               Constant::getNullValue(Op0->getType()));
02934       }
02935       break;
02936     case ICmpInst::ICMP_SLT:
02937       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
02938         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02939       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
02940         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02941       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
02942         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02943       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02944         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
02945           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02946                               Builder->getInt(CI->getValue()-1));
02947       }
02948       break;
02949     case ICmpInst::ICMP_SGT:
02950       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
02951         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02952       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
02953         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02954 
02955       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
02956         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02957       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02958         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
02959           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02960                               Builder->getInt(CI->getValue()+1));
02961       }
02962       break;
02963     case ICmpInst::ICMP_SGE:
02964       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
02965       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
02966         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02967       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
02968         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02969       break;
02970     case ICmpInst::ICMP_SLE:
02971       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
02972       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
02973         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02974       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
02975         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02976       break;
02977     case ICmpInst::ICMP_UGE:
02978       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
02979       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
02980         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02981       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
02982         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02983       break;
02984     case ICmpInst::ICMP_ULE:
02985       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
02986       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
02987         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02988       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
02989         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02990       break;
02991     }
02992 
02993     // Turn a signed comparison into an unsigned one if both operands
02994     // are known to have the same sign.
02995     if (I.isSigned() &&
02996         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
02997          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
02998       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
02999   }
03000 
03001   // Test if the ICmpInst instruction is used exclusively by a select as
03002   // part of a minimum or maximum operation. If so, refrain from doing
03003   // any other folding. This helps out other analyses which understand
03004   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
03005   // and CodeGen. And in this case, at least one of the comparison
03006   // operands has at least one user besides the compare (the select),
03007   // which would often largely negate the benefit of folding anyway.
03008   if (I.hasOneUse())
03009     if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
03010       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
03011           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
03012         return nullptr;
03013 
03014   // See if we are doing a comparison between a constant and an instruction that
03015   // can be folded into the comparison.
03016   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
03017     // Since the RHS is a ConstantInt (CI), if the left hand side is an
03018     // instruction, see if that instruction also has constants so that the
03019     // instruction can be folded into the icmp
03020     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
03021       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
03022         return Res;
03023   }
03024 
03025   // Handle icmp with constant (but not simple integer constant) RHS
03026   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
03027     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
03028       switch (LHSI->getOpcode()) {
03029       case Instruction::GetElementPtr:
03030           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
03031         if (RHSC->isNullValue() &&
03032             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
03033           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
03034                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
03035         break;
03036       case Instruction::PHI:
03037         // Only fold icmp into the PHI if the phi and icmp are in the same
03038         // block.  If in the same block, we're encouraging jump threading.  If
03039         // not, we are just pessimizing the code by making an i1 phi.
03040         if (LHSI->getParent() == I.getParent())
03041           if (Instruction *NV = FoldOpIntoPhi(I))
03042             return NV;
03043         break;
03044       case Instruction::Select: {
03045         // If either operand of the select is a constant, we can fold the
03046         // comparison into the select arms, which will cause one to be
03047         // constant folded and the select turned into a bitwise or.
03048         Value *Op1 = nullptr, *Op2 = nullptr;
03049         ConstantInt *CI = 0;
03050         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
03051           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
03052           CI = dyn_cast<ConstantInt>(Op1);
03053         }
03054         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
03055           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
03056           CI = dyn_cast<ConstantInt>(Op2);
03057         }
03058 
03059         // We only want to perform this transformation if it will not lead to
03060         // additional code. This is true if either both sides of the select
03061         // fold to a constant (in which case the icmp is replaced with a select
03062         // which will usually simplify) or this is the only user of the
03063         // select (in which case we are trading a select+icmp for a simpler
03064         // select+icmp) or all uses of the select can be replaced based on
03065         // dominance information ("Global cases").
03066         bool Transform = false;
03067         if (Op1 && Op2)
03068           Transform = true;
03069         else if (Op1 || Op2) {
03070           // Local case
03071           if (LHSI->hasOneUse())
03072             Transform = true;
03073           // Global cases
03074           else if (CI && !CI->isZero())
03075             // When Op1 is constant try replacing select with second operand.
03076             // Otherwise Op2 is constant and try replacing select with first
03077             // operand.
03078             Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
03079                                                   Op1 ? 2 : 1);
03080         }
03081         if (Transform) {
03082           if (!Op1)
03083             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
03084                                       RHSC, I.getName());
03085           if (!Op2)
03086             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
03087                                       RHSC, I.getName());
03088           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
03089         }
03090         break;
03091       }
03092       case Instruction::IntToPtr:
03093         // icmp pred inttoptr(X), null -> icmp pred X, 0
03094         if (RHSC->isNullValue() && DL &&
03095             DL->getIntPtrType(RHSC->getType()) ==
03096                LHSI->getOperand(0)->getType())
03097           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
03098                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
03099         break;
03100 
03101       case Instruction::Load:
03102         // Try to optimize things like "A[i] > 4" to index computations.
03103         if (GetElementPtrInst *GEP =
03104               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
03105           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
03106             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
03107                 !cast<LoadInst>(LHSI)->isVolatile())
03108               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
03109                 return Res;
03110         }
03111         break;
03112       }
03113   }
03114 
03115   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
03116   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
03117     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
03118       return NI;
03119   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
03120     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
03121                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
03122       return NI;
03123 
03124   // Test to see if the operands of the icmp are casted versions of other
03125   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
03126   // now.
03127   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
03128     if (Op0->getType()->isPointerTy() &&
03129         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
03130       // We keep moving the cast from the left operand over to the right
03131       // operand, where it can often be eliminated completely.
03132       Op0 = CI->getOperand(0);
03133 
03134       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
03135       // so eliminate it as well.
03136       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
03137         Op1 = CI2->getOperand(0);
03138 
03139       // If Op1 is a constant, we can fold the cast into the constant.
03140       if (Op0->getType() != Op1->getType()) {
03141         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
03142           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
03143         } else {
03144           // Otherwise, cast the RHS right before the icmp
03145           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
03146         }
03147       }
03148       return new ICmpInst(I.getPredicate(), Op0, Op1);
03149     }
03150   }
03151 
03152   if (isa<CastInst>(Op0)) {
03153     // Handle the special case of: icmp (cast bool to X), <cst>
03154     // This comes up when you have code like
03155     //   int X = A < B;
03156     //   if (X) ...
03157     // For generality, we handle any zero-extension of any operand comparison
03158     // with a constant or another cast from the same type.
03159     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
03160       if (Instruction *R = visitICmpInstWithCastAndCast(I))
03161         return R;
03162   }
03163 
03164   // Special logic for binary operators.
03165   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
03166   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
03167   if (BO0 || BO1) {
03168     CmpInst::Predicate Pred = I.getPredicate();
03169     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
03170     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
03171       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
03172         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
03173         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
03174     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
03175       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
03176         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
03177         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
03178 
03179     // Analyze the case when either Op0 or Op1 is an add instruction.
03180     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
03181     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
03182     if (BO0 && BO0->getOpcode() == Instruction::Add)
03183       A = BO0->getOperand(0), B = BO0->getOperand(1);
03184     if (BO1 && BO1->getOpcode() == Instruction::Add)
03185       C = BO1->getOperand(0), D = BO1->getOperand(1);
03186 
03187     // icmp (X+cst) < 0 --> X < -cst
03188     if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
03189       if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
03190         if (!RHSC->isMinValue(/*isSigned=*/true))
03191           return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
03192 
03193     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
03194     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
03195       return new ICmpInst(Pred, A == Op1 ? B : A,
03196                           Constant::getNullValue(Op1->getType()));
03197 
03198     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
03199     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
03200       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
03201                           C == Op0 ? D : C);
03202 
03203     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
03204     if (A && C && (A == C || A == D || B == C || B == D) &&
03205         NoOp0WrapProblem && NoOp1WrapProblem &&
03206         // Try not to increase register pressure.
03207         BO0->hasOneUse() && BO1->hasOneUse()) {
03208       // Determine Y and Z in the form icmp (X+Y), (X+Z).
03209       Value *Y, *Z;
03210       if (A == C) {
03211         // C + B == C + D  ->  B == D
03212         Y = B;
03213         Z = D;
03214       } else if (A == D) {
03215         // D + B == C + D  ->  B == C
03216         Y = B;
03217         Z = C;
03218       } else if (B == C) {
03219         // A + C == C + D  ->  A == D
03220         Y = A;
03221         Z = D;
03222       } else {
03223         assert(B == D);
03224         // A + D == C + D  ->  A == C
03225         Y = A;
03226         Z = C;
03227       }
03228       return new ICmpInst(Pred, Y, Z);
03229     }
03230 
03231     // icmp slt (X + -1), Y -> icmp sle X, Y
03232     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
03233         match(B, m_AllOnes()))
03234       return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
03235 
03236     // icmp sge (X + -1), Y -> icmp sgt X, Y
03237     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
03238         match(B, m_AllOnes()))
03239       return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
03240 
03241     // icmp sle (X + 1), Y -> icmp slt X, Y
03242     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
03243         match(B, m_One()))
03244       return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
03245 
03246     // icmp sgt (X + 1), Y -> icmp sge X, Y
03247     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
03248         match(B, m_One()))
03249       return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
03250 
03251     // if C1 has greater magnitude than C2:
03252     //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
03253     //  s.t. C3 = C1 - C2
03254     //
03255     // if C2 has greater magnitude than C1:
03256     //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
03257     //  s.t. C3 = C2 - C1
03258     if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
03259         (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
03260       if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
03261         if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
03262           const APInt &AP1 = C1->getValue();
03263           const APInt &AP2 = C2->getValue();
03264           if (AP1.isNegative() == AP2.isNegative()) {
03265             APInt AP1Abs = C1->getValue().abs();
03266             APInt AP2Abs = C2->getValue().abs();
03267             if (AP1Abs.uge(AP2Abs)) {
03268               ConstantInt *C3 = Builder->getInt(AP1 - AP2);
03269               Value *NewAdd = Builder->CreateNSWAdd(A, C3);
03270               return new ICmpInst(Pred, NewAdd, C);
03271             } else {
03272               ConstantInt *C3 = Builder->getInt(AP2 - AP1);
03273               Value *NewAdd = Builder->CreateNSWAdd(C, C3);
03274               return new ICmpInst(Pred, A, NewAdd);
03275             }
03276           }
03277         }
03278 
03279 
03280     // Analyze the case when either Op0 or Op1 is a sub instruction.
03281     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
03282     A = nullptr; B = nullptr; C = nullptr; D = nullptr;
03283     if (BO0 && BO0->getOpcode() == Instruction::Sub)
03284       A = BO0->getOperand(0), B = BO0->getOperand(1);
03285     if (BO1 && BO1->getOpcode() == Instruction::Sub)
03286       C = BO1->getOperand(0), D = BO1->getOperand(1);
03287 
03288     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
03289     if (A == Op1 && NoOp0WrapProblem)
03290       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
03291 
03292     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
03293     if (C == Op0 && NoOp1WrapProblem)
03294       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
03295 
03296     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
03297     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
03298         // Try not to increase register pressure.
03299         BO0->hasOneUse() && BO1->hasOneUse())
03300       return new ICmpInst(Pred, A, C);
03301 
03302     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
03303     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
03304         // Try not to increase register pressure.
03305         BO0->hasOneUse() && BO1->hasOneUse())
03306       return new ICmpInst(Pred, D, B);
03307 
03308     // icmp (0-X) < cst --> x > -cst
03309     if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
03310       Value *X;
03311       if (match(BO0, m_Neg(m_Value(X))))
03312         if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
03313           if (!RHSC->isMinValue(/*isSigned=*/true))
03314             return new ICmpInst(I.getSwappedPredicate(), X,
03315                                 ConstantExpr::getNeg(RHSC));
03316     }
03317 
03318     BinaryOperator *SRem = nullptr;
03319     // icmp (srem X, Y), Y
03320     if (BO0 && BO0->getOpcode() == Instruction::SRem &&
03321         Op1 == BO0->getOperand(1))
03322       SRem = BO0;
03323     // icmp Y, (srem X, Y)
03324     else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
03325              Op0 == BO1->getOperand(1))
03326       SRem = BO1;
03327     if (SRem) {
03328       // We don't check hasOneUse to avoid increasing register pressure because
03329       // the value we use is the same value this instruction was already using.
03330       switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
03331         default: break;
03332         case ICmpInst::ICMP_EQ:
03333           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
03334         case ICmpInst::ICMP_NE:
03335           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
03336         case ICmpInst::ICMP_SGT:
03337         case ICmpInst::ICMP_SGE:
03338           return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
03339                               Constant::getAllOnesValue(SRem->getType()));
03340         case ICmpInst::ICMP_SLT:
03341         case ICmpInst::ICMP_SLE:
03342           return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
03343                               Constant::getNullValue(SRem->getType()));
03344       }
03345     }
03346 
03347     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
03348         BO0->hasOneUse() && BO1->hasOneUse() &&
03349         BO0->getOperand(1) == BO1->getOperand(1)) {
03350       switch (BO0->getOpcode()) {
03351       default: break;
03352       case Instruction::Add:
03353       case Instruction::Sub:
03354       case Instruction::Xor:
03355         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
03356           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03357                               BO1->getOperand(0));
03358         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
03359         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
03360           if (CI->getValue().isSignBit()) {
03361             ICmpInst::Predicate Pred = I.isSigned()
03362                                            ? I.getUnsignedPredicate()
03363                                            : I.getSignedPredicate();
03364             return new ICmpInst(Pred, BO0->getOperand(0),
03365                                 BO1->getOperand(0));
03366           }
03367 
03368           if (CI->isMaxValue(true)) {
03369             ICmpInst::Predicate Pred = I.isSigned()
03370                                            ? I.getUnsignedPredicate()
03371                                            : I.getSignedPredicate();
03372             Pred = I.getSwappedPredicate(Pred);
03373             return new ICmpInst(Pred, BO0->getOperand(0),
03374                                 BO1->getOperand(0));
03375           }
03376         }
03377         break;
03378       case Instruction::Mul:
03379         if (!I.isEquality())
03380           break;
03381 
03382         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
03383           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
03384           // Mask = -1 >> count-trailing-zeros(Cst).
03385           if (!CI->isZero() && !CI->isOne()) {
03386             const APInt &AP = CI->getValue();
03387             ConstantInt *Mask = ConstantInt::get(I.getContext(),
03388                                     APInt::getLowBitsSet(AP.getBitWidth(),
03389                                                          AP.getBitWidth() -
03390                                                     AP.countTrailingZeros()));
03391             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
03392             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
03393             return new ICmpInst(I.getPredicate(), And1, And2);
03394           }
03395         }
03396         break;
03397       case Instruction::UDiv:
03398       case Instruction::LShr:
03399         if (I.isSigned())
03400           break;
03401         // fall-through
03402       case Instruction::SDiv:
03403       case Instruction::AShr:
03404         if (!BO0->isExact() || !BO1->isExact())
03405           break;
03406         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03407                             BO1->getOperand(0));
03408       case Instruction::Shl: {
03409         bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
03410         bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
03411         if (!NUW && !NSW)
03412           break;
03413         if (!NSW && I.isSigned())
03414           break;
03415         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03416                             BO1->getOperand(0));
03417       }
03418       }
03419     }
03420   }
03421 
03422   { Value *A, *B;
03423     // Transform (A & ~B) == 0 --> (A & B) != 0
03424     // and       (A & ~B) != 0 --> (A & B) == 0
03425     // if A is a power of 2.
03426     if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
03427         match(Op1, m_Zero()) &&
03428         isKnownToBeAPowerOfTwo(A, false, 0, AC, &I, DT) && I.isEquality())
03429       return new ICmpInst(I.getInversePredicate(),
03430                           Builder->CreateAnd(A, B),
03431                           Op1);
03432 
03433     // ~x < ~y --> y < x
03434     // ~x < cst --> ~cst < x
03435     if (match(Op0, m_Not(m_Value(A)))) {
03436       if (match(Op1, m_Not(m_Value(B))))
03437         return new ICmpInst(I.getPredicate(), B, A);
03438       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
03439         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
03440     }
03441 
03442     // (a+b) <u a  --> llvm.uadd.with.overflow.
03443     // (a+b) <u b  --> llvm.uadd.with.overflow.
03444     if (I.getPredicate() == ICmpInst::ICMP_ULT &&
03445         match(Op0, m_Add(m_Value(A), m_Value(B))) &&
03446         (Op1 == A || Op1 == B))
03447       if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
03448         return R;
03449 
03450     // a >u (a+b)  --> llvm.uadd.with.overflow.
03451     // b >u (a+b)  --> llvm.uadd.with.overflow.
03452     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
03453         match(Op1, m_Add(m_Value(A), m_Value(B))) &&
03454         (Op0 == A || Op0 == B))
03455       if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
03456         return R;
03457 
03458     // (zext a) * (zext b)  --> llvm.umul.with.overflow.
03459     if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
03460       if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
03461         return R;
03462     }
03463     if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
03464       if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
03465         return R;
03466     }
03467   }
03468 
03469   if (I.isEquality()) {
03470     Value *A, *B, *C, *D;
03471 
03472     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
03473       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
03474         Value *OtherVal = A == Op1 ? B : A;
03475         return new ICmpInst(I.getPredicate(), OtherVal,
03476                             Constant::getNullValue(A->getType()));
03477       }
03478 
03479       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
03480         // A^c1 == C^c2 --> A == C^(c1^c2)
03481         ConstantInt *C1, *C2;
03482         if (match(B, m_ConstantInt(C1)) &&
03483             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
03484           Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
03485           Value *Xor = Builder->CreateXor(C, NC);
03486           return new ICmpInst(I.getPredicate(), A, Xor);
03487         }
03488 
03489         // A^B == A^D -> B == D
03490         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
03491         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
03492         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
03493         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
03494       }
03495     }
03496 
03497     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
03498         (A == Op0 || B == Op0)) {
03499       // A == (A^B)  ->  B == 0
03500       Value *OtherVal = A == Op0 ? B : A;
03501       return new ICmpInst(I.getPredicate(), OtherVal,
03502                           Constant::getNullValue(A->getType()));
03503     }
03504 
03505     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
03506     if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
03507         match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
03508       Value *X = nullptr, *Y = nullptr, *Z = nullptr;
03509 
03510       if (A == C) {
03511         X = B; Y = D; Z = A;
03512       } else if (A == D) {
03513         X = B; Y = C; Z = A;
03514       } else if (B == C) {
03515         X = A; Y = D; Z = B;
03516       } else if (B == D) {
03517         X = A; Y = C; Z = B;
03518       }
03519 
03520       if (X) {   // Build (X^Y) & Z
03521         Op1 = Builder->CreateXor(X, Y);
03522         Op1 = Builder->CreateAnd(Op1, Z);
03523         I.setOperand(0, Op1);
03524         I.setOperand(1, Constant::getNullValue(Op1->getType()));
03525         return &I;
03526       }
03527     }
03528 
03529     // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
03530     // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
03531     ConstantInt *Cst1;
03532     if ((Op0->hasOneUse() &&
03533          match(Op0, m_ZExt(m_Value(A))) &&
03534          match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
03535         (Op1->hasOneUse() &&
03536          match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
03537          match(Op1, m_ZExt(m_Value(A))))) {
03538       APInt Pow2 = Cst1->getValue() + 1;
03539       if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
03540           Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
03541         return new ICmpInst(I.getPredicate(), A,
03542                             Builder->CreateTrunc(B, A->getType()));
03543     }
03544 
03545     // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
03546     // For lshr and ashr pairs.
03547     if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
03548          match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
03549         (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
03550          match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
03551       unsigned TypeBits = Cst1->getBitWidth();
03552       unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
03553       if (ShAmt < TypeBits && ShAmt != 0) {
03554         ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
03555                                        ? ICmpInst::ICMP_UGE
03556                                        : ICmpInst::ICMP_ULT;
03557         Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
03558         APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
03559         return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
03560       }
03561     }
03562 
03563     // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
03564     // "icmp (and X, mask), cst"
03565     uint64_t ShAmt = 0;
03566     if (Op0->hasOneUse() &&
03567         match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
03568                                            m_ConstantInt(ShAmt))))) &&
03569         match(Op1, m_ConstantInt(Cst1)) &&
03570         // Only do this when A has multiple uses.  This is most important to do
03571         // when it exposes other optimizations.
03572         !A->hasOneUse()) {
03573       unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
03574 
03575       if (ShAmt < ASize) {
03576         APInt MaskV =
03577           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
03578         MaskV <<= ShAmt;
03579 
03580         APInt CmpV = Cst1->getValue().zext(ASize);
03581         CmpV <<= ShAmt;
03582 
03583         Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
03584         return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
03585       }
03586     }
03587   }
03588 
03589   // The 'cmpxchg' instruction returns an aggregate containing the old value and
03590   // an i1 which indicates whether or not we successfully did the swap.
03591   //
03592   // Replace comparisons between the old value and the expected value with the
03593   // indicator that 'cmpxchg' returns.
03594   //
03595   // N.B.  This transform is only valid when the 'cmpxchg' is not permitted to
03596   // spuriously fail.  In those cases, the old value may equal the expected
03597   // value but it is possible for the swap to not occur.
03598   if (I.getPredicate() == ICmpInst::ICMP_EQ)
03599     if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
03600       if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
03601         if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
03602             !ACXI->isWeak())
03603           return ExtractValueInst::Create(ACXI, 1);
03604 
03605   {
03606     Value *X; ConstantInt *Cst;
03607     // icmp X+Cst, X
03608     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
03609       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
03610 
03611     // icmp X, X+Cst
03612     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
03613       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
03614   }
03615   return Changed ? &I : nullptr;
03616 }
03617 
03618 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
03619 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
03620                                                 Instruction *LHSI,
03621                                                 Constant *RHSC) {
03622   if (!isa<ConstantFP>(RHSC)) return nullptr;
03623   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
03624 
03625   // Get the width of the mantissa.  We don't want to hack on conversions that
03626   // might lose information from the integer, e.g. "i64 -> float"
03627   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
03628   if (MantissaWidth == -1) return nullptr;  // Unknown.
03629 
03630   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
03631 
03632   // Check to see that the input is converted from an integer type that is small
03633   // enough that preserves all bits.  TODO: check here for "known" sign bits.
03634   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
03635   unsigned InputSize = IntTy->getScalarSizeInBits();
03636 
03637   // If this is a uitofp instruction, we need an extra bit to hold the sign.
03638   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
03639   if (LHSUnsigned)
03640     ++InputSize;
03641 
03642   if (I.isEquality()) {
03643     FCmpInst::Predicate P = I.getPredicate();
03644     bool IsExact = false;
03645     APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
03646     RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
03647 
03648     // If the floating point constant isn't an integer value, we know if we will
03649     // ever compare equal / not equal to it.
03650     if (!IsExact) {
03651       // TODO: Can never be -0.0 and other non-representable values
03652       APFloat RHSRoundInt(RHS);
03653       RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
03654       if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
03655         if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
03656           return ReplaceInstUsesWith(I, Builder->getFalse());
03657 
03658         assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
03659         return ReplaceInstUsesWith(I, Builder->getTrue());
03660       }
03661     }
03662 
03663     // TODO: If the constant is exactly representable, is it always OK to do
03664     // equality compares as integer?
03665   }
03666 
03667   // Comparisons with zero are a special case where we know we won't lose
03668   // information.
03669   bool IsCmpZero = RHS.isPosZero();
03670 
03671   // If the conversion would lose info, don't hack on this.
03672   if ((int)InputSize > MantissaWidth && !IsCmpZero)
03673     return nullptr;
03674 
03675   // Otherwise, we can potentially simplify the comparison.  We know that it
03676   // will always come through as an integer value and we know the constant is
03677   // not a NAN (it would have been previously simplified).
03678   assert(!RHS.isNaN() && "NaN comparison not already folded!");
03679 
03680   ICmpInst::Predicate Pred;
03681   switch (I.getPredicate()) {
03682   default: llvm_unreachable("Unexpected predicate!");
03683   case FCmpInst::FCMP_UEQ:
03684   case FCmpInst::FCMP_OEQ:
03685     Pred = ICmpInst::ICMP_EQ;
03686     break;
03687   case FCmpInst::FCMP_UGT:
03688   case FCmpInst::FCMP_OGT:
03689     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
03690     break;
03691   case FCmpInst::FCMP_UGE:
03692   case FCmpInst::FCMP_OGE:
03693     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
03694     break;
03695   case FCmpInst::FCMP_ULT:
03696   case FCmpInst::FCMP_OLT:
03697     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
03698     break;
03699   case FCmpInst::FCMP_ULE:
03700   case FCmpInst::FCMP_OLE:
03701     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
03702     break;
03703   case FCmpInst::FCMP_UNE:
03704   case FCmpInst::FCMP_ONE:
03705     Pred = ICmpInst::ICMP_NE;
03706     break;
03707   case FCmpInst::FCMP_ORD:
03708     return ReplaceInstUsesWith(I, Builder->getTrue());
03709   case FCmpInst::FCMP_UNO:
03710     return ReplaceInstUsesWith(I, Builder->getFalse());
03711   }
03712 
03713   // Now we know that the APFloat is a normal number, zero or inf.
03714 
03715   // See if the FP constant is too large for the integer.  For example,
03716   // comparing an i8 to 300.0.
03717   unsigned IntWidth = IntTy->getScalarSizeInBits();
03718 
03719   if (!LHSUnsigned) {
03720     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
03721     // and large values.
03722     APFloat SMax(RHS.getSemantics());
03723     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
03724                           APFloat::rmNearestTiesToEven);
03725     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
03726       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
03727           Pred == ICmpInst::ICMP_SLE)
03728         return ReplaceInstUsesWith(I, Builder->getTrue());
03729       return ReplaceInstUsesWith(I, Builder->getFalse());
03730     }
03731   } else {
03732     // If the RHS value is > UnsignedMax, fold the comparison. This handles
03733     // +INF and large values.
03734     APFloat UMax(RHS.getSemantics());
03735     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
03736                           APFloat::rmNearestTiesToEven);
03737     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
03738       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
03739           Pred == ICmpInst::ICMP_ULE)
03740         return ReplaceInstUsesWith(I, Builder->getTrue());
03741       return ReplaceInstUsesWith(I, Builder->getFalse());
03742     }
03743   }
03744 
03745   if (!LHSUnsigned) {
03746     // See if the RHS value is < SignedMin.
03747     APFloat SMin(RHS.getSemantics());
03748     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
03749                           APFloat::rmNearestTiesToEven);
03750     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
03751       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
03752           Pred == ICmpInst::ICMP_SGE)
03753         return ReplaceInstUsesWith(I, Builder->getTrue());
03754       return ReplaceInstUsesWith(I, Builder->getFalse());
03755     }
03756   } else {
03757     // See if the RHS value is < UnsignedMin.
03758     APFloat SMin(RHS.getSemantics());
03759     SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
03760                           APFloat::rmNearestTiesToEven);
03761     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
03762       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
03763           Pred == ICmpInst::ICMP_UGE)
03764         return ReplaceInstUsesWith(I, Builder->getTrue());
03765       return ReplaceInstUsesWith(I, Builder->getFalse());
03766     }
03767   }
03768 
03769   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
03770   // [0, UMAX], but it may still be fractional.  See if it is fractional by
03771   // casting the FP value to the integer value and back, checking for equality.
03772   // Don't do this for zero, because -0.0 is not fractional.
03773   Constant *RHSInt = LHSUnsigned
03774     ? ConstantExpr::getFPToUI(RHSC, IntTy)
03775     : ConstantExpr::getFPToSI(RHSC, IntTy);
03776   if (!RHS.isZero()) {
03777     bool Equal = LHSUnsigned
03778       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
03779       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
03780     if (!Equal) {
03781       // If we had a comparison against a fractional value, we have to adjust
03782       // the compare predicate and sometimes the value.  RHSC is rounded towards
03783       // zero at this point.
03784       switch (Pred) {
03785       default: llvm_unreachable("Unexpected integer comparison!");
03786       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
03787         return ReplaceInstUsesWith(I, Builder->getTrue());
03788       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
03789         return ReplaceInstUsesWith(I, Builder->getFalse());
03790       case ICmpInst::ICMP_ULE:
03791         // (float)int <= 4.4   --> int <= 4
03792         // (float)int <= -4.4  --> false
03793         if (RHS.isNegative())
03794           return ReplaceInstUsesWith(I, Builder->getFalse());
03795         break;
03796       case ICmpInst::ICMP_SLE:
03797         // (float)int <= 4.4   --> int <= 4
03798         // (float)int <= -4.4  --> int < -4
03799         if (RHS.isNegative())
03800           Pred = ICmpInst::ICMP_SLT;
03801         break;
03802       case ICmpInst::ICMP_ULT:
03803         // (float)int < -4.4   --> false
03804         // (float)int < 4.4    --> int <= 4
03805         if (RHS.isNegative())
03806           return ReplaceInstUsesWith(I, Builder->getFalse());
03807         Pred = ICmpInst::ICMP_ULE;
03808         break;
03809       case ICmpInst::ICMP_SLT:
03810         // (float)int < -4.4   --> int < -4
03811         // (float)int < 4.4    --> int <= 4
03812         if (!RHS.isNegative())
03813           Pred = ICmpInst::ICMP_SLE;
03814         break;
03815       case ICmpInst::ICMP_UGT:
03816         // (float)int > 4.4    --> int > 4
03817         // (float)int > -4.4   --> true
03818         if (RHS.isNegative())
03819           return ReplaceInstUsesWith(I, Builder->getTrue());
03820         break;
03821       case ICmpInst::ICMP_SGT:
03822         // (float)int > 4.4    --> int > 4
03823         // (float)int > -4.4   --> int >= -4
03824         if (RHS.isNegative())
03825           Pred = ICmpInst::ICMP_SGE;
03826         break;
03827       case ICmpInst::ICMP_UGE:
03828         // (float)int >= -4.4   --> true
03829         // (float)int >= 4.4    --> int > 4
03830         if (RHS.isNegative())
03831           return ReplaceInstUsesWith(I, Builder->getTrue());
03832         Pred = ICmpInst::ICMP_UGT;
03833         break;
03834       case ICmpInst::ICMP_SGE:
03835         // (float)int >= -4.4   --> int >= -4
03836         // (float)int >= 4.4    --> int > 4
03837         if (!RHS.isNegative())
03838           Pred = ICmpInst::ICMP_SGT;
03839         break;
03840       }
03841     }
03842   }
03843 
03844   // Lower this FP comparison into an appropriate integer version of the
03845   // comparison.
03846   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
03847 }
03848 
03849 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
03850   bool Changed = false;
03851 
03852   /// Orders the operands of the compare so that they are listed from most
03853   /// complex to least complex.  This puts constants before unary operators,
03854   /// before binary operators.
03855   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
03856     I.swapOperands();
03857     Changed = true;
03858   }
03859 
03860   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03861 
03862   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC))
03863     return ReplaceInstUsesWith(I, V);
03864 
03865   // Simplify 'fcmp pred X, X'
03866   if (Op0 == Op1) {
03867     switch (I.getPredicate()) {
03868     default: llvm_unreachable("Unknown predicate!");
03869     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
03870     case FCmpInst::FCMP_ULT:    // True if unordered or less than
03871     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
03872     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
03873       // Canonicalize these to be 'fcmp uno %X, 0.0'.
03874       I.setPredicate(FCmpInst::FCMP_UNO);
03875       I.setOperand(1, Constant::getNullValue(Op0->getType()));
03876       return &I;
03877 
03878     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
03879     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
03880     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
03881     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
03882       // Canonicalize these to be 'fcmp ord %X, 0.0'.
03883       I.setPredicate(FCmpInst::FCMP_ORD);
03884       I.setOperand(1, Constant::getNullValue(Op0->getType()));
03885       return &I;
03886     }
03887   }
03888 
03889   // Handle fcmp with constant RHS
03890   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
03891     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
03892       switch (LHSI->getOpcode()) {
03893       case Instruction::FPExt: {
03894         // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
03895         FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
03896         ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
03897         if (!RHSF)
03898           break;
03899 
03900         const fltSemantics *Sem;
03901         // FIXME: This shouldn't be here.
03902         if (LHSExt->getSrcTy()->isHalfTy())
03903           Sem = &APFloat::IEEEhalf;
03904         else if (LHSExt->getSrcTy()->isFloatTy())
03905           Sem = &APFloat::IEEEsingle;
03906         else if (LHSExt->getSrcTy()->isDoubleTy())
03907           Sem = &APFloat::IEEEdouble;
03908         else if (LHSExt->getSrcTy()->isFP128Ty())
03909           Sem = &APFloat::IEEEquad;
03910         else if (LHSExt->getSrcTy()->isX86_FP80Ty())
03911           Sem = &APFloat::x87DoubleExtended;
03912         else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
03913           Sem = &APFloat::PPCDoubleDouble;
03914         else
03915           break;
03916 
03917         bool Lossy;
03918         APFloat F = RHSF->getValueAPF();
03919         F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
03920 
03921         // Avoid lossy conversions and denormals. Zero is a special case
03922         // that's OK to convert.
03923         APFloat Fabs = F;
03924         Fabs.clearSign();
03925         if (!Lossy &&
03926             ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
03927                  APFloat::cmpLessThan) || Fabs.isZero()))
03928 
03929           return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
03930                               ConstantFP::get(RHSC->getContext(), F));
03931         break;
03932       }
03933       case Instruction::PHI:
03934         // Only fold fcmp into the PHI if the phi and fcmp are in the same
03935         // block.  If in the same block, we're encouraging jump threading.  If
03936         // not, we are just pessimizing the code by making an i1 phi.
03937         if (LHSI->getParent() == I.getParent())
03938           if (Instruction *NV = FoldOpIntoPhi(I))
03939             return NV;
03940         break;
03941       case Instruction::SIToFP:
03942       case Instruction::UIToFP:
03943         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
03944           return NV;
03945         break;
03946       case Instruction::FSub: {
03947         // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
03948         Value *Op;
03949         if (match(LHSI, m_FNeg(m_Value(Op))))
03950           return new FCmpInst(I.getSwappedPredicate(), Op,
03951                               ConstantExpr::getFNeg(RHSC));
03952         break;
03953       }
03954       case Instruction::Load:
03955         if (GetElementPtrInst *GEP =
03956             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
03957           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
03958             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
03959                 !cast<LoadInst>(LHSI)->isVolatile())
03960               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
03961                 return Res;
03962         }
03963         break;
03964       case Instruction::Call: {
03965         if (!RHSC->isNullValue())
03966           break;
03967 
03968         CallInst *CI = cast<CallInst>(LHSI);
03969         const Function *F = CI->getCalledFunction();
03970         if (!F)
03971           break;
03972 
03973         // Various optimization for fabs compared with zero.
03974         LibFunc::Func Func;
03975         if (F->getIntrinsicID() == Intrinsic::fabs ||
03976             (TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
03977              (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
03978               Func == LibFunc::fabsl))) {
03979           switch (I.getPredicate()) {
03980           default:
03981             break;
03982             // fabs(x) < 0 --> false
03983           case FCmpInst::FCMP_OLT:
03984             return ReplaceInstUsesWith(I, Builder->getFalse());
03985             // fabs(x) > 0 --> x != 0
03986           case FCmpInst::FCMP_OGT:
03987             return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
03988             // fabs(x) <= 0 --> x == 0
03989           case FCmpInst::FCMP_OLE:
03990             return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
03991             // fabs(x) >= 0 --> !isnan(x)
03992           case FCmpInst::FCMP_OGE:
03993             return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
03994             // fabs(x) == 0 --> x == 0
03995             // fabs(x) != 0 --> x != 0
03996           case FCmpInst::FCMP_OEQ:
03997           case FCmpInst::FCMP_UEQ:
03998           case FCmpInst::FCMP_ONE:
03999           case FCmpInst::FCMP_UNE:
04000             return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
04001           }
04002         }
04003       }
04004       }
04005   }
04006 
04007   // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
04008   Value *X, *Y;
04009   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
04010     return new FCmpInst(I.getSwappedPredicate(), X, Y);
04011 
04012   // fcmp (fpext x), (fpext y) -> fcmp x, y
04013   if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
04014     if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
04015       if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
04016         return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
04017                             RHSExt->getOperand(0));
04018 
04019   return Changed ? &I : nullptr;
04020 }