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