InstCombineCompares.cpp revision 202375
1202375Srdivacky//===- InstCombineCompares.cpp --------------------------------------------===// 2202375Srdivacky// 3202375Srdivacky// The LLVM Compiler Infrastructure 4202375Srdivacky// 5202375Srdivacky// This file is distributed under the University of Illinois Open Source 6202375Srdivacky// License. See LICENSE.TXT for details. 7202375Srdivacky// 8202375Srdivacky//===----------------------------------------------------------------------===// 9202375Srdivacky// 10202375Srdivacky// This file implements the visitICmp and visitFCmp functions. 11202375Srdivacky// 12202375Srdivacky//===----------------------------------------------------------------------===// 13202375Srdivacky 14202375Srdivacky#include "InstCombine.h" 15202375Srdivacky#include "llvm/IntrinsicInst.h" 16202375Srdivacky#include "llvm/Analysis/InstructionSimplify.h" 17202375Srdivacky#include "llvm/Analysis/MemoryBuiltins.h" 18202375Srdivacky#include "llvm/Target/TargetData.h" 19202375Srdivacky#include "llvm/Support/ConstantRange.h" 20202375Srdivacky#include "llvm/Support/GetElementPtrTypeIterator.h" 21202375Srdivacky#include "llvm/Support/PatternMatch.h" 22202375Srdivackyusing namespace llvm; 23202375Srdivackyusing namespace PatternMatch; 24202375Srdivacky 25202375Srdivacky/// AddOne - Add one to a ConstantInt 26202375Srdivackystatic Constant *AddOne(Constant *C) { 27202375Srdivacky return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1)); 28202375Srdivacky} 29202375Srdivacky/// SubOne - Subtract one from a ConstantInt 30202375Srdivackystatic Constant *SubOne(ConstantInt *C) { 31202375Srdivacky return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1)); 32202375Srdivacky} 33202375Srdivacky 34202375Srdivackystatic ConstantInt *ExtractElement(Constant *V, Constant *Idx) { 35202375Srdivacky return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx)); 36202375Srdivacky} 37202375Srdivacky 38202375Srdivackystatic bool HasAddOverflow(ConstantInt *Result, 39202375Srdivacky ConstantInt *In1, ConstantInt *In2, 40202375Srdivacky bool IsSigned) { 41202375Srdivacky if (IsSigned) 42202375Srdivacky if (In2->getValue().isNegative()) 43202375Srdivacky return Result->getValue().sgt(In1->getValue()); 44202375Srdivacky else 45202375Srdivacky return Result->getValue().slt(In1->getValue()); 46202375Srdivacky else 47202375Srdivacky return Result->getValue().ult(In1->getValue()); 48202375Srdivacky} 49202375Srdivacky 50202375Srdivacky/// AddWithOverflow - Compute Result = In1+In2, returning true if the result 51202375Srdivacky/// overflowed for this type. 52202375Srdivackystatic bool AddWithOverflow(Constant *&Result, Constant *In1, 53202375Srdivacky Constant *In2, bool IsSigned = false) { 54202375Srdivacky Result = ConstantExpr::getAdd(In1, In2); 55202375Srdivacky 56202375Srdivacky if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 57202375Srdivacky for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 58202375Srdivacky Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 59202375Srdivacky if (HasAddOverflow(ExtractElement(Result, Idx), 60202375Srdivacky ExtractElement(In1, Idx), 61202375Srdivacky ExtractElement(In2, Idx), 62202375Srdivacky IsSigned)) 63202375Srdivacky return true; 64202375Srdivacky } 65202375Srdivacky return false; 66202375Srdivacky } 67202375Srdivacky 68202375Srdivacky return HasAddOverflow(cast<ConstantInt>(Result), 69202375Srdivacky cast<ConstantInt>(In1), cast<ConstantInt>(In2), 70202375Srdivacky IsSigned); 71202375Srdivacky} 72202375Srdivacky 73202375Srdivackystatic bool HasSubOverflow(ConstantInt *Result, 74202375Srdivacky ConstantInt *In1, ConstantInt *In2, 75202375Srdivacky bool IsSigned) { 76202375Srdivacky if (IsSigned) 77202375Srdivacky if (In2->getValue().isNegative()) 78202375Srdivacky return Result->getValue().slt(In1->getValue()); 79202375Srdivacky else 80202375Srdivacky return Result->getValue().sgt(In1->getValue()); 81202375Srdivacky else 82202375Srdivacky return Result->getValue().ugt(In1->getValue()); 83202375Srdivacky} 84202375Srdivacky 85202375Srdivacky/// SubWithOverflow - Compute Result = In1-In2, returning true if the result 86202375Srdivacky/// overflowed for this type. 87202375Srdivackystatic bool SubWithOverflow(Constant *&Result, Constant *In1, 88202375Srdivacky Constant *In2, bool IsSigned = false) { 89202375Srdivacky Result = ConstantExpr::getSub(In1, In2); 90202375Srdivacky 91202375Srdivacky if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 92202375Srdivacky for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 93202375Srdivacky Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 94202375Srdivacky if (HasSubOverflow(ExtractElement(Result, Idx), 95202375Srdivacky ExtractElement(In1, Idx), 96202375Srdivacky ExtractElement(In2, Idx), 97202375Srdivacky IsSigned)) 98202375Srdivacky return true; 99202375Srdivacky } 100202375Srdivacky return false; 101202375Srdivacky } 102202375Srdivacky 103202375Srdivacky return HasSubOverflow(cast<ConstantInt>(Result), 104202375Srdivacky cast<ConstantInt>(In1), cast<ConstantInt>(In2), 105202375Srdivacky IsSigned); 106202375Srdivacky} 107202375Srdivacky 108202375Srdivacky/// isSignBitCheck - Given an exploded icmp instruction, return true if the 109202375Srdivacky/// comparison only checks the sign bit. If it only checks the sign bit, set 110202375Srdivacky/// TrueIfSigned if the result of the comparison is true when the input value is 111202375Srdivacky/// signed. 112202375Srdivackystatic bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS, 113202375Srdivacky bool &TrueIfSigned) { 114202375Srdivacky switch (pred) { 115202375Srdivacky case ICmpInst::ICMP_SLT: // True if LHS s< 0 116202375Srdivacky TrueIfSigned = true; 117202375Srdivacky return RHS->isZero(); 118202375Srdivacky case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 119202375Srdivacky TrueIfSigned = true; 120202375Srdivacky return RHS->isAllOnesValue(); 121202375Srdivacky case ICmpInst::ICMP_SGT: // True if LHS s> -1 122202375Srdivacky TrueIfSigned = false; 123202375Srdivacky return RHS->isAllOnesValue(); 124202375Srdivacky case ICmpInst::ICMP_UGT: 125202375Srdivacky // True if LHS u> RHS and RHS == high-bit-mask - 1 126202375Srdivacky TrueIfSigned = true; 127202375Srdivacky return RHS->getValue() == 128202375Srdivacky APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits()); 129202375Srdivacky case ICmpInst::ICMP_UGE: 130202375Srdivacky // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) 131202375Srdivacky TrueIfSigned = true; 132202375Srdivacky return RHS->getValue().isSignBit(); 133202375Srdivacky default: 134202375Srdivacky return false; 135202375Srdivacky } 136202375Srdivacky} 137202375Srdivacky 138202375Srdivacky// isHighOnes - Return true if the constant is of the form 1+0+. 139202375Srdivacky// This is the same as lowones(~X). 140202375Srdivackystatic bool isHighOnes(const ConstantInt *CI) { 141202375Srdivacky return (~CI->getValue() + 1).isPowerOf2(); 142202375Srdivacky} 143202375Srdivacky 144202375Srdivacky/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 145202375Srdivacky/// set of known zero and one bits, compute the maximum and minimum values that 146202375Srdivacky/// could have the specified known zero and known one bits, returning them in 147202375Srdivacky/// min/max. 148202375Srdivackystatic void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero, 149202375Srdivacky const APInt& KnownOne, 150202375Srdivacky APInt& Min, APInt& Max) { 151202375Srdivacky assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && 152202375Srdivacky KnownZero.getBitWidth() == Min.getBitWidth() && 153202375Srdivacky KnownZero.getBitWidth() == Max.getBitWidth() && 154202375Srdivacky "KnownZero, KnownOne and Min, Max must have equal bitwidth."); 155202375Srdivacky APInt UnknownBits = ~(KnownZero|KnownOne); 156202375Srdivacky 157202375Srdivacky // The minimum value is when all unknown bits are zeros, EXCEPT for the sign 158202375Srdivacky // bit if it is unknown. 159202375Srdivacky Min = KnownOne; 160202375Srdivacky Max = KnownOne|UnknownBits; 161202375Srdivacky 162202375Srdivacky if (UnknownBits.isNegative()) { // Sign bit is unknown 163202375Srdivacky Min.set(Min.getBitWidth()-1); 164202375Srdivacky Max.clear(Max.getBitWidth()-1); 165202375Srdivacky } 166202375Srdivacky} 167202375Srdivacky 168202375Srdivacky// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and 169202375Srdivacky// a set of known zero and one bits, compute the maximum and minimum values that 170202375Srdivacky// could have the specified known zero and known one bits, returning them in 171202375Srdivacky// min/max. 172202375Srdivackystatic void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero, 173202375Srdivacky const APInt &KnownOne, 174202375Srdivacky APInt &Min, APInt &Max) { 175202375Srdivacky assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && 176202375Srdivacky KnownZero.getBitWidth() == Min.getBitWidth() && 177202375Srdivacky KnownZero.getBitWidth() == Max.getBitWidth() && 178202375Srdivacky "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); 179202375Srdivacky APInt UnknownBits = ~(KnownZero|KnownOne); 180202375Srdivacky 181202375Srdivacky // The minimum value is when the unknown bits are all zeros. 182202375Srdivacky Min = KnownOne; 183202375Srdivacky // The maximum value is when the unknown bits are all ones. 184202375Srdivacky Max = KnownOne|UnknownBits; 185202375Srdivacky} 186202375Srdivacky 187202375Srdivacky 188202375Srdivacky 189202375Srdivacky/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern: 190202375Srdivacky/// cmp pred (load (gep GV, ...)), cmpcst 191202375Srdivacky/// where GV is a global variable with a constant initializer. Try to simplify 192202375Srdivacky/// this into some simple computation that does not need the load. For example 193202375Srdivacky/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". 194202375Srdivacky/// 195202375Srdivacky/// If AndCst is non-null, then the loaded value is masked with that constant 196202375Srdivacky/// before doing the comparison. This handles cases like "A[i]&4 == 0". 197202375SrdivackyInstruction *InstCombiner:: 198202375SrdivackyFoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, 199202375Srdivacky CmpInst &ICI, ConstantInt *AndCst) { 200202375Srdivacky // We need TD information to know the pointer size unless this is inbounds. 201202375Srdivacky if (!GEP->isInBounds() && TD == 0) return 0; 202202375Srdivacky 203202375Srdivacky ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer()); 204202375Srdivacky if (Init == 0 || Init->getNumOperands() > 1024) return 0; 205202375Srdivacky 206202375Srdivacky // There are many forms of this optimization we can handle, for now, just do 207202375Srdivacky // the simple index into a single-dimensional array. 208202375Srdivacky // 209202375Srdivacky // Require: GEP GV, 0, i {{, constant indices}} 210202375Srdivacky if (GEP->getNumOperands() < 3 || 211202375Srdivacky !isa<ConstantInt>(GEP->getOperand(1)) || 212202375Srdivacky !cast<ConstantInt>(GEP->getOperand(1))->isZero() || 213202375Srdivacky isa<Constant>(GEP->getOperand(2))) 214202375Srdivacky return 0; 215202375Srdivacky 216202375Srdivacky // Check that indices after the variable are constants and in-range for the 217202375Srdivacky // type they index. Collect the indices. This is typically for arrays of 218202375Srdivacky // structs. 219202375Srdivacky SmallVector<unsigned, 4> LaterIndices; 220202375Srdivacky 221202375Srdivacky const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType(); 222202375Srdivacky for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { 223202375Srdivacky ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 224202375Srdivacky if (Idx == 0) return 0; // Variable index. 225202375Srdivacky 226202375Srdivacky uint64_t IdxVal = Idx->getZExtValue(); 227202375Srdivacky if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index. 228202375Srdivacky 229202375Srdivacky if (const StructType *STy = dyn_cast<StructType>(EltTy)) 230202375Srdivacky EltTy = STy->getElementType(IdxVal); 231202375Srdivacky else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { 232202375Srdivacky if (IdxVal >= ATy->getNumElements()) return 0; 233202375Srdivacky EltTy = ATy->getElementType(); 234202375Srdivacky } else { 235202375Srdivacky return 0; // Unknown type. 236202375Srdivacky } 237202375Srdivacky 238202375Srdivacky LaterIndices.push_back(IdxVal); 239202375Srdivacky } 240202375Srdivacky 241202375Srdivacky enum { Overdefined = -3, Undefined = -2 }; 242202375Srdivacky 243202375Srdivacky // Variables for our state machines. 244202375Srdivacky 245202375Srdivacky // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form 246202375Srdivacky // "i == 47 | i == 87", where 47 is the first index the condition is true for, 247202375Srdivacky // and 87 is the second (and last) index. FirstTrueElement is -2 when 248202375Srdivacky // undefined, otherwise set to the first true element. SecondTrueElement is 249202375Srdivacky // -2 when undefined, -3 when overdefined and >= 0 when that index is true. 250202375Srdivacky int FirstTrueElement = Undefined, SecondTrueElement = Undefined; 251202375Srdivacky 252202375Srdivacky // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the 253202375Srdivacky // form "i != 47 & i != 87". Same state transitions as for true elements. 254202375Srdivacky int FirstFalseElement = Undefined, SecondFalseElement = Undefined; 255202375Srdivacky 256202375Srdivacky /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these 257202375Srdivacky /// define a state machine that triggers for ranges of values that the index 258202375Srdivacky /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. 259202375Srdivacky /// This is -2 when undefined, -3 when overdefined, and otherwise the last 260202375Srdivacky /// index in the range (inclusive). We use -2 for undefined here because we 261202375Srdivacky /// use relative comparisons and don't want 0-1 to match -1. 262202375Srdivacky int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; 263202375Srdivacky 264202375Srdivacky // MagicBitvector - This is a magic bitvector where we set a bit if the 265202375Srdivacky // comparison is true for element 'i'. If there are 64 elements or less in 266202375Srdivacky // the array, this will fully represent all the comparison results. 267202375Srdivacky uint64_t MagicBitvector = 0; 268202375Srdivacky 269202375Srdivacky 270202375Srdivacky // Scan the array and see if one of our patterns matches. 271202375Srdivacky Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); 272202375Srdivacky for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 273202375Srdivacky Constant *Elt = Init->getOperand(i); 274202375Srdivacky 275202375Srdivacky // If this is indexing an array of structures, get the structure element. 276202375Srdivacky if (!LaterIndices.empty()) 277202375Srdivacky Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(), 278202375Srdivacky LaterIndices.size()); 279202375Srdivacky 280202375Srdivacky // If the element is masked, handle it. 281202375Srdivacky if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); 282202375Srdivacky 283202375Srdivacky // Find out if the comparison would be true or false for the i'th element. 284202375Srdivacky Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, 285202375Srdivacky CompareRHS, TD); 286202375Srdivacky // If the result is undef for this element, ignore it. 287202375Srdivacky if (isa<UndefValue>(C)) { 288202375Srdivacky // Extend range state machines to cover this element in case there is an 289202375Srdivacky // undef in the middle of the range. 290202375Srdivacky if (TrueRangeEnd == (int)i-1) 291202375Srdivacky TrueRangeEnd = i; 292202375Srdivacky if (FalseRangeEnd == (int)i-1) 293202375Srdivacky FalseRangeEnd = i; 294202375Srdivacky continue; 295202375Srdivacky } 296202375Srdivacky 297202375Srdivacky // If we can't compute the result for any of the elements, we have to give 298202375Srdivacky // up evaluating the entire conditional. 299202375Srdivacky if (!isa<ConstantInt>(C)) return 0; 300202375Srdivacky 301202375Srdivacky // Otherwise, we know if the comparison is true or false for this element, 302202375Srdivacky // update our state machines. 303202375Srdivacky bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); 304202375Srdivacky 305202375Srdivacky // State machine for single/double/range index comparison. 306202375Srdivacky if (IsTrueForElt) { 307202375Srdivacky // Update the TrueElement state machine. 308202375Srdivacky if (FirstTrueElement == Undefined) 309202375Srdivacky FirstTrueElement = TrueRangeEnd = i; // First true element. 310202375Srdivacky else { 311202375Srdivacky // Update double-compare state machine. 312202375Srdivacky if (SecondTrueElement == Undefined) 313202375Srdivacky SecondTrueElement = i; 314202375Srdivacky else 315202375Srdivacky SecondTrueElement = Overdefined; 316202375Srdivacky 317202375Srdivacky // Update range state machine. 318202375Srdivacky if (TrueRangeEnd == (int)i-1) 319202375Srdivacky TrueRangeEnd = i; 320202375Srdivacky else 321202375Srdivacky TrueRangeEnd = Overdefined; 322202375Srdivacky } 323202375Srdivacky } else { 324202375Srdivacky // Update the FalseElement state machine. 325202375Srdivacky if (FirstFalseElement == Undefined) 326202375Srdivacky FirstFalseElement = FalseRangeEnd = i; // First false element. 327202375Srdivacky else { 328202375Srdivacky // Update double-compare state machine. 329202375Srdivacky if (SecondFalseElement == Undefined) 330202375Srdivacky SecondFalseElement = i; 331202375Srdivacky else 332202375Srdivacky SecondFalseElement = Overdefined; 333202375Srdivacky 334202375Srdivacky // Update range state machine. 335202375Srdivacky if (FalseRangeEnd == (int)i-1) 336202375Srdivacky FalseRangeEnd = i; 337202375Srdivacky else 338202375Srdivacky FalseRangeEnd = Overdefined; 339202375Srdivacky } 340202375Srdivacky } 341202375Srdivacky 342202375Srdivacky 343202375Srdivacky // If this element is in range, update our magic bitvector. 344202375Srdivacky if (i < 64 && IsTrueForElt) 345202375Srdivacky MagicBitvector |= 1ULL << i; 346202375Srdivacky 347202375Srdivacky // If all of our states become overdefined, bail out early. Since the 348202375Srdivacky // predicate is expensive, only check it every 8 elements. This is only 349202375Srdivacky // really useful for really huge arrays. 350202375Srdivacky if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && 351202375Srdivacky SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && 352202375Srdivacky FalseRangeEnd == Overdefined) 353202375Srdivacky return 0; 354202375Srdivacky } 355202375Srdivacky 356202375Srdivacky // Now that we've scanned the entire array, emit our new comparison(s). We 357202375Srdivacky // order the state machines in complexity of the generated code. 358202375Srdivacky Value *Idx = GEP->getOperand(2); 359202375Srdivacky 360202375Srdivacky // If the index is larger than the pointer size of the target, truncate the 361202375Srdivacky // index down like the GEP would do implicitly. We don't have to do this for 362202375Srdivacky // an inbounds GEP because the index can't be out of range. 363202375Srdivacky if (!GEP->isInBounds() && 364202375Srdivacky Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits()) 365202375Srdivacky Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext())); 366202375Srdivacky 367202375Srdivacky // If the comparison is only true for one or two elements, emit direct 368202375Srdivacky // comparisons. 369202375Srdivacky if (SecondTrueElement != Overdefined) { 370202375Srdivacky // None true -> false. 371202375Srdivacky if (FirstTrueElement == Undefined) 372202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext())); 373202375Srdivacky 374202375Srdivacky Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); 375202375Srdivacky 376202375Srdivacky // True for one element -> 'i == 47'. 377202375Srdivacky if (SecondTrueElement == Undefined) 378202375Srdivacky return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); 379202375Srdivacky 380202375Srdivacky // True for two elements -> 'i == 47 | i == 72'. 381202375Srdivacky Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx); 382202375Srdivacky Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); 383202375Srdivacky Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx); 384202375Srdivacky return BinaryOperator::CreateOr(C1, C2); 385202375Srdivacky } 386202375Srdivacky 387202375Srdivacky // If the comparison is only false for one or two elements, emit direct 388202375Srdivacky // comparisons. 389202375Srdivacky if (SecondFalseElement != Overdefined) { 390202375Srdivacky // None false -> true. 391202375Srdivacky if (FirstFalseElement == Undefined) 392202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext())); 393202375Srdivacky 394202375Srdivacky Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); 395202375Srdivacky 396202375Srdivacky // False for one element -> 'i != 47'. 397202375Srdivacky if (SecondFalseElement == Undefined) 398202375Srdivacky return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); 399202375Srdivacky 400202375Srdivacky // False for two elements -> 'i != 47 & i != 72'. 401202375Srdivacky Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx); 402202375Srdivacky Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); 403202375Srdivacky Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx); 404202375Srdivacky return BinaryOperator::CreateAnd(C1, C2); 405202375Srdivacky } 406202375Srdivacky 407202375Srdivacky // If the comparison can be replaced with a range comparison for the elements 408202375Srdivacky // where it is true, emit the range check. 409202375Srdivacky if (TrueRangeEnd != Overdefined) { 410202375Srdivacky assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); 411202375Srdivacky 412202375Srdivacky // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). 413202375Srdivacky if (FirstTrueElement) { 414202375Srdivacky Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); 415202375Srdivacky Idx = Builder->CreateAdd(Idx, Offs); 416202375Srdivacky } 417202375Srdivacky 418202375Srdivacky Value *End = ConstantInt::get(Idx->getType(), 419202375Srdivacky TrueRangeEnd-FirstTrueElement+1); 420202375Srdivacky return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); 421202375Srdivacky } 422202375Srdivacky 423202375Srdivacky // False range check. 424202375Srdivacky if (FalseRangeEnd != Overdefined) { 425202375Srdivacky assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); 426202375Srdivacky // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). 427202375Srdivacky if (FirstFalseElement) { 428202375Srdivacky Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); 429202375Srdivacky Idx = Builder->CreateAdd(Idx, Offs); 430202375Srdivacky } 431202375Srdivacky 432202375Srdivacky Value *End = ConstantInt::get(Idx->getType(), 433202375Srdivacky FalseRangeEnd-FirstFalseElement); 434202375Srdivacky return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); 435202375Srdivacky } 436202375Srdivacky 437202375Srdivacky 438202375Srdivacky // If a 32-bit or 64-bit magic bitvector captures the entire comparison state 439202375Srdivacky // of this load, replace it with computation that does: 440202375Srdivacky // ((magic_cst >> i) & 1) != 0 441202375Srdivacky if (Init->getNumOperands() <= 32 || 442202375Srdivacky (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) { 443202375Srdivacky const Type *Ty; 444202375Srdivacky if (Init->getNumOperands() <= 32) 445202375Srdivacky Ty = Type::getInt32Ty(Init->getContext()); 446202375Srdivacky else 447202375Srdivacky Ty = Type::getInt64Ty(Init->getContext()); 448202375Srdivacky Value *V = Builder->CreateIntCast(Idx, Ty, false); 449202375Srdivacky V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); 450202375Srdivacky V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); 451202375Srdivacky return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); 452202375Srdivacky } 453202375Srdivacky 454202375Srdivacky return 0; 455202375Srdivacky} 456202375Srdivacky 457202375Srdivacky 458202375Srdivacky/// EvaluateGEPOffsetExpression - Return a value that can be used to compare 459202375Srdivacky/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we 460202375Srdivacky/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can 461202375Srdivacky/// be complex, and scales are involved. The above expression would also be 462202375Srdivacky/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). 463202375Srdivacky/// This later form is less amenable to optimization though, and we are allowed 464202375Srdivacky/// to generate the first by knowing that pointer arithmetic doesn't overflow. 465202375Srdivacky/// 466202375Srdivacky/// If we can't emit an optimized form for this expression, this returns null. 467202375Srdivacky/// 468202375Srdivackystatic Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I, 469202375Srdivacky InstCombiner &IC) { 470202375Srdivacky TargetData &TD = *IC.getTargetData(); 471202375Srdivacky gep_type_iterator GTI = gep_type_begin(GEP); 472202375Srdivacky 473202375Srdivacky // Check to see if this gep only has a single variable index. If so, and if 474202375Srdivacky // any constant indices are a multiple of its scale, then we can compute this 475202375Srdivacky // in terms of the scale of the variable index. For example, if the GEP 476202375Srdivacky // implies an offset of "12 + i*4", then we can codegen this as "3 + i", 477202375Srdivacky // because the expression will cross zero at the same point. 478202375Srdivacky unsigned i, e = GEP->getNumOperands(); 479202375Srdivacky int64_t Offset = 0; 480202375Srdivacky for (i = 1; i != e; ++i, ++GTI) { 481202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 482202375Srdivacky // Compute the aggregate offset of constant indices. 483202375Srdivacky if (CI->isZero()) continue; 484202375Srdivacky 485202375Srdivacky // Handle a struct index, which adds its field offset to the pointer. 486202375Srdivacky if (const StructType *STy = dyn_cast<StructType>(*GTI)) { 487202375Srdivacky Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 488202375Srdivacky } else { 489202375Srdivacky uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); 490202375Srdivacky Offset += Size*CI->getSExtValue(); 491202375Srdivacky } 492202375Srdivacky } else { 493202375Srdivacky // Found our variable index. 494202375Srdivacky break; 495202375Srdivacky } 496202375Srdivacky } 497202375Srdivacky 498202375Srdivacky // If there are no variable indices, we must have a constant offset, just 499202375Srdivacky // evaluate it the general way. 500202375Srdivacky if (i == e) return 0; 501202375Srdivacky 502202375Srdivacky Value *VariableIdx = GEP->getOperand(i); 503202375Srdivacky // Determine the scale factor of the variable element. For example, this is 504202375Srdivacky // 4 if the variable index is into an array of i32. 505202375Srdivacky uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType()); 506202375Srdivacky 507202375Srdivacky // Verify that there are no other variable indices. If so, emit the hard way. 508202375Srdivacky for (++i, ++GTI; i != e; ++i, ++GTI) { 509202375Srdivacky ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); 510202375Srdivacky if (!CI) return 0; 511202375Srdivacky 512202375Srdivacky // Compute the aggregate offset of constant indices. 513202375Srdivacky if (CI->isZero()) continue; 514202375Srdivacky 515202375Srdivacky // Handle a struct index, which adds its field offset to the pointer. 516202375Srdivacky if (const StructType *STy = dyn_cast<StructType>(*GTI)) { 517202375Srdivacky Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 518202375Srdivacky } else { 519202375Srdivacky uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); 520202375Srdivacky Offset += Size*CI->getSExtValue(); 521202375Srdivacky } 522202375Srdivacky } 523202375Srdivacky 524202375Srdivacky // Okay, we know we have a single variable index, which must be a 525202375Srdivacky // pointer/array/vector index. If there is no offset, life is simple, return 526202375Srdivacky // the index. 527202375Srdivacky unsigned IntPtrWidth = TD.getPointerSizeInBits(); 528202375Srdivacky if (Offset == 0) { 529202375Srdivacky // Cast to intptrty in case a truncation occurs. If an extension is needed, 530202375Srdivacky // we don't need to bother extending: the extension won't affect where the 531202375Srdivacky // computation crosses zero. 532202375Srdivacky if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) 533202375Srdivacky VariableIdx = new TruncInst(VariableIdx, 534202375Srdivacky TD.getIntPtrType(VariableIdx->getContext()), 535202375Srdivacky VariableIdx->getName(), &I); 536202375Srdivacky return VariableIdx; 537202375Srdivacky } 538202375Srdivacky 539202375Srdivacky // Otherwise, there is an index. The computation we will do will be modulo 540202375Srdivacky // the pointer size, so get it. 541202375Srdivacky uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); 542202375Srdivacky 543202375Srdivacky Offset &= PtrSizeMask; 544202375Srdivacky VariableScale &= PtrSizeMask; 545202375Srdivacky 546202375Srdivacky // To do this transformation, any constant index must be a multiple of the 547202375Srdivacky // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", 548202375Srdivacky // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a 549202375Srdivacky // multiple of the variable scale. 550202375Srdivacky int64_t NewOffs = Offset / (int64_t)VariableScale; 551202375Srdivacky if (Offset != NewOffs*(int64_t)VariableScale) 552202375Srdivacky return 0; 553202375Srdivacky 554202375Srdivacky // Okay, we can do this evaluation. Start by converting the index to intptr. 555202375Srdivacky const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext()); 556202375Srdivacky if (VariableIdx->getType() != IntPtrTy) 557202375Srdivacky VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy, 558202375Srdivacky true /*SExt*/, 559202375Srdivacky VariableIdx->getName(), &I); 560202375Srdivacky Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); 561202375Srdivacky return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I); 562202375Srdivacky} 563202375Srdivacky 564202375Srdivacky/// FoldGEPICmp - Fold comparisons between a GEP instruction and something 565202375Srdivacky/// else. At this point we know that the GEP is on the LHS of the comparison. 566202375SrdivackyInstruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS, 567202375Srdivacky ICmpInst::Predicate Cond, 568202375Srdivacky Instruction &I) { 569202375Srdivacky // Look through bitcasts. 570202375Srdivacky if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS)) 571202375Srdivacky RHS = BCI->getOperand(0); 572202375Srdivacky 573202375Srdivacky Value *PtrBase = GEPLHS->getOperand(0); 574202375Srdivacky if (TD && PtrBase == RHS && GEPLHS->isInBounds()) { 575202375Srdivacky // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). 576202375Srdivacky // This transformation (ignoring the base and scales) is valid because we 577202375Srdivacky // know pointers can't overflow since the gep is inbounds. See if we can 578202375Srdivacky // output an optimized form. 579202375Srdivacky Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this); 580202375Srdivacky 581202375Srdivacky // If not, synthesize the offset the hard way. 582202375Srdivacky if (Offset == 0) 583202375Srdivacky Offset = EmitGEPOffset(GEPLHS); 584202375Srdivacky return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, 585202375Srdivacky Constant::getNullValue(Offset->getType())); 586202375Srdivacky } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { 587202375Srdivacky // If the base pointers are different, but the indices are the same, just 588202375Srdivacky // compare the base pointer. 589202375Srdivacky if (PtrBase != GEPRHS->getOperand(0)) { 590202375Srdivacky bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); 591202375Srdivacky IndicesTheSame &= GEPLHS->getOperand(0)->getType() == 592202375Srdivacky GEPRHS->getOperand(0)->getType(); 593202375Srdivacky if (IndicesTheSame) 594202375Srdivacky for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 595202375Srdivacky if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 596202375Srdivacky IndicesTheSame = false; 597202375Srdivacky break; 598202375Srdivacky } 599202375Srdivacky 600202375Srdivacky // If all indices are the same, just compare the base pointers. 601202375Srdivacky if (IndicesTheSame) 602202375Srdivacky return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 603202375Srdivacky GEPLHS->getOperand(0), GEPRHS->getOperand(0)); 604202375Srdivacky 605202375Srdivacky // Otherwise, the base pointers are different and the indices are 606202375Srdivacky // different, bail out. 607202375Srdivacky return 0; 608202375Srdivacky } 609202375Srdivacky 610202375Srdivacky // If one of the GEPs has all zero indices, recurse. 611202375Srdivacky bool AllZeros = true; 612202375Srdivacky for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 613202375Srdivacky if (!isa<Constant>(GEPLHS->getOperand(i)) || 614202375Srdivacky !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) { 615202375Srdivacky AllZeros = false; 616202375Srdivacky break; 617202375Srdivacky } 618202375Srdivacky if (AllZeros) 619202375Srdivacky return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0), 620202375Srdivacky ICmpInst::getSwappedPredicate(Cond), I); 621202375Srdivacky 622202375Srdivacky // If the other GEP has all zero indices, recurse. 623202375Srdivacky AllZeros = true; 624202375Srdivacky for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 625202375Srdivacky if (!isa<Constant>(GEPRHS->getOperand(i)) || 626202375Srdivacky !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) { 627202375Srdivacky AllZeros = false; 628202375Srdivacky break; 629202375Srdivacky } 630202375Srdivacky if (AllZeros) 631202375Srdivacky return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); 632202375Srdivacky 633202375Srdivacky if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { 634202375Srdivacky // If the GEPs only differ by one index, compare it. 635202375Srdivacky unsigned NumDifferences = 0; // Keep track of # differences. 636202375Srdivacky unsigned DiffOperand = 0; // The operand that differs. 637202375Srdivacky for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 638202375Srdivacky if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 639202375Srdivacky if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != 640202375Srdivacky GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { 641202375Srdivacky // Irreconcilable differences. 642202375Srdivacky NumDifferences = 2; 643202375Srdivacky break; 644202375Srdivacky } else { 645202375Srdivacky if (NumDifferences++) break; 646202375Srdivacky DiffOperand = i; 647202375Srdivacky } 648202375Srdivacky } 649202375Srdivacky 650202375Srdivacky if (NumDifferences == 0) // SAME GEP? 651202375Srdivacky return ReplaceInstUsesWith(I, // No comparison is needed here. 652202375Srdivacky ConstantInt::get(Type::getInt1Ty(I.getContext()), 653202375Srdivacky ICmpInst::isTrueWhenEqual(Cond))); 654202375Srdivacky 655202375Srdivacky else if (NumDifferences == 1) { 656202375Srdivacky Value *LHSV = GEPLHS->getOperand(DiffOperand); 657202375Srdivacky Value *RHSV = GEPRHS->getOperand(DiffOperand); 658202375Srdivacky // Make sure we do a signed comparison here. 659202375Srdivacky return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); 660202375Srdivacky } 661202375Srdivacky } 662202375Srdivacky 663202375Srdivacky // Only lower this if the icmp is the only user of the GEP or if we expect 664202375Srdivacky // the result to fold to a constant! 665202375Srdivacky if (TD && 666202375Srdivacky (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && 667202375Srdivacky (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { 668202375Srdivacky // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) 669202375Srdivacky Value *L = EmitGEPOffset(GEPLHS); 670202375Srdivacky Value *R = EmitGEPOffset(GEPRHS); 671202375Srdivacky return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); 672202375Srdivacky } 673202375Srdivacky } 674202375Srdivacky return 0; 675202375Srdivacky} 676202375Srdivacky 677202375Srdivacky/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X". 678202375SrdivackyInstruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI, 679202375Srdivacky Value *X, ConstantInt *CI, 680202375Srdivacky ICmpInst::Predicate Pred, 681202375Srdivacky Value *TheAdd) { 682202375Srdivacky // If we have X+0, exit early (simplifying logic below) and let it get folded 683202375Srdivacky // elsewhere. icmp X+0, X -> icmp X, X 684202375Srdivacky if (CI->isZero()) { 685202375Srdivacky bool isTrue = ICmpInst::isTrueWhenEqual(Pred); 686202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue)); 687202375Srdivacky } 688202375Srdivacky 689202375Srdivacky // (X+4) == X -> false. 690202375Srdivacky if (Pred == ICmpInst::ICMP_EQ) 691202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 692202375Srdivacky 693202375Srdivacky // (X+4) != X -> true. 694202375Srdivacky if (Pred == ICmpInst::ICMP_NE) 695202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 696202375Srdivacky 697202375Srdivacky // If this is an instruction (as opposed to constantexpr) get NUW/NSW info. 698202375Srdivacky bool isNUW = false, isNSW = false; 699202375Srdivacky if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) { 700202375Srdivacky isNUW = Add->hasNoUnsignedWrap(); 701202375Srdivacky isNSW = Add->hasNoSignedWrap(); 702202375Srdivacky } 703202375Srdivacky 704202375Srdivacky // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, 705202375Srdivacky // so the values can never be equal. Similiarly for all other "or equals" 706202375Srdivacky // operators. 707202375Srdivacky 708202375Srdivacky // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 709202375Srdivacky // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 710202375Srdivacky // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 711202375Srdivacky if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 712202375Srdivacky // If this is an NUW add, then this is always false. 713202375Srdivacky if (isNUW) 714202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 715202375Srdivacky 716202375Srdivacky Value *R = 717202375Srdivacky ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI); 718202375Srdivacky return new ICmpInst(ICmpInst::ICMP_UGT, X, R); 719202375Srdivacky } 720202375Srdivacky 721202375Srdivacky // (X+1) >u X --> X <u (0-1) --> X != 255 722202375Srdivacky // (X+2) >u X --> X <u (0-2) --> X <u 254 723202375Srdivacky // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 724202375Srdivacky if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) { 725202375Srdivacky // If this is an NUW add, then this is always true. 726202375Srdivacky if (isNUW) 727202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 728202375Srdivacky return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI)); 729202375Srdivacky } 730202375Srdivacky 731202375Srdivacky unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits(); 732202375Srdivacky ConstantInt *SMax = ConstantInt::get(X->getContext(), 733202375Srdivacky APInt::getSignedMaxValue(BitWidth)); 734202375Srdivacky 735202375Srdivacky // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 736202375Srdivacky // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 737202375Srdivacky // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 738202375Srdivacky // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 739202375Srdivacky // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 740202375Srdivacky // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 741202375Srdivacky if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) { 742202375Srdivacky // If this is an NSW add, then we have two cases: if the constant is 743202375Srdivacky // positive, then this is always false, if negative, this is always true. 744202375Srdivacky if (isNSW) { 745202375Srdivacky bool isTrue = CI->getValue().isNegative(); 746202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue)); 747202375Srdivacky } 748202375Srdivacky 749202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI)); 750202375Srdivacky } 751202375Srdivacky 752202375Srdivacky // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 753202375Srdivacky // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 754202375Srdivacky // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 755202375Srdivacky // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 756202375Srdivacky // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 757202375Srdivacky // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 758202375Srdivacky 759202375Srdivacky // If this is an NSW add, then we have two cases: if the constant is 760202375Srdivacky // positive, then this is always true, if negative, this is always false. 761202375Srdivacky if (isNSW) { 762202375Srdivacky bool isTrue = !CI->getValue().isNegative(); 763202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue)); 764202375Srdivacky } 765202375Srdivacky 766202375Srdivacky assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); 767202375Srdivacky Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1); 768202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C)); 769202375Srdivacky} 770202375Srdivacky 771202375Srdivacky/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS 772202375Srdivacky/// and CmpRHS are both known to be integer constants. 773202375SrdivackyInstruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI, 774202375Srdivacky ConstantInt *DivRHS) { 775202375Srdivacky ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1)); 776202375Srdivacky const APInt &CmpRHSV = CmpRHS->getValue(); 777202375Srdivacky 778202375Srdivacky // FIXME: If the operand types don't match the type of the divide 779202375Srdivacky // then don't attempt this transform. The code below doesn't have the 780202375Srdivacky // logic to deal with a signed divide and an unsigned compare (and 781202375Srdivacky // vice versa). This is because (x /s C1) <s C2 produces different 782202375Srdivacky // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even 783202375Srdivacky // (x /u C1) <u C2. Simply casting the operands and result won't 784202375Srdivacky // work. :( The if statement below tests that condition and bails 785202375Srdivacky // if it finds it. 786202375Srdivacky bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv; 787202375Srdivacky if (!ICI.isEquality() && DivIsSigned != ICI.isSigned()) 788202375Srdivacky return 0; 789202375Srdivacky if (DivRHS->isZero()) 790202375Srdivacky return 0; // The ProdOV computation fails on divide by zero. 791202375Srdivacky if (DivIsSigned && DivRHS->isAllOnesValue()) 792202375Srdivacky return 0; // The overflow computation also screws up here 793202375Srdivacky if (DivRHS->isOne()) 794202375Srdivacky return 0; // Not worth bothering, and eliminates some funny cases 795202375Srdivacky // with INT_MIN. 796202375Srdivacky 797202375Srdivacky // Compute Prod = CI * DivRHS. We are essentially solving an equation 798202375Srdivacky // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 799202375Srdivacky // C2 (CI). By solving for X we can turn this into a range check 800202375Srdivacky // instead of computing a divide. 801202375Srdivacky Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS); 802202375Srdivacky 803202375Srdivacky // Determine if the product overflows by seeing if the product is 804202375Srdivacky // not equal to the divide. Make sure we do the same kind of divide 805202375Srdivacky // as in the LHS instruction that we're folding. 806202375Srdivacky bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) : 807202375Srdivacky ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS; 808202375Srdivacky 809202375Srdivacky // Get the ICmp opcode 810202375Srdivacky ICmpInst::Predicate Pred = ICI.getPredicate(); 811202375Srdivacky 812202375Srdivacky // Figure out the interval that is being checked. For example, a comparison 813202375Srdivacky // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 814202375Srdivacky // Compute this interval based on the constants involved and the signedness of 815202375Srdivacky // the compare/divide. This computes a half-open interval, keeping track of 816202375Srdivacky // whether either value in the interval overflows. After analysis each 817202375Srdivacky // overflow variable is set to 0 if it's corresponding bound variable is valid 818202375Srdivacky // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. 819202375Srdivacky int LoOverflow = 0, HiOverflow = 0; 820202375Srdivacky Constant *LoBound = 0, *HiBound = 0; 821202375Srdivacky 822202375Srdivacky if (!DivIsSigned) { // udiv 823202375Srdivacky // e.g. X/5 op 3 --> [15, 20) 824202375Srdivacky LoBound = Prod; 825202375Srdivacky HiOverflow = LoOverflow = ProdOV; 826202375Srdivacky if (!HiOverflow) 827202375Srdivacky HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false); 828202375Srdivacky } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0. 829202375Srdivacky if (CmpRHSV == 0) { // (X / pos) op 0 830202375Srdivacky // Can't overflow. e.g. X/2 op 0 --> [-1, 2) 831202375Srdivacky LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS))); 832202375Srdivacky HiBound = DivRHS; 833202375Srdivacky } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos 834202375Srdivacky LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) 835202375Srdivacky HiOverflow = LoOverflow = ProdOV; 836202375Srdivacky if (!HiOverflow) 837202375Srdivacky HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true); 838202375Srdivacky } else { // (X / pos) op neg 839202375Srdivacky // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) 840202375Srdivacky HiBound = AddOne(Prod); 841202375Srdivacky LoOverflow = HiOverflow = ProdOV ? -1 : 0; 842202375Srdivacky if (!LoOverflow) { 843202375Srdivacky ConstantInt* DivNeg = 844202375Srdivacky cast<ConstantInt>(ConstantExpr::getNeg(DivRHS)); 845202375Srdivacky LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; 846202375Srdivacky } 847202375Srdivacky } 848202375Srdivacky } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0. 849202375Srdivacky if (CmpRHSV == 0) { // (X / neg) op 0 850202375Srdivacky // e.g. X/-5 op 0 --> [-4, 5) 851202375Srdivacky LoBound = AddOne(DivRHS); 852202375Srdivacky HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS)); 853202375Srdivacky if (HiBound == DivRHS) { // -INTMIN = INTMIN 854202375Srdivacky HiOverflow = 1; // [INTMIN+1, overflow) 855202375Srdivacky HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN 856202375Srdivacky } 857202375Srdivacky } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos 858202375Srdivacky // e.g. X/-5 op 3 --> [-19, -14) 859202375Srdivacky HiBound = AddOne(Prod); 860202375Srdivacky HiOverflow = LoOverflow = ProdOV ? -1 : 0; 861202375Srdivacky if (!LoOverflow) 862202375Srdivacky LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0; 863202375Srdivacky } else { // (X / neg) op neg 864202375Srdivacky LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) 865202375Srdivacky LoOverflow = HiOverflow = ProdOV; 866202375Srdivacky if (!HiOverflow) 867202375Srdivacky HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true); 868202375Srdivacky } 869202375Srdivacky 870202375Srdivacky // Dividing by a negative swaps the condition. LT <-> GT 871202375Srdivacky Pred = ICmpInst::getSwappedPredicate(Pred); 872202375Srdivacky } 873202375Srdivacky 874202375Srdivacky Value *X = DivI->getOperand(0); 875202375Srdivacky switch (Pred) { 876202375Srdivacky default: llvm_unreachable("Unhandled icmp opcode!"); 877202375Srdivacky case ICmpInst::ICMP_EQ: 878202375Srdivacky if (LoOverflow && HiOverflow) 879202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext())); 880202375Srdivacky else if (HiOverflow) 881202375Srdivacky return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 882202375Srdivacky ICmpInst::ICMP_UGE, X, LoBound); 883202375Srdivacky else if (LoOverflow) 884202375Srdivacky return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 885202375Srdivacky ICmpInst::ICMP_ULT, X, HiBound); 886202375Srdivacky else 887202375Srdivacky return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI); 888202375Srdivacky case ICmpInst::ICMP_NE: 889202375Srdivacky if (LoOverflow && HiOverflow) 890202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext())); 891202375Srdivacky else if (HiOverflow) 892202375Srdivacky return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 893202375Srdivacky ICmpInst::ICMP_ULT, X, LoBound); 894202375Srdivacky else if (LoOverflow) 895202375Srdivacky return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 896202375Srdivacky ICmpInst::ICMP_UGE, X, HiBound); 897202375Srdivacky else 898202375Srdivacky return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI); 899202375Srdivacky case ICmpInst::ICMP_ULT: 900202375Srdivacky case ICmpInst::ICMP_SLT: 901202375Srdivacky if (LoOverflow == +1) // Low bound is greater than input range. 902202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext())); 903202375Srdivacky if (LoOverflow == -1) // Low bound is less than input range. 904202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext())); 905202375Srdivacky return new ICmpInst(Pred, X, LoBound); 906202375Srdivacky case ICmpInst::ICMP_UGT: 907202375Srdivacky case ICmpInst::ICMP_SGT: 908202375Srdivacky if (HiOverflow == +1) // High bound greater than input range. 909202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext())); 910202375Srdivacky else if (HiOverflow == -1) // High bound less than input range. 911202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext())); 912202375Srdivacky if (Pred == ICmpInst::ICMP_UGT) 913202375Srdivacky return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound); 914202375Srdivacky else 915202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound); 916202375Srdivacky } 917202375Srdivacky} 918202375Srdivacky 919202375Srdivacky 920202375Srdivacky/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)". 921202375Srdivacky/// 922202375SrdivackyInstruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI, 923202375Srdivacky Instruction *LHSI, 924202375Srdivacky ConstantInt *RHS) { 925202375Srdivacky const APInt &RHSV = RHS->getValue(); 926202375Srdivacky 927202375Srdivacky switch (LHSI->getOpcode()) { 928202375Srdivacky case Instruction::Trunc: 929202375Srdivacky if (ICI.isEquality() && LHSI->hasOneUse()) { 930202375Srdivacky // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all 931202375Srdivacky // of the high bits truncated out of x are known. 932202375Srdivacky unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(), 933202375Srdivacky SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits(); 934202375Srdivacky APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits)); 935202375Srdivacky APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0); 936202375Srdivacky ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne); 937202375Srdivacky 938202375Srdivacky // If all the high bits are known, we can do this xform. 939202375Srdivacky if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) { 940202375Srdivacky // Pull in the high bits from known-ones set. 941202375Srdivacky APInt NewRHS(RHS->getValue()); 942202375Srdivacky NewRHS.zext(SrcBits); 943202375Srdivacky NewRHS |= KnownOne; 944202375Srdivacky return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 945202375Srdivacky ConstantInt::get(ICI.getContext(), NewRHS)); 946202375Srdivacky } 947202375Srdivacky } 948202375Srdivacky break; 949202375Srdivacky 950202375Srdivacky case Instruction::Xor: // (icmp pred (xor X, XorCST), CI) 951202375Srdivacky if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) { 952202375Srdivacky // If this is a comparison that tests the signbit (X < 0) or (x > -1), 953202375Srdivacky // fold the xor. 954202375Srdivacky if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) || 955202375Srdivacky (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) { 956202375Srdivacky Value *CompareVal = LHSI->getOperand(0); 957202375Srdivacky 958202375Srdivacky // If the sign bit of the XorCST is not set, there is no change to 959202375Srdivacky // the operation, just stop using the Xor. 960202375Srdivacky if (!XorCST->getValue().isNegative()) { 961202375Srdivacky ICI.setOperand(0, CompareVal); 962202375Srdivacky Worklist.Add(LHSI); 963202375Srdivacky return &ICI; 964202375Srdivacky } 965202375Srdivacky 966202375Srdivacky // Was the old condition true if the operand is positive? 967202375Srdivacky bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT; 968202375Srdivacky 969202375Srdivacky // If so, the new one isn't. 970202375Srdivacky isTrueIfPositive ^= true; 971202375Srdivacky 972202375Srdivacky if (isTrueIfPositive) 973202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, 974202375Srdivacky SubOne(RHS)); 975202375Srdivacky else 976202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, 977202375Srdivacky AddOne(RHS)); 978202375Srdivacky } 979202375Srdivacky 980202375Srdivacky if (LHSI->hasOneUse()) { 981202375Srdivacky // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit)) 982202375Srdivacky if (!ICI.isEquality() && XorCST->getValue().isSignBit()) { 983202375Srdivacky const APInt &SignBit = XorCST->getValue(); 984202375Srdivacky ICmpInst::Predicate Pred = ICI.isSigned() 985202375Srdivacky ? ICI.getUnsignedPredicate() 986202375Srdivacky : ICI.getSignedPredicate(); 987202375Srdivacky return new ICmpInst(Pred, LHSI->getOperand(0), 988202375Srdivacky ConstantInt::get(ICI.getContext(), 989202375Srdivacky RHSV ^ SignBit)); 990202375Srdivacky } 991202375Srdivacky 992202375Srdivacky // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A) 993202375Srdivacky if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) { 994202375Srdivacky const APInt &NotSignBit = XorCST->getValue(); 995202375Srdivacky ICmpInst::Predicate Pred = ICI.isSigned() 996202375Srdivacky ? ICI.getUnsignedPredicate() 997202375Srdivacky : ICI.getSignedPredicate(); 998202375Srdivacky Pred = ICI.getSwappedPredicate(Pred); 999202375Srdivacky return new ICmpInst(Pred, LHSI->getOperand(0), 1000202375Srdivacky ConstantInt::get(ICI.getContext(), 1001202375Srdivacky RHSV ^ NotSignBit)); 1002202375Srdivacky } 1003202375Srdivacky } 1004202375Srdivacky } 1005202375Srdivacky break; 1006202375Srdivacky case Instruction::And: // (icmp pred (and X, AndCST), RHS) 1007202375Srdivacky if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) && 1008202375Srdivacky LHSI->getOperand(0)->hasOneUse()) { 1009202375Srdivacky ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1)); 1010202375Srdivacky 1011202375Srdivacky // If the LHS is an AND of a truncating cast, we can widen the 1012202375Srdivacky // and/compare to be the input width without changing the value 1013202375Srdivacky // produced, eliminating a cast. 1014202375Srdivacky if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) { 1015202375Srdivacky // We can do this transformation if either the AND constant does not 1016202375Srdivacky // have its sign bit set or if it is an equality comparison. 1017202375Srdivacky // Extending a relational comparison when we're checking the sign 1018202375Srdivacky // bit would not work. 1019202375Srdivacky if (Cast->hasOneUse() && 1020202375Srdivacky (ICI.isEquality() || 1021202375Srdivacky (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) { 1022202375Srdivacky uint32_t BitWidth = 1023202375Srdivacky cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth(); 1024202375Srdivacky APInt NewCST = AndCST->getValue(); 1025202375Srdivacky NewCST.zext(BitWidth); 1026202375Srdivacky APInt NewCI = RHSV; 1027202375Srdivacky NewCI.zext(BitWidth); 1028202375Srdivacky Value *NewAnd = 1029202375Srdivacky Builder->CreateAnd(Cast->getOperand(0), 1030202375Srdivacky ConstantInt::get(ICI.getContext(), NewCST), 1031202375Srdivacky LHSI->getName()); 1032202375Srdivacky return new ICmpInst(ICI.getPredicate(), NewAnd, 1033202375Srdivacky ConstantInt::get(ICI.getContext(), NewCI)); 1034202375Srdivacky } 1035202375Srdivacky } 1036202375Srdivacky 1037202375Srdivacky // If this is: (X >> C1) & C2 != C3 (where any shift and any compare 1038202375Srdivacky // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This 1039202375Srdivacky // happens a LOT in code produced by the C front-end, for bitfield 1040202375Srdivacky // access. 1041202375Srdivacky BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0)); 1042202375Srdivacky if (Shift && !Shift->isShift()) 1043202375Srdivacky Shift = 0; 1044202375Srdivacky 1045202375Srdivacky ConstantInt *ShAmt; 1046202375Srdivacky ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0; 1047202375Srdivacky const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift. 1048202375Srdivacky const Type *AndTy = AndCST->getType(); // Type of the and. 1049202375Srdivacky 1050202375Srdivacky // We can fold this as long as we can't shift unknown bits 1051202375Srdivacky // into the mask. This can only happen with signed shift 1052202375Srdivacky // rights, as they sign-extend. 1053202375Srdivacky if (ShAmt) { 1054202375Srdivacky bool CanFold = Shift->isLogicalShift(); 1055202375Srdivacky if (!CanFold) { 1056202375Srdivacky // To test for the bad case of the signed shr, see if any 1057202375Srdivacky // of the bits shifted in could be tested after the mask. 1058202375Srdivacky uint32_t TyBits = Ty->getPrimitiveSizeInBits(); 1059202375Srdivacky int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits); 1060202375Srdivacky 1061202375Srdivacky uint32_t BitWidth = AndTy->getPrimitiveSizeInBits(); 1062202375Srdivacky if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 1063202375Srdivacky AndCST->getValue()) == 0) 1064202375Srdivacky CanFold = true; 1065202375Srdivacky } 1066202375Srdivacky 1067202375Srdivacky if (CanFold) { 1068202375Srdivacky Constant *NewCst; 1069202375Srdivacky if (Shift->getOpcode() == Instruction::Shl) 1070202375Srdivacky NewCst = ConstantExpr::getLShr(RHS, ShAmt); 1071202375Srdivacky else 1072202375Srdivacky NewCst = ConstantExpr::getShl(RHS, ShAmt); 1073202375Srdivacky 1074202375Srdivacky // Check to see if we are shifting out any of the bits being 1075202375Srdivacky // compared. 1076202375Srdivacky if (ConstantExpr::get(Shift->getOpcode(), 1077202375Srdivacky NewCst, ShAmt) != RHS) { 1078202375Srdivacky // If we shifted bits out, the fold is not going to work out. 1079202375Srdivacky // As a special case, check to see if this means that the 1080202375Srdivacky // result is always true or false now. 1081202375Srdivacky if (ICI.getPredicate() == ICmpInst::ICMP_EQ) 1082202375Srdivacky return ReplaceInstUsesWith(ICI, 1083202375Srdivacky ConstantInt::getFalse(ICI.getContext())); 1084202375Srdivacky if (ICI.getPredicate() == ICmpInst::ICMP_NE) 1085202375Srdivacky return ReplaceInstUsesWith(ICI, 1086202375Srdivacky ConstantInt::getTrue(ICI.getContext())); 1087202375Srdivacky } else { 1088202375Srdivacky ICI.setOperand(1, NewCst); 1089202375Srdivacky Constant *NewAndCST; 1090202375Srdivacky if (Shift->getOpcode() == Instruction::Shl) 1091202375Srdivacky NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt); 1092202375Srdivacky else 1093202375Srdivacky NewAndCST = ConstantExpr::getShl(AndCST, ShAmt); 1094202375Srdivacky LHSI->setOperand(1, NewAndCST); 1095202375Srdivacky LHSI->setOperand(0, Shift->getOperand(0)); 1096202375Srdivacky Worklist.Add(Shift); // Shift is dead. 1097202375Srdivacky return &ICI; 1098202375Srdivacky } 1099202375Srdivacky } 1100202375Srdivacky } 1101202375Srdivacky 1102202375Srdivacky // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is 1103202375Srdivacky // preferable because it allows the C<<Y expression to be hoisted out 1104202375Srdivacky // of a loop if Y is invariant and X is not. 1105202375Srdivacky if (Shift && Shift->hasOneUse() && RHSV == 0 && 1106202375Srdivacky ICI.isEquality() && !Shift->isArithmeticShift() && 1107202375Srdivacky !isa<Constant>(Shift->getOperand(0))) { 1108202375Srdivacky // Compute C << Y. 1109202375Srdivacky Value *NS; 1110202375Srdivacky if (Shift->getOpcode() == Instruction::LShr) { 1111202375Srdivacky NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp"); 1112202375Srdivacky } else { 1113202375Srdivacky // Insert a logical shift. 1114202375Srdivacky NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp"); 1115202375Srdivacky } 1116202375Srdivacky 1117202375Srdivacky // Compute X & (C << Y). 1118202375Srdivacky Value *NewAnd = 1119202375Srdivacky Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName()); 1120202375Srdivacky 1121202375Srdivacky ICI.setOperand(0, NewAnd); 1122202375Srdivacky return &ICI; 1123202375Srdivacky } 1124202375Srdivacky } 1125202375Srdivacky 1126202375Srdivacky // Try to optimize things like "A[i]&42 == 0" to index computations. 1127202375Srdivacky if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) { 1128202375Srdivacky if (GetElementPtrInst *GEP = 1129202375Srdivacky dyn_cast<GetElementPtrInst>(LI->getOperand(0))) 1130202375Srdivacky if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1131202375Srdivacky if (GV->isConstant() && GV->hasDefinitiveInitializer() && 1132202375Srdivacky !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) { 1133202375Srdivacky ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1)); 1134202375Srdivacky if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C)) 1135202375Srdivacky return Res; 1136202375Srdivacky } 1137202375Srdivacky } 1138202375Srdivacky break; 1139202375Srdivacky 1140202375Srdivacky case Instruction::Or: { 1141202375Srdivacky if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse()) 1142202375Srdivacky break; 1143202375Srdivacky Value *P, *Q; 1144202375Srdivacky if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { 1145202375Srdivacky // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 1146202375Srdivacky // -> and (icmp eq P, null), (icmp eq Q, null). 1147202375Srdivacky 1148202375Srdivacky Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P, 1149202375Srdivacky Constant::getNullValue(P->getType())); 1150202375Srdivacky Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q, 1151202375Srdivacky Constant::getNullValue(Q->getType())); 1152202375Srdivacky Instruction *Op; 1153202375Srdivacky if (ICI.getPredicate() == ICmpInst::ICMP_EQ) 1154202375Srdivacky Op = BinaryOperator::CreateAnd(ICIP, ICIQ); 1155202375Srdivacky else 1156202375Srdivacky Op = BinaryOperator::CreateOr(ICIP, ICIQ); 1157202375Srdivacky return Op; 1158202375Srdivacky } 1159202375Srdivacky break; 1160202375Srdivacky } 1161202375Srdivacky 1162202375Srdivacky case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI) 1163202375Srdivacky ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1164202375Srdivacky if (!ShAmt) break; 1165202375Srdivacky 1166202375Srdivacky uint32_t TypeBits = RHSV.getBitWidth(); 1167202375Srdivacky 1168202375Srdivacky // Check that the shift amount is in range. If not, don't perform 1169202375Srdivacky // undefined shifts. When the shift is visited it will be 1170202375Srdivacky // simplified. 1171202375Srdivacky if (ShAmt->uge(TypeBits)) 1172202375Srdivacky break; 1173202375Srdivacky 1174202375Srdivacky if (ICI.isEquality()) { 1175202375Srdivacky // If we are comparing against bits always shifted out, the 1176202375Srdivacky // comparison cannot succeed. 1177202375Srdivacky Constant *Comp = 1178202375Srdivacky ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), 1179202375Srdivacky ShAmt); 1180202375Srdivacky if (Comp != RHS) {// Comparing against a bit that we know is zero. 1181202375Srdivacky bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1182202375Srdivacky Constant *Cst = 1183202375Srdivacky ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE); 1184202375Srdivacky return ReplaceInstUsesWith(ICI, Cst); 1185202375Srdivacky } 1186202375Srdivacky 1187202375Srdivacky if (LHSI->hasOneUse()) { 1188202375Srdivacky // Otherwise strength reduce the shift into an and. 1189202375Srdivacky uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); 1190202375Srdivacky Constant *Mask = 1191202375Srdivacky ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits, 1192202375Srdivacky TypeBits-ShAmtVal)); 1193202375Srdivacky 1194202375Srdivacky Value *And = 1195202375Srdivacky Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask"); 1196202375Srdivacky return new ICmpInst(ICI.getPredicate(), And, 1197202375Srdivacky ConstantInt::get(ICI.getContext(), 1198202375Srdivacky RHSV.lshr(ShAmtVal))); 1199202375Srdivacky } 1200202375Srdivacky } 1201202375Srdivacky 1202202375Srdivacky // Otherwise, if this is a comparison of the sign bit, simplify to and/test. 1203202375Srdivacky bool TrueIfSigned = false; 1204202375Srdivacky if (LHSI->hasOneUse() && 1205202375Srdivacky isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) { 1206202375Srdivacky // (X << 31) <s 0 --> (X&1) != 0 1207202375Srdivacky Constant *Mask = ConstantInt::get(ICI.getContext(), APInt(TypeBits, 1) << 1208202375Srdivacky (TypeBits-ShAmt->getZExtValue()-1)); 1209202375Srdivacky Value *And = 1210202375Srdivacky Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask"); 1211202375Srdivacky return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, 1212202375Srdivacky And, Constant::getNullValue(And->getType())); 1213202375Srdivacky } 1214202375Srdivacky break; 1215202375Srdivacky } 1216202375Srdivacky 1217202375Srdivacky case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI) 1218202375Srdivacky case Instruction::AShr: { 1219202375Srdivacky // Only handle equality comparisons of shift-by-constant. 1220202375Srdivacky ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1221202375Srdivacky if (!ShAmt || !ICI.isEquality()) break; 1222202375Srdivacky 1223202375Srdivacky // Check that the shift amount is in range. If not, don't perform 1224202375Srdivacky // undefined shifts. When the shift is visited it will be 1225202375Srdivacky // simplified. 1226202375Srdivacky uint32_t TypeBits = RHSV.getBitWidth(); 1227202375Srdivacky if (ShAmt->uge(TypeBits)) 1228202375Srdivacky break; 1229202375Srdivacky 1230202375Srdivacky uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); 1231202375Srdivacky 1232202375Srdivacky // If we are comparing against bits always shifted out, the 1233202375Srdivacky // comparison cannot succeed. 1234202375Srdivacky APInt Comp = RHSV << ShAmtVal; 1235202375Srdivacky if (LHSI->getOpcode() == Instruction::LShr) 1236202375Srdivacky Comp = Comp.lshr(ShAmtVal); 1237202375Srdivacky else 1238202375Srdivacky Comp = Comp.ashr(ShAmtVal); 1239202375Srdivacky 1240202375Srdivacky if (Comp != RHSV) { // Comparing against a bit that we know is zero. 1241202375Srdivacky bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1242202375Srdivacky Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 1243202375Srdivacky IsICMP_NE); 1244202375Srdivacky return ReplaceInstUsesWith(ICI, Cst); 1245202375Srdivacky } 1246202375Srdivacky 1247202375Srdivacky // Otherwise, check to see if the bits shifted out are known to be zero. 1248202375Srdivacky // If so, we can compare against the unshifted value: 1249202375Srdivacky // (X & 4) >> 1 == 2 --> (X & 4) == 4. 1250202375Srdivacky if (LHSI->hasOneUse() && 1251202375Srdivacky MaskedValueIsZero(LHSI->getOperand(0), 1252202375Srdivacky APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) { 1253202375Srdivacky return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 1254202375Srdivacky ConstantExpr::getShl(RHS, ShAmt)); 1255202375Srdivacky } 1256202375Srdivacky 1257202375Srdivacky if (LHSI->hasOneUse()) { 1258202375Srdivacky // Otherwise strength reduce the shift into an and. 1259202375Srdivacky APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); 1260202375Srdivacky Constant *Mask = ConstantInt::get(ICI.getContext(), Val); 1261202375Srdivacky 1262202375Srdivacky Value *And = Builder->CreateAnd(LHSI->getOperand(0), 1263202375Srdivacky Mask, LHSI->getName()+".mask"); 1264202375Srdivacky return new ICmpInst(ICI.getPredicate(), And, 1265202375Srdivacky ConstantExpr::getShl(RHS, ShAmt)); 1266202375Srdivacky } 1267202375Srdivacky break; 1268202375Srdivacky } 1269202375Srdivacky 1270202375Srdivacky case Instruction::SDiv: 1271202375Srdivacky case Instruction::UDiv: 1272202375Srdivacky // Fold: icmp pred ([us]div X, C1), C2 -> range test 1273202375Srdivacky // Fold this div into the comparison, producing a range check. 1274202375Srdivacky // Determine, based on the divide type, what the range is being 1275202375Srdivacky // checked. If there is an overflow on the low or high side, remember 1276202375Srdivacky // it, otherwise compute the range [low, hi) bounding the new value. 1277202375Srdivacky // See: InsertRangeTest above for the kinds of replacements possible. 1278202375Srdivacky if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) 1279202375Srdivacky if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI), 1280202375Srdivacky DivRHS)) 1281202375Srdivacky return R; 1282202375Srdivacky break; 1283202375Srdivacky 1284202375Srdivacky case Instruction::Add: 1285202375Srdivacky // Fold: icmp pred (add X, C1), C2 1286202375Srdivacky if (!ICI.isEquality()) { 1287202375Srdivacky ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1288202375Srdivacky if (!LHSC) break; 1289202375Srdivacky const APInt &LHSV = LHSC->getValue(); 1290202375Srdivacky 1291202375Srdivacky ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV) 1292202375Srdivacky .subtract(LHSV); 1293202375Srdivacky 1294202375Srdivacky if (ICI.isSigned()) { 1295202375Srdivacky if (CR.getLower().isSignBit()) { 1296202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0), 1297202375Srdivacky ConstantInt::get(ICI.getContext(),CR.getUpper())); 1298202375Srdivacky } else if (CR.getUpper().isSignBit()) { 1299202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0), 1300202375Srdivacky ConstantInt::get(ICI.getContext(),CR.getLower())); 1301202375Srdivacky } 1302202375Srdivacky } else { 1303202375Srdivacky if (CR.getLower().isMinValue()) { 1304202375Srdivacky return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), 1305202375Srdivacky ConstantInt::get(ICI.getContext(),CR.getUpper())); 1306202375Srdivacky } else if (CR.getUpper().isMinValue()) { 1307202375Srdivacky return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), 1308202375Srdivacky ConstantInt::get(ICI.getContext(),CR.getLower())); 1309202375Srdivacky } 1310202375Srdivacky } 1311202375Srdivacky } 1312202375Srdivacky break; 1313202375Srdivacky } 1314202375Srdivacky 1315202375Srdivacky // Simplify icmp_eq and icmp_ne instructions with integer constant RHS. 1316202375Srdivacky if (ICI.isEquality()) { 1317202375Srdivacky bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1318202375Srdivacky 1319202375Srdivacky // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 1320202375Srdivacky // the second operand is a constant, simplify a bit. 1321202375Srdivacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) { 1322202375Srdivacky switch (BO->getOpcode()) { 1323202375Srdivacky case Instruction::SRem: 1324202375Srdivacky // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. 1325202375Srdivacky if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){ 1326202375Srdivacky const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue(); 1327202375Srdivacky if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) { 1328202375Srdivacky Value *NewRem = 1329202375Srdivacky Builder->CreateURem(BO->getOperand(0), BO->getOperand(1), 1330202375Srdivacky BO->getName()); 1331202375Srdivacky return new ICmpInst(ICI.getPredicate(), NewRem, 1332202375Srdivacky Constant::getNullValue(BO->getType())); 1333202375Srdivacky } 1334202375Srdivacky } 1335202375Srdivacky break; 1336202375Srdivacky case Instruction::Add: 1337202375Srdivacky // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. 1338202375Srdivacky if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1339202375Srdivacky if (BO->hasOneUse()) 1340202375Srdivacky return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1341202375Srdivacky ConstantExpr::getSub(RHS, BOp1C)); 1342202375Srdivacky } else if (RHSV == 0) { 1343202375Srdivacky // Replace ((add A, B) != 0) with (A != -B) if A or B is 1344202375Srdivacky // efficiently invertible, or if the add has just this one use. 1345202375Srdivacky Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); 1346202375Srdivacky 1347202375Srdivacky if (Value *NegVal = dyn_castNegVal(BOp1)) 1348202375Srdivacky return new ICmpInst(ICI.getPredicate(), BOp0, NegVal); 1349202375Srdivacky else if (Value *NegVal = dyn_castNegVal(BOp0)) 1350202375Srdivacky return new ICmpInst(ICI.getPredicate(), NegVal, BOp1); 1351202375Srdivacky else if (BO->hasOneUse()) { 1352202375Srdivacky Value *Neg = Builder->CreateNeg(BOp1); 1353202375Srdivacky Neg->takeName(BO); 1354202375Srdivacky return new ICmpInst(ICI.getPredicate(), BOp0, Neg); 1355202375Srdivacky } 1356202375Srdivacky } 1357202375Srdivacky break; 1358202375Srdivacky case Instruction::Xor: 1359202375Srdivacky // For the xor case, we can xor two constants together, eliminating 1360202375Srdivacky // the explicit xor. 1361202375Srdivacky if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) 1362202375Srdivacky return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1363202375Srdivacky ConstantExpr::getXor(RHS, BOC)); 1364202375Srdivacky 1365202375Srdivacky // FALLTHROUGH 1366202375Srdivacky case Instruction::Sub: 1367202375Srdivacky // Replace (([sub|xor] A, B) != 0) with (A != B) 1368202375Srdivacky if (RHSV == 0) 1369202375Srdivacky return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1370202375Srdivacky BO->getOperand(1)); 1371202375Srdivacky break; 1372202375Srdivacky 1373202375Srdivacky case Instruction::Or: 1374202375Srdivacky // If bits are being or'd in that are not present in the constant we 1375202375Srdivacky // are comparing against, then the comparison could never succeed! 1376202375Srdivacky if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) { 1377202375Srdivacky Constant *NotCI = ConstantExpr::getNot(RHS); 1378202375Srdivacky if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue()) 1379202375Srdivacky return ReplaceInstUsesWith(ICI, 1380202375Srdivacky ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 1381202375Srdivacky isICMP_NE)); 1382202375Srdivacky } 1383202375Srdivacky break; 1384202375Srdivacky 1385202375Srdivacky case Instruction::And: 1386202375Srdivacky if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1387202375Srdivacky // If bits are being compared against that are and'd out, then the 1388202375Srdivacky // comparison can never succeed! 1389202375Srdivacky if ((RHSV & ~BOC->getValue()) != 0) 1390202375Srdivacky return ReplaceInstUsesWith(ICI, 1391202375Srdivacky ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 1392202375Srdivacky isICMP_NE)); 1393202375Srdivacky 1394202375Srdivacky // If we have ((X & C) == C), turn it into ((X & C) != 0). 1395202375Srdivacky if (RHS == BOC && RHSV.isPowerOf2()) 1396202375Srdivacky return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : 1397202375Srdivacky ICmpInst::ICMP_NE, LHSI, 1398202375Srdivacky Constant::getNullValue(RHS->getType())); 1399202375Srdivacky 1400202375Srdivacky // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 1401202375Srdivacky if (BOC->getValue().isSignBit()) { 1402202375Srdivacky Value *X = BO->getOperand(0); 1403202375Srdivacky Constant *Zero = Constant::getNullValue(X->getType()); 1404202375Srdivacky ICmpInst::Predicate pred = isICMP_NE ? 1405202375Srdivacky ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; 1406202375Srdivacky return new ICmpInst(pred, X, Zero); 1407202375Srdivacky } 1408202375Srdivacky 1409202375Srdivacky // ((X & ~7) == 0) --> X < 8 1410202375Srdivacky if (RHSV == 0 && isHighOnes(BOC)) { 1411202375Srdivacky Value *X = BO->getOperand(0); 1412202375Srdivacky Constant *NegX = ConstantExpr::getNeg(BOC); 1413202375Srdivacky ICmpInst::Predicate pred = isICMP_NE ? 1414202375Srdivacky ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 1415202375Srdivacky return new ICmpInst(pred, X, NegX); 1416202375Srdivacky } 1417202375Srdivacky } 1418202375Srdivacky default: break; 1419202375Srdivacky } 1420202375Srdivacky } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) { 1421202375Srdivacky // Handle icmp {eq|ne} <intrinsic>, intcst. 1422202375Srdivacky switch (II->getIntrinsicID()) { 1423202375Srdivacky case Intrinsic::bswap: 1424202375Srdivacky Worklist.Add(II); 1425202375Srdivacky ICI.setOperand(0, II->getOperand(1)); 1426202375Srdivacky ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap())); 1427202375Srdivacky return &ICI; 1428202375Srdivacky case Intrinsic::ctlz: 1429202375Srdivacky case Intrinsic::cttz: 1430202375Srdivacky // ctz(A) == bitwidth(a) -> A == 0 and likewise for != 1431202375Srdivacky if (RHSV == RHS->getType()->getBitWidth()) { 1432202375Srdivacky Worklist.Add(II); 1433202375Srdivacky ICI.setOperand(0, II->getOperand(1)); 1434202375Srdivacky ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0)); 1435202375Srdivacky return &ICI; 1436202375Srdivacky } 1437202375Srdivacky break; 1438202375Srdivacky case Intrinsic::ctpop: 1439202375Srdivacky // popcount(A) == 0 -> A == 0 and likewise for != 1440202375Srdivacky if (RHS->isZero()) { 1441202375Srdivacky Worklist.Add(II); 1442202375Srdivacky ICI.setOperand(0, II->getOperand(1)); 1443202375Srdivacky ICI.setOperand(1, RHS); 1444202375Srdivacky return &ICI; 1445202375Srdivacky } 1446202375Srdivacky break; 1447202375Srdivacky default: 1448202375Srdivacky break; 1449202375Srdivacky } 1450202375Srdivacky } 1451202375Srdivacky } 1452202375Srdivacky return 0; 1453202375Srdivacky} 1454202375Srdivacky 1455202375Srdivacky/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst). 1456202375Srdivacky/// We only handle extending casts so far. 1457202375Srdivacky/// 1458202375SrdivackyInstruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) { 1459202375Srdivacky const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0)); 1460202375Srdivacky Value *LHSCIOp = LHSCI->getOperand(0); 1461202375Srdivacky const Type *SrcTy = LHSCIOp->getType(); 1462202375Srdivacky const Type *DestTy = LHSCI->getType(); 1463202375Srdivacky Value *RHSCIOp; 1464202375Srdivacky 1465202375Srdivacky // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 1466202375Srdivacky // integer type is the same size as the pointer type. 1467202375Srdivacky if (TD && LHSCI->getOpcode() == Instruction::PtrToInt && 1468202375Srdivacky TD->getPointerSizeInBits() == 1469202375Srdivacky cast<IntegerType>(DestTy)->getBitWidth()) { 1470202375Srdivacky Value *RHSOp = 0; 1471202375Srdivacky if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) { 1472202375Srdivacky RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); 1473202375Srdivacky } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) { 1474202375Srdivacky RHSOp = RHSC->getOperand(0); 1475202375Srdivacky // If the pointer types don't match, insert a bitcast. 1476202375Srdivacky if (LHSCIOp->getType() != RHSOp->getType()) 1477202375Srdivacky RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType()); 1478202375Srdivacky } 1479202375Srdivacky 1480202375Srdivacky if (RHSOp) 1481202375Srdivacky return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp); 1482202375Srdivacky } 1483202375Srdivacky 1484202375Srdivacky // The code below only handles extension cast instructions, so far. 1485202375Srdivacky // Enforce this. 1486202375Srdivacky if (LHSCI->getOpcode() != Instruction::ZExt && 1487202375Srdivacky LHSCI->getOpcode() != Instruction::SExt) 1488202375Srdivacky return 0; 1489202375Srdivacky 1490202375Srdivacky bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; 1491202375Srdivacky bool isSignedCmp = ICI.isSigned(); 1492202375Srdivacky 1493202375Srdivacky if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) { 1494202375Srdivacky // Not an extension from the same type? 1495202375Srdivacky RHSCIOp = CI->getOperand(0); 1496202375Srdivacky if (RHSCIOp->getType() != LHSCIOp->getType()) 1497202375Srdivacky return 0; 1498202375Srdivacky 1499202375Srdivacky // If the signedness of the two casts doesn't agree (i.e. one is a sext 1500202375Srdivacky // and the other is a zext), then we can't handle this. 1501202375Srdivacky if (CI->getOpcode() != LHSCI->getOpcode()) 1502202375Srdivacky return 0; 1503202375Srdivacky 1504202375Srdivacky // Deal with equality cases early. 1505202375Srdivacky if (ICI.isEquality()) 1506202375Srdivacky return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); 1507202375Srdivacky 1508202375Srdivacky // A signed comparison of sign extended values simplifies into a 1509202375Srdivacky // signed comparison. 1510202375Srdivacky if (isSignedCmp && isSignedExt) 1511202375Srdivacky return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); 1512202375Srdivacky 1513202375Srdivacky // The other three cases all fold into an unsigned comparison. 1514202375Srdivacky return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp); 1515202375Srdivacky } 1516202375Srdivacky 1517202375Srdivacky // If we aren't dealing with a constant on the RHS, exit early 1518202375Srdivacky ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1)); 1519202375Srdivacky if (!CI) 1520202375Srdivacky return 0; 1521202375Srdivacky 1522202375Srdivacky // Compute the constant that would happen if we truncated to SrcTy then 1523202375Srdivacky // reextended to DestTy. 1524202375Srdivacky Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy); 1525202375Srdivacky Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), 1526202375Srdivacky Res1, DestTy); 1527202375Srdivacky 1528202375Srdivacky // If the re-extended constant didn't change... 1529202375Srdivacky if (Res2 == CI) { 1530202375Srdivacky // Deal with equality cases early. 1531202375Srdivacky if (ICI.isEquality()) 1532202375Srdivacky return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1); 1533202375Srdivacky 1534202375Srdivacky // A signed comparison of sign extended values simplifies into a 1535202375Srdivacky // signed comparison. 1536202375Srdivacky if (isSignedExt && isSignedCmp) 1537202375Srdivacky return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1); 1538202375Srdivacky 1539202375Srdivacky // The other three cases all fold into an unsigned comparison. 1540202375Srdivacky return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1); 1541202375Srdivacky } 1542202375Srdivacky 1543202375Srdivacky // The re-extended constant changed so the constant cannot be represented 1544202375Srdivacky // in the shorter type. Consequently, we cannot emit a simple comparison. 1545202375Srdivacky 1546202375Srdivacky // First, handle some easy cases. We know the result cannot be equal at this 1547202375Srdivacky // point so handle the ICI.isEquality() cases 1548202375Srdivacky if (ICI.getPredicate() == ICmpInst::ICMP_EQ) 1549202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext())); 1550202375Srdivacky if (ICI.getPredicate() == ICmpInst::ICMP_NE) 1551202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext())); 1552202375Srdivacky 1553202375Srdivacky // Evaluate the comparison for LT (we invert for GT below). LE and GE cases 1554202375Srdivacky // should have been folded away previously and not enter in here. 1555202375Srdivacky Value *Result; 1556202375Srdivacky if (isSignedCmp) { 1557202375Srdivacky // We're performing a signed comparison. 1558202375Srdivacky if (cast<ConstantInt>(CI)->getValue().isNegative()) 1559202375Srdivacky Result = ConstantInt::getFalse(ICI.getContext()); // X < (small) --> false 1560202375Srdivacky else 1561202375Srdivacky Result = ConstantInt::getTrue(ICI.getContext()); // X < (large) --> true 1562202375Srdivacky } else { 1563202375Srdivacky // We're performing an unsigned comparison. 1564202375Srdivacky if (isSignedExt) { 1565202375Srdivacky // We're performing an unsigned comp with a sign extended value. 1566202375Srdivacky // This is true if the input is >= 0. [aka >s -1] 1567202375Srdivacky Constant *NegOne = Constant::getAllOnesValue(SrcTy); 1568202375Srdivacky Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName()); 1569202375Srdivacky } else { 1570202375Srdivacky // Unsigned extend & unsigned compare -> always true. 1571202375Srdivacky Result = ConstantInt::getTrue(ICI.getContext()); 1572202375Srdivacky } 1573202375Srdivacky } 1574202375Srdivacky 1575202375Srdivacky // Finally, return the value computed. 1576202375Srdivacky if (ICI.getPredicate() == ICmpInst::ICMP_ULT || 1577202375Srdivacky ICI.getPredicate() == ICmpInst::ICMP_SLT) 1578202375Srdivacky return ReplaceInstUsesWith(ICI, Result); 1579202375Srdivacky 1580202375Srdivacky assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 1581202375Srdivacky ICI.getPredicate()==ICmpInst::ICMP_SGT) && 1582202375Srdivacky "ICmp should be folded!"); 1583202375Srdivacky if (Constant *CI = dyn_cast<Constant>(Result)) 1584202375Srdivacky return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI)); 1585202375Srdivacky return BinaryOperator::CreateNot(Result); 1586202375Srdivacky} 1587202375Srdivacky 1588202375Srdivacky 1589202375Srdivacky 1590202375SrdivackyInstruction *InstCombiner::visitICmpInst(ICmpInst &I) { 1591202375Srdivacky bool Changed = false; 1592202375Srdivacky 1593202375Srdivacky /// Orders the operands of the compare so that they are listed from most 1594202375Srdivacky /// complex to least complex. This puts constants before unary operators, 1595202375Srdivacky /// before binary operators. 1596202375Srdivacky if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 1597202375Srdivacky I.swapOperands(); 1598202375Srdivacky Changed = true; 1599202375Srdivacky } 1600202375Srdivacky 1601202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1602202375Srdivacky 1603202375Srdivacky if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD)) 1604202375Srdivacky return ReplaceInstUsesWith(I, V); 1605202375Srdivacky 1606202375Srdivacky const Type *Ty = Op0->getType(); 1607202375Srdivacky 1608202375Srdivacky // icmp's with boolean values can always be turned into bitwise operations 1609202375Srdivacky if (Ty == Type::getInt1Ty(I.getContext())) { 1610202375Srdivacky switch (I.getPredicate()) { 1611202375Srdivacky default: llvm_unreachable("Invalid icmp instruction!"); 1612202375Srdivacky case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B) 1613202375Srdivacky Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp"); 1614202375Srdivacky return BinaryOperator::CreateNot(Xor); 1615202375Srdivacky } 1616202375Srdivacky case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B 1617202375Srdivacky return BinaryOperator::CreateXor(Op0, Op1); 1618202375Srdivacky 1619202375Srdivacky case ICmpInst::ICMP_UGT: 1620202375Srdivacky std::swap(Op0, Op1); // Change icmp ugt -> icmp ult 1621202375Srdivacky // FALL THROUGH 1622202375Srdivacky case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B 1623202375Srdivacky Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp"); 1624202375Srdivacky return BinaryOperator::CreateAnd(Not, Op1); 1625202375Srdivacky } 1626202375Srdivacky case ICmpInst::ICMP_SGT: 1627202375Srdivacky std::swap(Op0, Op1); // Change icmp sgt -> icmp slt 1628202375Srdivacky // FALL THROUGH 1629202375Srdivacky case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B 1630202375Srdivacky Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp"); 1631202375Srdivacky return BinaryOperator::CreateAnd(Not, Op0); 1632202375Srdivacky } 1633202375Srdivacky case ICmpInst::ICMP_UGE: 1634202375Srdivacky std::swap(Op0, Op1); // Change icmp uge -> icmp ule 1635202375Srdivacky // FALL THROUGH 1636202375Srdivacky case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B 1637202375Srdivacky Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp"); 1638202375Srdivacky return BinaryOperator::CreateOr(Not, Op1); 1639202375Srdivacky } 1640202375Srdivacky case ICmpInst::ICMP_SGE: 1641202375Srdivacky std::swap(Op0, Op1); // Change icmp sge -> icmp sle 1642202375Srdivacky // FALL THROUGH 1643202375Srdivacky case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B 1644202375Srdivacky Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp"); 1645202375Srdivacky return BinaryOperator::CreateOr(Not, Op0); 1646202375Srdivacky } 1647202375Srdivacky } 1648202375Srdivacky } 1649202375Srdivacky 1650202375Srdivacky unsigned BitWidth = 0; 1651202375Srdivacky if (TD) 1652202375Srdivacky BitWidth = TD->getTypeSizeInBits(Ty->getScalarType()); 1653202375Srdivacky else if (Ty->isIntOrIntVector()) 1654202375Srdivacky BitWidth = Ty->getScalarSizeInBits(); 1655202375Srdivacky 1656202375Srdivacky bool isSignBit = false; 1657202375Srdivacky 1658202375Srdivacky // See if we are doing a comparison with a constant. 1659202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1660202375Srdivacky Value *A = 0, *B = 0; 1661202375Srdivacky 1662202375Srdivacky // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B) 1663202375Srdivacky if (I.isEquality() && CI->isZero() && 1664202375Srdivacky match(Op0, m_Sub(m_Value(A), m_Value(B)))) { 1665202375Srdivacky // (icmp cond A B) if cond is equality 1666202375Srdivacky return new ICmpInst(I.getPredicate(), A, B); 1667202375Srdivacky } 1668202375Srdivacky 1669202375Srdivacky // If we have an icmp le or icmp ge instruction, turn it into the 1670202375Srdivacky // appropriate icmp lt or icmp gt instruction. This allows us to rely on 1671202375Srdivacky // them being folded in the code below. The SimplifyICmpInst code has 1672202375Srdivacky // already handled the edge cases for us, so we just assert on them. 1673202375Srdivacky switch (I.getPredicate()) { 1674202375Srdivacky default: break; 1675202375Srdivacky case ICmpInst::ICMP_ULE: 1676202375Srdivacky assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE 1677202375Srdivacky return new ICmpInst(ICmpInst::ICMP_ULT, Op0, 1678202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()+1)); 1679202375Srdivacky case ICmpInst::ICMP_SLE: 1680202375Srdivacky assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE 1681202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SLT, Op0, 1682202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()+1)); 1683202375Srdivacky case ICmpInst::ICMP_UGE: 1684202375Srdivacky assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE 1685202375Srdivacky return new ICmpInst(ICmpInst::ICMP_UGT, Op0, 1686202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()-1)); 1687202375Srdivacky case ICmpInst::ICMP_SGE: 1688202375Srdivacky assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE 1689202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SGT, Op0, 1690202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()-1)); 1691202375Srdivacky } 1692202375Srdivacky 1693202375Srdivacky // If this comparison is a normal comparison, it demands all 1694202375Srdivacky // bits, if it is a sign bit comparison, it only demands the sign bit. 1695202375Srdivacky bool UnusedBit; 1696202375Srdivacky isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit); 1697202375Srdivacky } 1698202375Srdivacky 1699202375Srdivacky // See if we can fold the comparison based on range information we can get 1700202375Srdivacky // by checking whether bits are known to be zero or one in the input. 1701202375Srdivacky if (BitWidth != 0) { 1702202375Srdivacky APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0); 1703202375Srdivacky APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0); 1704202375Srdivacky 1705202375Srdivacky if (SimplifyDemandedBits(I.getOperandUse(0), 1706202375Srdivacky isSignBit ? APInt::getSignBit(BitWidth) 1707202375Srdivacky : APInt::getAllOnesValue(BitWidth), 1708202375Srdivacky Op0KnownZero, Op0KnownOne, 0)) 1709202375Srdivacky return &I; 1710202375Srdivacky if (SimplifyDemandedBits(I.getOperandUse(1), 1711202375Srdivacky APInt::getAllOnesValue(BitWidth), 1712202375Srdivacky Op1KnownZero, Op1KnownOne, 0)) 1713202375Srdivacky return &I; 1714202375Srdivacky 1715202375Srdivacky // Given the known and unknown bits, compute a range that the LHS could be 1716202375Srdivacky // in. Compute the Min, Max and RHS values based on the known bits. For the 1717202375Srdivacky // EQ and NE we use unsigned values. 1718202375Srdivacky APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); 1719202375Srdivacky APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); 1720202375Srdivacky if (I.isSigned()) { 1721202375Srdivacky ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, 1722202375Srdivacky Op0Min, Op0Max); 1723202375Srdivacky ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, 1724202375Srdivacky Op1Min, Op1Max); 1725202375Srdivacky } else { 1726202375Srdivacky ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, 1727202375Srdivacky Op0Min, Op0Max); 1728202375Srdivacky ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, 1729202375Srdivacky Op1Min, Op1Max); 1730202375Srdivacky } 1731202375Srdivacky 1732202375Srdivacky // If Min and Max are known to be the same, then SimplifyDemandedBits 1733202375Srdivacky // figured out that the LHS is a constant. Just constant fold this now so 1734202375Srdivacky // that code below can assume that Min != Max. 1735202375Srdivacky if (!isa<Constant>(Op0) && Op0Min == Op0Max) 1736202375Srdivacky return new ICmpInst(I.getPredicate(), 1737202375Srdivacky ConstantInt::get(I.getContext(), Op0Min), Op1); 1738202375Srdivacky if (!isa<Constant>(Op1) && Op1Min == Op1Max) 1739202375Srdivacky return new ICmpInst(I.getPredicate(), Op0, 1740202375Srdivacky ConstantInt::get(I.getContext(), Op1Min)); 1741202375Srdivacky 1742202375Srdivacky // Based on the range information we know about the LHS, see if we can 1743202375Srdivacky // simplify this comparison. For example, (x&4) < 8 is always true. 1744202375Srdivacky switch (I.getPredicate()) { 1745202375Srdivacky default: llvm_unreachable("Unknown icmp opcode!"); 1746202375Srdivacky case ICmpInst::ICMP_EQ: 1747202375Srdivacky if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) 1748202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1749202375Srdivacky break; 1750202375Srdivacky case ICmpInst::ICMP_NE: 1751202375Srdivacky if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) 1752202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1753202375Srdivacky break; 1754202375Srdivacky case ICmpInst::ICMP_ULT: 1755202375Srdivacky if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) 1756202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1757202375Srdivacky if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) 1758202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1759202375Srdivacky if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) 1760202375Srdivacky return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 1761202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1762202375Srdivacky if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C 1763202375Srdivacky return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 1764202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()-1)); 1765202375Srdivacky 1766202375Srdivacky // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear 1767202375Srdivacky if (CI->isMinValue(true)) 1768202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SGT, Op0, 1769202375Srdivacky Constant::getAllOnesValue(Op0->getType())); 1770202375Srdivacky } 1771202375Srdivacky break; 1772202375Srdivacky case ICmpInst::ICMP_UGT: 1773202375Srdivacky if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) 1774202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1775202375Srdivacky if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) 1776202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1777202375Srdivacky 1778202375Srdivacky if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) 1779202375Srdivacky return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 1780202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1781202375Srdivacky if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C 1782202375Srdivacky return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 1783202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()+1)); 1784202375Srdivacky 1785202375Srdivacky // (x >u 2147483647) -> (x <s 0) -> true if sign bit set 1786202375Srdivacky if (CI->isMaxValue(true)) 1787202375Srdivacky return new ICmpInst(ICmpInst::ICMP_SLT, Op0, 1788202375Srdivacky Constant::getNullValue(Op0->getType())); 1789202375Srdivacky } 1790202375Srdivacky break; 1791202375Srdivacky case ICmpInst::ICMP_SLT: 1792202375Srdivacky if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) 1793202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1794202375Srdivacky if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) 1795202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1796202375Srdivacky if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) 1797202375Srdivacky return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 1798202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1799202375Srdivacky if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C 1800202375Srdivacky return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 1801202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()-1)); 1802202375Srdivacky } 1803202375Srdivacky break; 1804202375Srdivacky case ICmpInst::ICMP_SGT: 1805202375Srdivacky if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) 1806202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1807202375Srdivacky if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) 1808202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1809202375Srdivacky 1810202375Srdivacky if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) 1811202375Srdivacky return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 1812202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1813202375Srdivacky if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C 1814202375Srdivacky return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 1815202375Srdivacky ConstantInt::get(CI->getContext(), CI->getValue()+1)); 1816202375Srdivacky } 1817202375Srdivacky break; 1818202375Srdivacky case ICmpInst::ICMP_SGE: 1819202375Srdivacky assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); 1820202375Srdivacky if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) 1821202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1822202375Srdivacky if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) 1823202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1824202375Srdivacky break; 1825202375Srdivacky case ICmpInst::ICMP_SLE: 1826202375Srdivacky assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); 1827202375Srdivacky if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) 1828202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1829202375Srdivacky if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) 1830202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1831202375Srdivacky break; 1832202375Srdivacky case ICmpInst::ICMP_UGE: 1833202375Srdivacky assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); 1834202375Srdivacky if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) 1835202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1836202375Srdivacky if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) 1837202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1838202375Srdivacky break; 1839202375Srdivacky case ICmpInst::ICMP_ULE: 1840202375Srdivacky assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); 1841202375Srdivacky if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) 1842202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1843202375Srdivacky if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) 1844202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1845202375Srdivacky break; 1846202375Srdivacky } 1847202375Srdivacky 1848202375Srdivacky // Turn a signed comparison into an unsigned one if both operands 1849202375Srdivacky // are known to have the same sign. 1850202375Srdivacky if (I.isSigned() && 1851202375Srdivacky ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) || 1852202375Srdivacky (Op0KnownOne.isNegative() && Op1KnownOne.isNegative()))) 1853202375Srdivacky return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); 1854202375Srdivacky } 1855202375Srdivacky 1856202375Srdivacky // Test if the ICmpInst instruction is used exclusively by a select as 1857202375Srdivacky // part of a minimum or maximum operation. If so, refrain from doing 1858202375Srdivacky // any other folding. This helps out other analyses which understand 1859202375Srdivacky // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 1860202375Srdivacky // and CodeGen. And in this case, at least one of the comparison 1861202375Srdivacky // operands has at least one user besides the compare (the select), 1862202375Srdivacky // which would often largely negate the benefit of folding anyway. 1863202375Srdivacky if (I.hasOneUse()) 1864202375Srdivacky if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin())) 1865202375Srdivacky if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || 1866202375Srdivacky (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) 1867202375Srdivacky return 0; 1868202375Srdivacky 1869202375Srdivacky // See if we are doing a comparison between a constant and an instruction that 1870202375Srdivacky // can be folded into the comparison. 1871202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1872202375Srdivacky // Since the RHS is a ConstantInt (CI), if the left hand side is an 1873202375Srdivacky // instruction, see if that instruction also has constants so that the 1874202375Srdivacky // instruction can be folded into the icmp 1875202375Srdivacky if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 1876202375Srdivacky if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI)) 1877202375Srdivacky return Res; 1878202375Srdivacky } 1879202375Srdivacky 1880202375Srdivacky // Handle icmp with constant (but not simple integer constant) RHS 1881202375Srdivacky if (Constant *RHSC = dyn_cast<Constant>(Op1)) { 1882202375Srdivacky if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 1883202375Srdivacky switch (LHSI->getOpcode()) { 1884202375Srdivacky case Instruction::GetElementPtr: 1885202375Srdivacky // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null 1886202375Srdivacky if (RHSC->isNullValue() && 1887202375Srdivacky cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) 1888202375Srdivacky return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), 1889202375Srdivacky Constant::getNullValue(LHSI->getOperand(0)->getType())); 1890202375Srdivacky break; 1891202375Srdivacky case Instruction::PHI: 1892202375Srdivacky // Only fold icmp into the PHI if the phi and icmp are in the same 1893202375Srdivacky // block. If in the same block, we're encouraging jump threading. If 1894202375Srdivacky // not, we are just pessimizing the code by making an i1 phi. 1895202375Srdivacky if (LHSI->getParent() == I.getParent()) 1896202375Srdivacky if (Instruction *NV = FoldOpIntoPhi(I, true)) 1897202375Srdivacky return NV; 1898202375Srdivacky break; 1899202375Srdivacky case Instruction::Select: { 1900202375Srdivacky // If either operand of the select is a constant, we can fold the 1901202375Srdivacky // comparison into the select arms, which will cause one to be 1902202375Srdivacky // constant folded and the select turned into a bitwise or. 1903202375Srdivacky Value *Op1 = 0, *Op2 = 0; 1904202375Srdivacky if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) 1905202375Srdivacky Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 1906202375Srdivacky if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) 1907202375Srdivacky Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 1908202375Srdivacky 1909202375Srdivacky // We only want to perform this transformation if it will not lead to 1910202375Srdivacky // additional code. This is true if either both sides of the select 1911202375Srdivacky // fold to a constant (in which case the icmp is replaced with a select 1912202375Srdivacky // which will usually simplify) or this is the only user of the 1913202375Srdivacky // select (in which case we are trading a select+icmp for a simpler 1914202375Srdivacky // select+icmp). 1915202375Srdivacky if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) { 1916202375Srdivacky if (!Op1) 1917202375Srdivacky Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), 1918202375Srdivacky RHSC, I.getName()); 1919202375Srdivacky if (!Op2) 1920202375Srdivacky Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), 1921202375Srdivacky RHSC, I.getName()); 1922202375Srdivacky return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 1923202375Srdivacky } 1924202375Srdivacky break; 1925202375Srdivacky } 1926202375Srdivacky case Instruction::Call: 1927202375Srdivacky // If we have (malloc != null), and if the malloc has a single use, we 1928202375Srdivacky // can assume it is successful and remove the malloc. 1929202375Srdivacky if (isMalloc(LHSI) && LHSI->hasOneUse() && 1930202375Srdivacky isa<ConstantPointerNull>(RHSC)) { 1931202375Srdivacky // Need to explicitly erase malloc call here, instead of adding it to 1932202375Srdivacky // Worklist, because it won't get DCE'd from the Worklist since 1933202375Srdivacky // isInstructionTriviallyDead() returns false for function calls. 1934202375Srdivacky // It is OK to replace LHSI/MallocCall with Undef because the 1935202375Srdivacky // instruction that uses it will be erased via Worklist. 1936202375Srdivacky if (extractMallocCall(LHSI)) { 1937202375Srdivacky LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType())); 1938202375Srdivacky EraseInstFromFunction(*LHSI); 1939202375Srdivacky return ReplaceInstUsesWith(I, 1940202375Srdivacky ConstantInt::get(Type::getInt1Ty(I.getContext()), 1941202375Srdivacky !I.isTrueWhenEqual())); 1942202375Srdivacky } 1943202375Srdivacky if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI)) 1944202375Srdivacky if (MallocCall->hasOneUse()) { 1945202375Srdivacky MallocCall->replaceAllUsesWith( 1946202375Srdivacky UndefValue::get(MallocCall->getType())); 1947202375Srdivacky EraseInstFromFunction(*MallocCall); 1948202375Srdivacky Worklist.Add(LHSI); // The malloc's bitcast use. 1949202375Srdivacky return ReplaceInstUsesWith(I, 1950202375Srdivacky ConstantInt::get(Type::getInt1Ty(I.getContext()), 1951202375Srdivacky !I.isTrueWhenEqual())); 1952202375Srdivacky } 1953202375Srdivacky } 1954202375Srdivacky break; 1955202375Srdivacky case Instruction::IntToPtr: 1956202375Srdivacky // icmp pred inttoptr(X), null -> icmp pred X, 0 1957202375Srdivacky if (RHSC->isNullValue() && TD && 1958202375Srdivacky TD->getIntPtrType(RHSC->getContext()) == 1959202375Srdivacky LHSI->getOperand(0)->getType()) 1960202375Srdivacky return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), 1961202375Srdivacky Constant::getNullValue(LHSI->getOperand(0)->getType())); 1962202375Srdivacky break; 1963202375Srdivacky 1964202375Srdivacky case Instruction::Load: 1965202375Srdivacky // Try to optimize things like "A[i] > 4" to index computations. 1966202375Srdivacky if (GetElementPtrInst *GEP = 1967202375Srdivacky dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 1968202375Srdivacky if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1969202375Srdivacky if (GV->isConstant() && GV->hasDefinitiveInitializer() && 1970202375Srdivacky !cast<LoadInst>(LHSI)->isVolatile()) 1971202375Srdivacky if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) 1972202375Srdivacky return Res; 1973202375Srdivacky } 1974202375Srdivacky break; 1975202375Srdivacky } 1976202375Srdivacky } 1977202375Srdivacky 1978202375Srdivacky // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. 1979202375Srdivacky if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0)) 1980202375Srdivacky if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I)) 1981202375Srdivacky return NI; 1982202375Srdivacky if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) 1983202375Srdivacky if (Instruction *NI = FoldGEPICmp(GEP, Op0, 1984202375Srdivacky ICmpInst::getSwappedPredicate(I.getPredicate()), I)) 1985202375Srdivacky return NI; 1986202375Srdivacky 1987202375Srdivacky // Test to see if the operands of the icmp are casted versions of other 1988202375Srdivacky // values. If the ptr->ptr cast can be stripped off both arguments, we do so 1989202375Srdivacky // now. 1990202375Srdivacky if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) { 1991202375Srdivacky if (isa<PointerType>(Op0->getType()) && 1992202375Srdivacky (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 1993202375Srdivacky // We keep moving the cast from the left operand over to the right 1994202375Srdivacky // operand, where it can often be eliminated completely. 1995202375Srdivacky Op0 = CI->getOperand(0); 1996202375Srdivacky 1997202375Srdivacky // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast 1998202375Srdivacky // so eliminate it as well. 1999202375Srdivacky if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1)) 2000202375Srdivacky Op1 = CI2->getOperand(0); 2001202375Srdivacky 2002202375Srdivacky // If Op1 is a constant, we can fold the cast into the constant. 2003202375Srdivacky if (Op0->getType() != Op1->getType()) { 2004202375Srdivacky if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 2005202375Srdivacky Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType()); 2006202375Srdivacky } else { 2007202375Srdivacky // Otherwise, cast the RHS right before the icmp 2008202375Srdivacky Op1 = Builder->CreateBitCast(Op1, Op0->getType()); 2009202375Srdivacky } 2010202375Srdivacky } 2011202375Srdivacky return new ICmpInst(I.getPredicate(), Op0, Op1); 2012202375Srdivacky } 2013202375Srdivacky } 2014202375Srdivacky 2015202375Srdivacky if (isa<CastInst>(Op0)) { 2016202375Srdivacky // Handle the special case of: icmp (cast bool to X), <cst> 2017202375Srdivacky // This comes up when you have code like 2018202375Srdivacky // int X = A < B; 2019202375Srdivacky // if (X) ... 2020202375Srdivacky // For generality, we handle any zero-extension of any operand comparison 2021202375Srdivacky // with a constant or another cast from the same type. 2022202375Srdivacky if (isa<Constant>(Op1) || isa<CastInst>(Op1)) 2023202375Srdivacky if (Instruction *R = visitICmpInstWithCastAndCast(I)) 2024202375Srdivacky return R; 2025202375Srdivacky } 2026202375Srdivacky 2027202375Srdivacky // See if it's the same type of instruction on the left and right. 2028202375Srdivacky if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) { 2029202375Srdivacky if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) { 2030202375Srdivacky if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() && 2031202375Srdivacky Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) { 2032202375Srdivacky switch (Op0I->getOpcode()) { 2033202375Srdivacky default: break; 2034202375Srdivacky case Instruction::Add: 2035202375Srdivacky case Instruction::Sub: 2036202375Srdivacky case Instruction::Xor: 2037202375Srdivacky if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b 2038202375Srdivacky return new ICmpInst(I.getPredicate(), Op0I->getOperand(0), 2039202375Srdivacky Op1I->getOperand(0)); 2040202375Srdivacky // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b 2041202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) { 2042202375Srdivacky if (CI->getValue().isSignBit()) { 2043202375Srdivacky ICmpInst::Predicate Pred = I.isSigned() 2044202375Srdivacky ? I.getUnsignedPredicate() 2045202375Srdivacky : I.getSignedPredicate(); 2046202375Srdivacky return new ICmpInst(Pred, Op0I->getOperand(0), 2047202375Srdivacky Op1I->getOperand(0)); 2048202375Srdivacky } 2049202375Srdivacky 2050202375Srdivacky if (CI->getValue().isMaxSignedValue()) { 2051202375Srdivacky ICmpInst::Predicate Pred = I.isSigned() 2052202375Srdivacky ? I.getUnsignedPredicate() 2053202375Srdivacky : I.getSignedPredicate(); 2054202375Srdivacky Pred = I.getSwappedPredicate(Pred); 2055202375Srdivacky return new ICmpInst(Pred, Op0I->getOperand(0), 2056202375Srdivacky Op1I->getOperand(0)); 2057202375Srdivacky } 2058202375Srdivacky } 2059202375Srdivacky break; 2060202375Srdivacky case Instruction::Mul: 2061202375Srdivacky if (!I.isEquality()) 2062202375Srdivacky break; 2063202375Srdivacky 2064202375Srdivacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) { 2065202375Srdivacky // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask 2066202375Srdivacky // Mask = -1 >> count-trailing-zeros(Cst). 2067202375Srdivacky if (!CI->isZero() && !CI->isOne()) { 2068202375Srdivacky const APInt &AP = CI->getValue(); 2069202375Srdivacky ConstantInt *Mask = ConstantInt::get(I.getContext(), 2070202375Srdivacky APInt::getLowBitsSet(AP.getBitWidth(), 2071202375Srdivacky AP.getBitWidth() - 2072202375Srdivacky AP.countTrailingZeros())); 2073202375Srdivacky Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask); 2074202375Srdivacky Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask); 2075202375Srdivacky return new ICmpInst(I.getPredicate(), And1, And2); 2076202375Srdivacky } 2077202375Srdivacky } 2078202375Srdivacky break; 2079202375Srdivacky } 2080202375Srdivacky } 2081202375Srdivacky } 2082202375Srdivacky } 2083202375Srdivacky 2084202375Srdivacky // ~x < ~y --> y < x 2085202375Srdivacky { Value *A, *B; 2086202375Srdivacky if (match(Op0, m_Not(m_Value(A))) && 2087202375Srdivacky match(Op1, m_Not(m_Value(B)))) 2088202375Srdivacky return new ICmpInst(I.getPredicate(), B, A); 2089202375Srdivacky } 2090202375Srdivacky 2091202375Srdivacky if (I.isEquality()) { 2092202375Srdivacky Value *A, *B, *C, *D; 2093202375Srdivacky 2094202375Srdivacky // -x == -y --> x == y 2095202375Srdivacky if (match(Op0, m_Neg(m_Value(A))) && 2096202375Srdivacky match(Op1, m_Neg(m_Value(B)))) 2097202375Srdivacky return new ICmpInst(I.getPredicate(), A, B); 2098202375Srdivacky 2099202375Srdivacky if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { 2100202375Srdivacky if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 2101202375Srdivacky Value *OtherVal = A == Op1 ? B : A; 2102202375Srdivacky return new ICmpInst(I.getPredicate(), OtherVal, 2103202375Srdivacky Constant::getNullValue(A->getType())); 2104202375Srdivacky } 2105202375Srdivacky 2106202375Srdivacky if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { 2107202375Srdivacky // A^c1 == C^c2 --> A == C^(c1^c2) 2108202375Srdivacky ConstantInt *C1, *C2; 2109202375Srdivacky if (match(B, m_ConstantInt(C1)) && 2110202375Srdivacky match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) { 2111202375Srdivacky Constant *NC = ConstantInt::get(I.getContext(), 2112202375Srdivacky C1->getValue() ^ C2->getValue()); 2113202375Srdivacky Value *Xor = Builder->CreateXor(C, NC, "tmp"); 2114202375Srdivacky return new ICmpInst(I.getPredicate(), A, Xor); 2115202375Srdivacky } 2116202375Srdivacky 2117202375Srdivacky // A^B == A^D -> B == D 2118202375Srdivacky if (A == C) return new ICmpInst(I.getPredicate(), B, D); 2119202375Srdivacky if (A == D) return new ICmpInst(I.getPredicate(), B, C); 2120202375Srdivacky if (B == C) return new ICmpInst(I.getPredicate(), A, D); 2121202375Srdivacky if (B == D) return new ICmpInst(I.getPredicate(), A, C); 2122202375Srdivacky } 2123202375Srdivacky } 2124202375Srdivacky 2125202375Srdivacky if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && 2126202375Srdivacky (A == Op0 || B == Op0)) { 2127202375Srdivacky // A == (A^B) -> B == 0 2128202375Srdivacky Value *OtherVal = A == Op0 ? B : A; 2129202375Srdivacky return new ICmpInst(I.getPredicate(), OtherVal, 2130202375Srdivacky Constant::getNullValue(A->getType())); 2131202375Srdivacky } 2132202375Srdivacky 2133202375Srdivacky // (A-B) == A -> B == 0 2134202375Srdivacky if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)))) 2135202375Srdivacky return new ICmpInst(I.getPredicate(), B, 2136202375Srdivacky Constant::getNullValue(B->getType())); 2137202375Srdivacky 2138202375Srdivacky // A == (A-B) -> B == 0 2139202375Srdivacky if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)))) 2140202375Srdivacky return new ICmpInst(I.getPredicate(), B, 2141202375Srdivacky Constant::getNullValue(B->getType())); 2142202375Srdivacky 2143202375Srdivacky // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 2144202375Srdivacky if (Op0->hasOneUse() && Op1->hasOneUse() && 2145202375Srdivacky match(Op0, m_And(m_Value(A), m_Value(B))) && 2146202375Srdivacky match(Op1, m_And(m_Value(C), m_Value(D)))) { 2147202375Srdivacky Value *X = 0, *Y = 0, *Z = 0; 2148202375Srdivacky 2149202375Srdivacky if (A == C) { 2150202375Srdivacky X = B; Y = D; Z = A; 2151202375Srdivacky } else if (A == D) { 2152202375Srdivacky X = B; Y = C; Z = A; 2153202375Srdivacky } else if (B == C) { 2154202375Srdivacky X = A; Y = D; Z = B; 2155202375Srdivacky } else if (B == D) { 2156202375Srdivacky X = A; Y = C; Z = B; 2157202375Srdivacky } 2158202375Srdivacky 2159202375Srdivacky if (X) { // Build (X^Y) & Z 2160202375Srdivacky Op1 = Builder->CreateXor(X, Y, "tmp"); 2161202375Srdivacky Op1 = Builder->CreateAnd(Op1, Z, "tmp"); 2162202375Srdivacky I.setOperand(0, Op1); 2163202375Srdivacky I.setOperand(1, Constant::getNullValue(Op1->getType())); 2164202375Srdivacky return &I; 2165202375Srdivacky } 2166202375Srdivacky } 2167202375Srdivacky } 2168202375Srdivacky 2169202375Srdivacky { 2170202375Srdivacky Value *X; ConstantInt *Cst; 2171202375Srdivacky // icmp X+Cst, X 2172202375Srdivacky if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X) 2173202375Srdivacky return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0); 2174202375Srdivacky 2175202375Srdivacky // icmp X, X+Cst 2176202375Srdivacky if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X) 2177202375Srdivacky return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1); 2178202375Srdivacky } 2179202375Srdivacky return Changed ? &I : 0; 2180202375Srdivacky} 2181202375Srdivacky 2182202375Srdivacky 2183202375Srdivacky 2184202375Srdivacky 2185202375Srdivacky 2186202375Srdivacky 2187202375Srdivacky/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible. 2188202375Srdivacky/// 2189202375SrdivackyInstruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I, 2190202375Srdivacky Instruction *LHSI, 2191202375Srdivacky Constant *RHSC) { 2192202375Srdivacky if (!isa<ConstantFP>(RHSC)) return 0; 2193202375Srdivacky const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); 2194202375Srdivacky 2195202375Srdivacky // Get the width of the mantissa. We don't want to hack on conversions that 2196202375Srdivacky // might lose information from the integer, e.g. "i64 -> float" 2197202375Srdivacky int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); 2198202375Srdivacky if (MantissaWidth == -1) return 0; // Unknown. 2199202375Srdivacky 2200202375Srdivacky // Check to see that the input is converted from an integer type that is small 2201202375Srdivacky // enough that preserves all bits. TODO: check here for "known" sign bits. 2202202375Srdivacky // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. 2203202375Srdivacky unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits(); 2204202375Srdivacky 2205202375Srdivacky // If this is a uitofp instruction, we need an extra bit to hold the sign. 2206202375Srdivacky bool LHSUnsigned = isa<UIToFPInst>(LHSI); 2207202375Srdivacky if (LHSUnsigned) 2208202375Srdivacky ++InputSize; 2209202375Srdivacky 2210202375Srdivacky // If the conversion would lose info, don't hack on this. 2211202375Srdivacky if ((int)InputSize > MantissaWidth) 2212202375Srdivacky return 0; 2213202375Srdivacky 2214202375Srdivacky // Otherwise, we can potentially simplify the comparison. We know that it 2215202375Srdivacky // will always come through as an integer value and we know the constant is 2216202375Srdivacky // not a NAN (it would have been previously simplified). 2217202375Srdivacky assert(!RHS.isNaN() && "NaN comparison not already folded!"); 2218202375Srdivacky 2219202375Srdivacky ICmpInst::Predicate Pred; 2220202375Srdivacky switch (I.getPredicate()) { 2221202375Srdivacky default: llvm_unreachable("Unexpected predicate!"); 2222202375Srdivacky case FCmpInst::FCMP_UEQ: 2223202375Srdivacky case FCmpInst::FCMP_OEQ: 2224202375Srdivacky Pred = ICmpInst::ICMP_EQ; 2225202375Srdivacky break; 2226202375Srdivacky case FCmpInst::FCMP_UGT: 2227202375Srdivacky case FCmpInst::FCMP_OGT: 2228202375Srdivacky Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; 2229202375Srdivacky break; 2230202375Srdivacky case FCmpInst::FCMP_UGE: 2231202375Srdivacky case FCmpInst::FCMP_OGE: 2232202375Srdivacky Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; 2233202375Srdivacky break; 2234202375Srdivacky case FCmpInst::FCMP_ULT: 2235202375Srdivacky case FCmpInst::FCMP_OLT: 2236202375Srdivacky Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; 2237202375Srdivacky break; 2238202375Srdivacky case FCmpInst::FCMP_ULE: 2239202375Srdivacky case FCmpInst::FCMP_OLE: 2240202375Srdivacky Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; 2241202375Srdivacky break; 2242202375Srdivacky case FCmpInst::FCMP_UNE: 2243202375Srdivacky case FCmpInst::FCMP_ONE: 2244202375Srdivacky Pred = ICmpInst::ICMP_NE; 2245202375Srdivacky break; 2246202375Srdivacky case FCmpInst::FCMP_ORD: 2247202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2248202375Srdivacky case FCmpInst::FCMP_UNO: 2249202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2250202375Srdivacky } 2251202375Srdivacky 2252202375Srdivacky const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); 2253202375Srdivacky 2254202375Srdivacky // Now we know that the APFloat is a normal number, zero or inf. 2255202375Srdivacky 2256202375Srdivacky // See if the FP constant is too large for the integer. For example, 2257202375Srdivacky // comparing an i8 to 300.0. 2258202375Srdivacky unsigned IntWidth = IntTy->getScalarSizeInBits(); 2259202375Srdivacky 2260202375Srdivacky if (!LHSUnsigned) { 2261202375Srdivacky // If the RHS value is > SignedMax, fold the comparison. This handles +INF 2262202375Srdivacky // and large values. 2263202375Srdivacky APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false); 2264202375Srdivacky SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, 2265202375Srdivacky APFloat::rmNearestTiesToEven); 2266202375Srdivacky if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0 2267202375Srdivacky if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || 2268202375Srdivacky Pred == ICmpInst::ICMP_SLE) 2269202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2270202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2271202375Srdivacky } 2272202375Srdivacky } else { 2273202375Srdivacky // If the RHS value is > UnsignedMax, fold the comparison. This handles 2274202375Srdivacky // +INF and large values. 2275202375Srdivacky APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false); 2276202375Srdivacky UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, 2277202375Srdivacky APFloat::rmNearestTiesToEven); 2278202375Srdivacky if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0 2279202375Srdivacky if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || 2280202375Srdivacky Pred == ICmpInst::ICMP_ULE) 2281202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2282202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2283202375Srdivacky } 2284202375Srdivacky } 2285202375Srdivacky 2286202375Srdivacky if (!LHSUnsigned) { 2287202375Srdivacky // See if the RHS value is < SignedMin. 2288202375Srdivacky APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false); 2289202375Srdivacky SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, 2290202375Srdivacky APFloat::rmNearestTiesToEven); 2291202375Srdivacky if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0 2292202375Srdivacky if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || 2293202375Srdivacky Pred == ICmpInst::ICMP_SGE) 2294202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2295202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2296202375Srdivacky } 2297202375Srdivacky } 2298202375Srdivacky 2299202375Srdivacky // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or 2300202375Srdivacky // [0, UMAX], but it may still be fractional. See if it is fractional by 2301202375Srdivacky // casting the FP value to the integer value and back, checking for equality. 2302202375Srdivacky // Don't do this for zero, because -0.0 is not fractional. 2303202375Srdivacky Constant *RHSInt = LHSUnsigned 2304202375Srdivacky ? ConstantExpr::getFPToUI(RHSC, IntTy) 2305202375Srdivacky : ConstantExpr::getFPToSI(RHSC, IntTy); 2306202375Srdivacky if (!RHS.isZero()) { 2307202375Srdivacky bool Equal = LHSUnsigned 2308202375Srdivacky ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC 2309202375Srdivacky : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; 2310202375Srdivacky if (!Equal) { 2311202375Srdivacky // If we had a comparison against a fractional value, we have to adjust 2312202375Srdivacky // the compare predicate and sometimes the value. RHSC is rounded towards 2313202375Srdivacky // zero at this point. 2314202375Srdivacky switch (Pred) { 2315202375Srdivacky default: llvm_unreachable("Unexpected integer comparison!"); 2316202375Srdivacky case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true 2317202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2318202375Srdivacky case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false 2319202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2320202375Srdivacky case ICmpInst::ICMP_ULE: 2321202375Srdivacky // (float)int <= 4.4 --> int <= 4 2322202375Srdivacky // (float)int <= -4.4 --> false 2323202375Srdivacky if (RHS.isNegative()) 2324202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2325202375Srdivacky break; 2326202375Srdivacky case ICmpInst::ICMP_SLE: 2327202375Srdivacky // (float)int <= 4.4 --> int <= 4 2328202375Srdivacky // (float)int <= -4.4 --> int < -4 2329202375Srdivacky if (RHS.isNegative()) 2330202375Srdivacky Pred = ICmpInst::ICMP_SLT; 2331202375Srdivacky break; 2332202375Srdivacky case ICmpInst::ICMP_ULT: 2333202375Srdivacky // (float)int < -4.4 --> false 2334202375Srdivacky // (float)int < 4.4 --> int <= 4 2335202375Srdivacky if (RHS.isNegative()) 2336202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2337202375Srdivacky Pred = ICmpInst::ICMP_ULE; 2338202375Srdivacky break; 2339202375Srdivacky case ICmpInst::ICMP_SLT: 2340202375Srdivacky // (float)int < -4.4 --> int < -4 2341202375Srdivacky // (float)int < 4.4 --> int <= 4 2342202375Srdivacky if (!RHS.isNegative()) 2343202375Srdivacky Pred = ICmpInst::ICMP_SLE; 2344202375Srdivacky break; 2345202375Srdivacky case ICmpInst::ICMP_UGT: 2346202375Srdivacky // (float)int > 4.4 --> int > 4 2347202375Srdivacky // (float)int > -4.4 --> true 2348202375Srdivacky if (RHS.isNegative()) 2349202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2350202375Srdivacky break; 2351202375Srdivacky case ICmpInst::ICMP_SGT: 2352202375Srdivacky // (float)int > 4.4 --> int > 4 2353202375Srdivacky // (float)int > -4.4 --> int >= -4 2354202375Srdivacky if (RHS.isNegative()) 2355202375Srdivacky Pred = ICmpInst::ICMP_SGE; 2356202375Srdivacky break; 2357202375Srdivacky case ICmpInst::ICMP_UGE: 2358202375Srdivacky // (float)int >= -4.4 --> true 2359202375Srdivacky // (float)int >= 4.4 --> int > 4 2360202375Srdivacky if (!RHS.isNegative()) 2361202375Srdivacky return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2362202375Srdivacky Pred = ICmpInst::ICMP_UGT; 2363202375Srdivacky break; 2364202375Srdivacky case ICmpInst::ICMP_SGE: 2365202375Srdivacky // (float)int >= -4.4 --> int >= -4 2366202375Srdivacky // (float)int >= 4.4 --> int > 4 2367202375Srdivacky if (!RHS.isNegative()) 2368202375Srdivacky Pred = ICmpInst::ICMP_SGT; 2369202375Srdivacky break; 2370202375Srdivacky } 2371202375Srdivacky } 2372202375Srdivacky } 2373202375Srdivacky 2374202375Srdivacky // Lower this FP comparison into an appropriate integer version of the 2375202375Srdivacky // comparison. 2376202375Srdivacky return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); 2377202375Srdivacky} 2378202375Srdivacky 2379202375SrdivackyInstruction *InstCombiner::visitFCmpInst(FCmpInst &I) { 2380202375Srdivacky bool Changed = false; 2381202375Srdivacky 2382202375Srdivacky /// Orders the operands of the compare so that they are listed from most 2383202375Srdivacky /// complex to least complex. This puts constants before unary operators, 2384202375Srdivacky /// before binary operators. 2385202375Srdivacky if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 2386202375Srdivacky I.swapOperands(); 2387202375Srdivacky Changed = true; 2388202375Srdivacky } 2389202375Srdivacky 2390202375Srdivacky Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 2391202375Srdivacky 2392202375Srdivacky if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD)) 2393202375Srdivacky return ReplaceInstUsesWith(I, V); 2394202375Srdivacky 2395202375Srdivacky // Simplify 'fcmp pred X, X' 2396202375Srdivacky if (Op0 == Op1) { 2397202375Srdivacky switch (I.getPredicate()) { 2398202375Srdivacky default: llvm_unreachable("Unknown predicate!"); 2399202375Srdivacky case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) 2400202375Srdivacky case FCmpInst::FCMP_ULT: // True if unordered or less than 2401202375Srdivacky case FCmpInst::FCMP_UGT: // True if unordered or greater than 2402202375Srdivacky case FCmpInst::FCMP_UNE: // True if unordered or not equal 2403202375Srdivacky // Canonicalize these to be 'fcmp uno %X, 0.0'. 2404202375Srdivacky I.setPredicate(FCmpInst::FCMP_UNO); 2405202375Srdivacky I.setOperand(1, Constant::getNullValue(Op0->getType())); 2406202375Srdivacky return &I; 2407202375Srdivacky 2408202375Srdivacky case FCmpInst::FCMP_ORD: // True if ordered (no nans) 2409202375Srdivacky case FCmpInst::FCMP_OEQ: // True if ordered and equal 2410202375Srdivacky case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal 2411202375Srdivacky case FCmpInst::FCMP_OLE: // True if ordered and less than or equal 2412202375Srdivacky // Canonicalize these to be 'fcmp ord %X, 0.0'. 2413202375Srdivacky I.setPredicate(FCmpInst::FCMP_ORD); 2414202375Srdivacky I.setOperand(1, Constant::getNullValue(Op0->getType())); 2415202375Srdivacky return &I; 2416202375Srdivacky } 2417202375Srdivacky } 2418202375Srdivacky 2419202375Srdivacky // Handle fcmp with constant RHS 2420202375Srdivacky if (Constant *RHSC = dyn_cast<Constant>(Op1)) { 2421202375Srdivacky if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 2422202375Srdivacky switch (LHSI->getOpcode()) { 2423202375Srdivacky case Instruction::PHI: 2424202375Srdivacky // Only fold fcmp into the PHI if the phi and fcmp are in the same 2425202375Srdivacky // block. If in the same block, we're encouraging jump threading. If 2426202375Srdivacky // not, we are just pessimizing the code by making an i1 phi. 2427202375Srdivacky if (LHSI->getParent() == I.getParent()) 2428202375Srdivacky if (Instruction *NV = FoldOpIntoPhi(I, true)) 2429202375Srdivacky return NV; 2430202375Srdivacky break; 2431202375Srdivacky case Instruction::SIToFP: 2432202375Srdivacky case Instruction::UIToFP: 2433202375Srdivacky if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC)) 2434202375Srdivacky return NV; 2435202375Srdivacky break; 2436202375Srdivacky case Instruction::Select: { 2437202375Srdivacky // If either operand of the select is a constant, we can fold the 2438202375Srdivacky // comparison into the select arms, which will cause one to be 2439202375Srdivacky // constant folded and the select turned into a bitwise or. 2440202375Srdivacky Value *Op1 = 0, *Op2 = 0; 2441202375Srdivacky if (LHSI->hasOneUse()) { 2442202375Srdivacky if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { 2443202375Srdivacky // Fold the known value into the constant operand. 2444202375Srdivacky Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); 2445202375Srdivacky // Insert a new FCmp of the other select operand. 2446202375Srdivacky Op2 = Builder->CreateFCmp(I.getPredicate(), 2447202375Srdivacky LHSI->getOperand(2), RHSC, I.getName()); 2448202375Srdivacky } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { 2449202375Srdivacky // Fold the known value into the constant operand. 2450202375Srdivacky Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); 2451202375Srdivacky // Insert a new FCmp of the other select operand. 2452202375Srdivacky Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1), 2453202375Srdivacky RHSC, I.getName()); 2454202375Srdivacky } 2455202375Srdivacky } 2456202375Srdivacky 2457202375Srdivacky if (Op1) 2458202375Srdivacky return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 2459202375Srdivacky break; 2460202375Srdivacky } 2461202375Srdivacky case Instruction::Load: 2462202375Srdivacky if (GetElementPtrInst *GEP = 2463202375Srdivacky dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 2464202375Srdivacky if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 2465202375Srdivacky if (GV->isConstant() && GV->hasDefinitiveInitializer() && 2466202375Srdivacky !cast<LoadInst>(LHSI)->isVolatile()) 2467202375Srdivacky if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) 2468202375Srdivacky return Res; 2469202375Srdivacky } 2470202375Srdivacky break; 2471202375Srdivacky } 2472202375Srdivacky } 2473202375Srdivacky 2474202375Srdivacky return Changed ? &I : 0; 2475202375Srdivacky} 2476