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