LLVM API Documentation

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