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