InstCombineCompares.cpp revision b6c8cb442298c79b1319078b3038156466be0c40
1//===- InstCombineCompares.cpp --------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the visitICmp and visitFCmp functions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "InstCombine.h" 15#include "llvm/IntrinsicInst.h" 16#include "llvm/Analysis/InstructionSimplify.h" 17#include "llvm/Analysis/MemoryBuiltins.h" 18#include "llvm/Target/TargetData.h" 19#include "llvm/Support/ConstantRange.h" 20#include "llvm/Support/GetElementPtrTypeIterator.h" 21#include "llvm/Support/PatternMatch.h" 22using namespace llvm; 23using namespace PatternMatch; 24 25static ConstantInt *getOne(Constant *C) { 26 return ConstantInt::get(cast<IntegerType>(C->getType()), 1); 27} 28 29/// AddOne - Add one to a ConstantInt 30static Constant *AddOne(Constant *C) { 31 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1)); 32} 33/// SubOne - Subtract one from a ConstantInt 34static Constant *SubOne(Constant *C) { 35 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1)); 36} 37 38static ConstantInt *ExtractElement(Constant *V, Constant *Idx) { 39 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx)); 40} 41 42static bool HasAddOverflow(ConstantInt *Result, 43 ConstantInt *In1, ConstantInt *In2, 44 bool IsSigned) { 45 if (IsSigned) 46 if (In2->getValue().isNegative()) 47 return Result->getValue().sgt(In1->getValue()); 48 else 49 return Result->getValue().slt(In1->getValue()); 50 else 51 return Result->getValue().ult(In1->getValue()); 52} 53 54/// AddWithOverflow - Compute Result = In1+In2, returning true if the result 55/// overflowed for this type. 56static bool AddWithOverflow(Constant *&Result, Constant *In1, 57 Constant *In2, bool IsSigned = false) { 58 Result = ConstantExpr::getAdd(In1, In2); 59 60 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 61 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 63 if (HasAddOverflow(ExtractElement(Result, Idx), 64 ExtractElement(In1, Idx), 65 ExtractElement(In2, Idx), 66 IsSigned)) 67 return true; 68 } 69 return false; 70 } 71 72 return HasAddOverflow(cast<ConstantInt>(Result), 73 cast<ConstantInt>(In1), cast<ConstantInt>(In2), 74 IsSigned); 75} 76 77static bool HasSubOverflow(ConstantInt *Result, 78 ConstantInt *In1, ConstantInt *In2, 79 bool IsSigned) { 80 if (IsSigned) 81 if (In2->getValue().isNegative()) 82 return Result->getValue().slt(In1->getValue()); 83 else 84 return Result->getValue().sgt(In1->getValue()); 85 else 86 return Result->getValue().ugt(In1->getValue()); 87} 88 89/// SubWithOverflow - Compute Result = In1-In2, returning true if the result 90/// overflowed for this type. 91static bool SubWithOverflow(Constant *&Result, Constant *In1, 92 Constant *In2, bool IsSigned = false) { 93 Result = ConstantExpr::getSub(In1, In2); 94 95 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 96 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 98 if (HasSubOverflow(ExtractElement(Result, Idx), 99 ExtractElement(In1, Idx), 100 ExtractElement(In2, Idx), 101 IsSigned)) 102 return true; 103 } 104 return false; 105 } 106 107 return HasSubOverflow(cast<ConstantInt>(Result), 108 cast<ConstantInt>(In1), cast<ConstantInt>(In2), 109 IsSigned); 110} 111 112/// isSignBitCheck - Given an exploded icmp instruction, return true if the 113/// comparison only checks the sign bit. If it only checks the sign bit, set 114/// TrueIfSigned if the result of the comparison is true when the input value is 115/// signed. 116static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS, 117 bool &TrueIfSigned) { 118 switch (pred) { 119 case ICmpInst::ICMP_SLT: // True if LHS s< 0 120 TrueIfSigned = true; 121 return RHS->isZero(); 122 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 123 TrueIfSigned = true; 124 return RHS->isAllOnesValue(); 125 case ICmpInst::ICMP_SGT: // True if LHS s> -1 126 TrueIfSigned = false; 127 return RHS->isAllOnesValue(); 128 case ICmpInst::ICMP_UGT: 129 // True if LHS u> RHS and RHS == high-bit-mask - 1 130 TrueIfSigned = true; 131 return RHS->getValue() == 132 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits()); 133 case ICmpInst::ICMP_UGE: 134 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) 135 TrueIfSigned = true; 136 return RHS->getValue().isSignBit(); 137 default: 138 return false; 139 } 140} 141 142// isHighOnes - Return true if the constant is of the form 1+0+. 143// This is the same as lowones(~X). 144static bool isHighOnes(const ConstantInt *CI) { 145 return (~CI->getValue() + 1).isPowerOf2(); 146} 147 148/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 149/// set of known zero and one bits, compute the maximum and minimum values that 150/// could have the specified known zero and known one bits, returning them in 151/// min/max. 152static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero, 153 const APInt& KnownOne, 154 APInt& Min, APInt& Max) { 155 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && 156 KnownZero.getBitWidth() == Min.getBitWidth() && 157 KnownZero.getBitWidth() == Max.getBitWidth() && 158 "KnownZero, KnownOne and Min, Max must have equal bitwidth."); 159 APInt UnknownBits = ~(KnownZero|KnownOne); 160 161 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign 162 // bit if it is unknown. 163 Min = KnownOne; 164 Max = KnownOne|UnknownBits; 165 166 if (UnknownBits.isNegative()) { // Sign bit is unknown 167 Min.setBit(Min.getBitWidth()-1); 168 Max.clearBit(Max.getBitWidth()-1); 169 } 170} 171 172// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and 173// a set of known zero and one bits, compute the maximum and minimum values that 174// could have the specified known zero and known one bits, returning them in 175// min/max. 176static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero, 177 const APInt &KnownOne, 178 APInt &Min, APInt &Max) { 179 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && 180 KnownZero.getBitWidth() == Min.getBitWidth() && 181 KnownZero.getBitWidth() == Max.getBitWidth() && 182 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); 183 APInt UnknownBits = ~(KnownZero|KnownOne); 184 185 // The minimum value is when the unknown bits are all zeros. 186 Min = KnownOne; 187 // The maximum value is when the unknown bits are all ones. 188 Max = KnownOne|UnknownBits; 189} 190 191 192 193/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern: 194/// cmp pred (load (gep GV, ...)), cmpcst 195/// where GV is a global variable with a constant initializer. Try to simplify 196/// this into some simple computation that does not need the load. For example 197/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". 198/// 199/// If AndCst is non-null, then the loaded value is masked with that constant 200/// before doing the comparison. This handles cases like "A[i]&4 == 0". 201Instruction *InstCombiner:: 202FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, 203 CmpInst &ICI, ConstantInt *AndCst) { 204 // We need TD information to know the pointer size unless this is inbounds. 205 if (!GEP->isInBounds() && TD == 0) return 0; 206 207 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer()); 208 if (Init == 0 || Init->getNumOperands() > 1024) return 0; 209 210 // There are many forms of this optimization we can handle, for now, just do 211 // the simple index into a single-dimensional array. 212 // 213 // Require: GEP GV, 0, i {{, constant indices}} 214 if (GEP->getNumOperands() < 3 || 215 !isa<ConstantInt>(GEP->getOperand(1)) || 216 !cast<ConstantInt>(GEP->getOperand(1))->isZero() || 217 isa<Constant>(GEP->getOperand(2))) 218 return 0; 219 220 // Check that indices after the variable are constants and in-range for the 221 // type they index. Collect the indices. This is typically for arrays of 222 // structs. 223 SmallVector<unsigned, 4> LaterIndices; 224 225 const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType(); 226 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { 227 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 228 if (Idx == 0) return 0; // Variable index. 229 230 uint64_t IdxVal = Idx->getZExtValue(); 231 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index. 232 233 if (const StructType *STy = dyn_cast<StructType>(EltTy)) 234 EltTy = STy->getElementType(IdxVal); 235 else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { 236 if (IdxVal >= ATy->getNumElements()) return 0; 237 EltTy = ATy->getElementType(); 238 } else { 239 return 0; // Unknown type. 240 } 241 242 LaterIndices.push_back(IdxVal); 243 } 244 245 enum { Overdefined = -3, Undefined = -2 }; 246 247 // Variables for our state machines. 248 249 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form 250 // "i == 47 | i == 87", where 47 is the first index the condition is true for, 251 // and 87 is the second (and last) index. FirstTrueElement is -2 when 252 // undefined, otherwise set to the first true element. SecondTrueElement is 253 // -2 when undefined, -3 when overdefined and >= 0 when that index is true. 254 int FirstTrueElement = Undefined, SecondTrueElement = Undefined; 255 256 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the 257 // form "i != 47 & i != 87". Same state transitions as for true elements. 258 int FirstFalseElement = Undefined, SecondFalseElement = Undefined; 259 260 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these 261 /// define a state machine that triggers for ranges of values that the index 262 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. 263 /// This is -2 when undefined, -3 when overdefined, and otherwise the last 264 /// index in the range (inclusive). We use -2 for undefined here because we 265 /// use relative comparisons and don't want 0-1 to match -1. 266 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; 267 268 // MagicBitvector - This is a magic bitvector where we set a bit if the 269 // comparison is true for element 'i'. If there are 64 elements or less in 270 // the array, this will fully represent all the comparison results. 271 uint64_t MagicBitvector = 0; 272 273 274 // Scan the array and see if one of our patterns matches. 275 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); 276 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 277 Constant *Elt = Init->getOperand(i); 278 279 // If this is indexing an array of structures, get the structure element. 280 if (!LaterIndices.empty()) 281 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(), 282 LaterIndices.size()); 283 284 // If the element is masked, handle it. 285 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); 286 287 // Find out if the comparison would be true or false for the i'th element. 288 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, 289 CompareRHS, TD); 290 // If the result is undef for this element, ignore it. 291 if (isa<UndefValue>(C)) { 292 // Extend range state machines to cover this element in case there is an 293 // undef in the middle of the range. 294 if (TrueRangeEnd == (int)i-1) 295 TrueRangeEnd = i; 296 if (FalseRangeEnd == (int)i-1) 297 FalseRangeEnd = i; 298 continue; 299 } 300 301 // If we can't compute the result for any of the elements, we have to give 302 // up evaluating the entire conditional. 303 if (!isa<ConstantInt>(C)) return 0; 304 305 // Otherwise, we know if the comparison is true or false for this element, 306 // update our state machines. 307 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); 308 309 // State machine for single/double/range index comparison. 310 if (IsTrueForElt) { 311 // Update the TrueElement state machine. 312 if (FirstTrueElement == Undefined) 313 FirstTrueElement = TrueRangeEnd = i; // First true element. 314 else { 315 // Update double-compare state machine. 316 if (SecondTrueElement == Undefined) 317 SecondTrueElement = i; 318 else 319 SecondTrueElement = Overdefined; 320 321 // Update range state machine. 322 if (TrueRangeEnd == (int)i-1) 323 TrueRangeEnd = i; 324 else 325 TrueRangeEnd = Overdefined; 326 } 327 } else { 328 // Update the FalseElement state machine. 329 if (FirstFalseElement == Undefined) 330 FirstFalseElement = FalseRangeEnd = i; // First false element. 331 else { 332 // Update double-compare state machine. 333 if (SecondFalseElement == Undefined) 334 SecondFalseElement = i; 335 else 336 SecondFalseElement = Overdefined; 337 338 // Update range state machine. 339 if (FalseRangeEnd == (int)i-1) 340 FalseRangeEnd = i; 341 else 342 FalseRangeEnd = Overdefined; 343 } 344 } 345 346 347 // If this element is in range, update our magic bitvector. 348 if (i < 64 && IsTrueForElt) 349 MagicBitvector |= 1ULL << i; 350 351 // If all of our states become overdefined, bail out early. Since the 352 // predicate is expensive, only check it every 8 elements. This is only 353 // really useful for really huge arrays. 354 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && 355 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && 356 FalseRangeEnd == Overdefined) 357 return 0; 358 } 359 360 // Now that we've scanned the entire array, emit our new comparison(s). We 361 // order the state machines in complexity of the generated code. 362 Value *Idx = GEP->getOperand(2); 363 364 // If the index is larger than the pointer size of the target, truncate the 365 // index down like the GEP would do implicitly. We don't have to do this for 366 // an inbounds GEP because the index can't be out of range. 367 if (!GEP->isInBounds() && 368 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits()) 369 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext())); 370 371 // If the comparison is only true for one or two elements, emit direct 372 // comparisons. 373 if (SecondTrueElement != Overdefined) { 374 // None true -> false. 375 if (FirstTrueElement == Undefined) 376 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext())); 377 378 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); 379 380 // True for one element -> 'i == 47'. 381 if (SecondTrueElement == Undefined) 382 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); 383 384 // True for two elements -> 'i == 47 | i == 72'. 385 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx); 386 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); 387 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx); 388 return BinaryOperator::CreateOr(C1, C2); 389 } 390 391 // If the comparison is only false for one or two elements, emit direct 392 // comparisons. 393 if (SecondFalseElement != Overdefined) { 394 // None false -> true. 395 if (FirstFalseElement == Undefined) 396 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext())); 397 398 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); 399 400 // False for one element -> 'i != 47'. 401 if (SecondFalseElement == Undefined) 402 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); 403 404 // False for two elements -> 'i != 47 & i != 72'. 405 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx); 406 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); 407 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx); 408 return BinaryOperator::CreateAnd(C1, C2); 409 } 410 411 // If the comparison can be replaced with a range comparison for the elements 412 // where it is true, emit the range check. 413 if (TrueRangeEnd != Overdefined) { 414 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); 415 416 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). 417 if (FirstTrueElement) { 418 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); 419 Idx = Builder->CreateAdd(Idx, Offs); 420 } 421 422 Value *End = ConstantInt::get(Idx->getType(), 423 TrueRangeEnd-FirstTrueElement+1); 424 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); 425 } 426 427 // False range check. 428 if (FalseRangeEnd != Overdefined) { 429 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); 430 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). 431 if (FirstFalseElement) { 432 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); 433 Idx = Builder->CreateAdd(Idx, Offs); 434 } 435 436 Value *End = ConstantInt::get(Idx->getType(), 437 FalseRangeEnd-FirstFalseElement); 438 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); 439 } 440 441 442 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state 443 // of this load, replace it with computation that does: 444 // ((magic_cst >> i) & 1) != 0 445 if (Init->getNumOperands() <= 32 || 446 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) { 447 const Type *Ty; 448 if (Init->getNumOperands() <= 32) 449 Ty = Type::getInt32Ty(Init->getContext()); 450 else 451 Ty = Type::getInt64Ty(Init->getContext()); 452 Value *V = Builder->CreateIntCast(Idx, Ty, false); 453 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); 454 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); 455 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); 456 } 457 458 return 0; 459} 460 461 462/// EvaluateGEPOffsetExpression - Return a value that can be used to compare 463/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we 464/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can 465/// be complex, and scales are involved. The above expression would also be 466/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). 467/// This later form is less amenable to optimization though, and we are allowed 468/// to generate the first by knowing that pointer arithmetic doesn't overflow. 469/// 470/// If we can't emit an optimized form for this expression, this returns null. 471/// 472static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I, 473 InstCombiner &IC) { 474 TargetData &TD = *IC.getTargetData(); 475 gep_type_iterator GTI = gep_type_begin(GEP); 476 477 // Check to see if this gep only has a single variable index. If so, and if 478 // any constant indices are a multiple of its scale, then we can compute this 479 // in terms of the scale of the variable index. For example, if the GEP 480 // implies an offset of "12 + i*4", then we can codegen this as "3 + i", 481 // because the expression will cross zero at the same point. 482 unsigned i, e = GEP->getNumOperands(); 483 int64_t Offset = 0; 484 for (i = 1; i != e; ++i, ++GTI) { 485 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 486 // Compute the aggregate offset of constant indices. 487 if (CI->isZero()) continue; 488 489 // Handle a struct index, which adds its field offset to the pointer. 490 if (const StructType *STy = dyn_cast<StructType>(*GTI)) { 491 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 492 } else { 493 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); 494 Offset += Size*CI->getSExtValue(); 495 } 496 } else { 497 // Found our variable index. 498 break; 499 } 500 } 501 502 // If there are no variable indices, we must have a constant offset, just 503 // evaluate it the general way. 504 if (i == e) return 0; 505 506 Value *VariableIdx = GEP->getOperand(i); 507 // Determine the scale factor of the variable element. For example, this is 508 // 4 if the variable index is into an array of i32. 509 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType()); 510 511 // Verify that there are no other variable indices. If so, emit the hard way. 512 for (++i, ++GTI; i != e; ++i, ++GTI) { 513 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); 514 if (!CI) return 0; 515 516 // Compute the aggregate offset of constant indices. 517 if (CI->isZero()) continue; 518 519 // Handle a struct index, which adds its field offset to the pointer. 520 if (const StructType *STy = dyn_cast<StructType>(*GTI)) { 521 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 522 } else { 523 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); 524 Offset += Size*CI->getSExtValue(); 525 } 526 } 527 528 // Okay, we know we have a single variable index, which must be a 529 // pointer/array/vector index. If there is no offset, life is simple, return 530 // the index. 531 unsigned IntPtrWidth = TD.getPointerSizeInBits(); 532 if (Offset == 0) { 533 // Cast to intptrty in case a truncation occurs. If an extension is needed, 534 // we don't need to bother extending: the extension won't affect where the 535 // computation crosses zero. 536 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) 537 VariableIdx = new TruncInst(VariableIdx, 538 TD.getIntPtrType(VariableIdx->getContext()), 539 VariableIdx->getName(), &I); 540 return VariableIdx; 541 } 542 543 // Otherwise, there is an index. The computation we will do will be modulo 544 // the pointer size, so get it. 545 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); 546 547 Offset &= PtrSizeMask; 548 VariableScale &= PtrSizeMask; 549 550 // To do this transformation, any constant index must be a multiple of the 551 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", 552 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a 553 // multiple of the variable scale. 554 int64_t NewOffs = Offset / (int64_t)VariableScale; 555 if (Offset != NewOffs*(int64_t)VariableScale) 556 return 0; 557 558 // Okay, we can do this evaluation. Start by converting the index to intptr. 559 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext()); 560 if (VariableIdx->getType() != IntPtrTy) 561 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy, 562 true /*SExt*/, 563 VariableIdx->getName(), &I); 564 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); 565 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I); 566} 567 568/// FoldGEPICmp - Fold comparisons between a GEP instruction and something 569/// else. At this point we know that the GEP is on the LHS of the comparison. 570Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS, 571 ICmpInst::Predicate Cond, 572 Instruction &I) { 573 // Look through bitcasts. 574 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS)) 575 RHS = BCI->getOperand(0); 576 577 Value *PtrBase = GEPLHS->getOperand(0); 578 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) { 579 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). 580 // This transformation (ignoring the base and scales) is valid because we 581 // know pointers can't overflow since the gep is inbounds. See if we can 582 // output an optimized form. 583 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this); 584 585 // If not, synthesize the offset the hard way. 586 if (Offset == 0) 587 Offset = EmitGEPOffset(GEPLHS); 588 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, 589 Constant::getNullValue(Offset->getType())); 590 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { 591 // If the base pointers are different, but the indices are the same, just 592 // compare the base pointer. 593 if (PtrBase != GEPRHS->getOperand(0)) { 594 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); 595 IndicesTheSame &= GEPLHS->getOperand(0)->getType() == 596 GEPRHS->getOperand(0)->getType(); 597 if (IndicesTheSame) 598 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 599 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 600 IndicesTheSame = false; 601 break; 602 } 603 604 // If all indices are the same, just compare the base pointers. 605 if (IndicesTheSame) 606 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 607 GEPLHS->getOperand(0), GEPRHS->getOperand(0)); 608 609 // Otherwise, the base pointers are different and the indices are 610 // different, bail out. 611 return 0; 612 } 613 614 // If one of the GEPs has all zero indices, recurse. 615 bool AllZeros = true; 616 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 617 if (!isa<Constant>(GEPLHS->getOperand(i)) || 618 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) { 619 AllZeros = false; 620 break; 621 } 622 if (AllZeros) 623 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0), 624 ICmpInst::getSwappedPredicate(Cond), I); 625 626 // If the other GEP has all zero indices, recurse. 627 AllZeros = true; 628 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 629 if (!isa<Constant>(GEPRHS->getOperand(i)) || 630 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) { 631 AllZeros = false; 632 break; 633 } 634 if (AllZeros) 635 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); 636 637 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { 638 // If the GEPs only differ by one index, compare it. 639 unsigned NumDifferences = 0; // Keep track of # differences. 640 unsigned DiffOperand = 0; // The operand that differs. 641 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 642 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 643 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != 644 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { 645 // Irreconcilable differences. 646 NumDifferences = 2; 647 break; 648 } else { 649 if (NumDifferences++) break; 650 DiffOperand = i; 651 } 652 } 653 654 if (NumDifferences == 0) // SAME GEP? 655 return ReplaceInstUsesWith(I, // No comparison is needed here. 656 ConstantInt::get(Type::getInt1Ty(I.getContext()), 657 ICmpInst::isTrueWhenEqual(Cond))); 658 659 else if (NumDifferences == 1) { 660 Value *LHSV = GEPLHS->getOperand(DiffOperand); 661 Value *RHSV = GEPRHS->getOperand(DiffOperand); 662 // Make sure we do a signed comparison here. 663 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); 664 } 665 } 666 667 // Only lower this if the icmp is the only user of the GEP or if we expect 668 // the result to fold to a constant! 669 if (TD && 670 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && 671 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { 672 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) 673 Value *L = EmitGEPOffset(GEPLHS); 674 Value *R = EmitGEPOffset(GEPRHS); 675 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); 676 } 677 } 678 return 0; 679} 680 681/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X". 682Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI, 683 Value *X, ConstantInt *CI, 684 ICmpInst::Predicate Pred, 685 Value *TheAdd) { 686 // If we have X+0, exit early (simplifying logic below) and let it get folded 687 // elsewhere. icmp X+0, X -> icmp X, X 688 if (CI->isZero()) { 689 bool isTrue = ICmpInst::isTrueWhenEqual(Pred); 690 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue)); 691 } 692 693 // (X+4) == X -> false. 694 if (Pred == ICmpInst::ICMP_EQ) 695 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 696 697 // (X+4) != X -> true. 698 if (Pred == ICmpInst::ICMP_NE) 699 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 700 701 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info. 702 bool isNUW = false, isNSW = false; 703 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) { 704 isNUW = Add->hasNoUnsignedWrap(); 705 isNSW = Add->hasNoSignedWrap(); 706 } 707 708 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, 709 // so the values can never be equal. Similiarly for all other "or equals" 710 // operators. 711 712 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 713 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 714 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 715 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 716 // If this is an NUW add, then this is always false. 717 if (isNUW) 718 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 719 720 Value *R = 721 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI); 722 return new ICmpInst(ICmpInst::ICMP_UGT, X, R); 723 } 724 725 // (X+1) >u X --> X <u (0-1) --> X != 255 726 // (X+2) >u X --> X <u (0-2) --> X <u 254 727 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 728 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) { 729 // If this is an NUW add, then this is always true. 730 if (isNUW) 731 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 732 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI)); 733 } 734 735 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits(); 736 ConstantInt *SMax = ConstantInt::get(X->getContext(), 737 APInt::getSignedMaxValue(BitWidth)); 738 739 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 740 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 741 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 742 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 743 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 744 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 745 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) { 746 // If this is an NSW add, then we have two cases: if the constant is 747 // positive, then this is always false, if negative, this is always true. 748 if (isNSW) { 749 bool isTrue = CI->getValue().isNegative(); 750 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue)); 751 } 752 753 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI)); 754 } 755 756 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 757 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 758 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 759 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 760 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 761 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 762 763 // If this is an NSW add, then we have two cases: if the constant is 764 // positive, then this is always true, if negative, this is always false. 765 if (isNSW) { 766 bool isTrue = !CI->getValue().isNegative(); 767 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue)); 768 } 769 770 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); 771 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1); 772 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C)); 773} 774 775/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS 776/// and CmpRHS are both known to be integer constants. 777Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI, 778 ConstantInt *DivRHS) { 779 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1)); 780 const APInt &CmpRHSV = CmpRHS->getValue(); 781 782 // FIXME: If the operand types don't match the type of the divide 783 // then don't attempt this transform. The code below doesn't have the 784 // logic to deal with a signed divide and an unsigned compare (and 785 // vice versa). This is because (x /s C1) <s C2 produces different 786 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even 787 // (x /u C1) <u C2. Simply casting the operands and result won't 788 // work. :( The if statement below tests that condition and bails 789 // if it finds it. 790 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv; 791 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned()) 792 return 0; 793 if (DivRHS->isZero()) 794 return 0; // The ProdOV computation fails on divide by zero. 795 if (DivIsSigned && DivRHS->isAllOnesValue()) 796 return 0; // The overflow computation also screws up here 797 if (DivRHS->isOne()) 798 return 0; // Not worth bothering, and eliminates some funny cases 799 // with INT_MIN. 800 801 // Compute Prod = CI * DivRHS. We are essentially solving an equation 802 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 803 // C2 (CI). By solving for X we can turn this into a range check 804 // instead of computing a divide. 805 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS); 806 807 // Determine if the product overflows by seeing if the product is 808 // not equal to the divide. Make sure we do the same kind of divide 809 // as in the LHS instruction that we're folding. 810 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) : 811 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS; 812 813 // Get the ICmp opcode 814 ICmpInst::Predicate Pred = ICI.getPredicate(); 815 816 /// If the division is known to be exact, then there is no remainder from the 817 /// divide, so the covered range size is unit, otherwise it is the divisor. 818 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS; 819 820 // Figure out the interval that is being checked. For example, a comparison 821 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 822 // Compute this interval based on the constants involved and the signedness of 823 // the compare/divide. This computes a half-open interval, keeping track of 824 // whether either value in the interval overflows. After analysis each 825 // overflow variable is set to 0 if it's corresponding bound variable is valid 826 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. 827 int LoOverflow = 0, HiOverflow = 0; 828 Constant *LoBound = 0, *HiBound = 0; 829 830 if (!DivIsSigned) { // udiv 831 // e.g. X/5 op 3 --> [15, 20) 832 LoBound = Prod; 833 HiOverflow = LoOverflow = ProdOV; 834 if (!HiOverflow) { 835 // If this is not an exact divide, then many values in the range collapse 836 // to the same result value. 837 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false); 838 } 839 840 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0. 841 if (CmpRHSV == 0) { // (X / pos) op 0 842 // Can't overflow. e.g. X/2 op 0 --> [-1, 2) 843 LoBound = ConstantExpr::getNeg(SubOne(RangeSize)); 844 HiBound = RangeSize; 845 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos 846 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) 847 HiOverflow = LoOverflow = ProdOV; 848 if (!HiOverflow) 849 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true); 850 } else { // (X / pos) op neg 851 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) 852 HiBound = AddOne(Prod); 853 LoOverflow = HiOverflow = ProdOV ? -1 : 0; 854 if (!LoOverflow) { 855 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize)); 856 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; 857 } 858 } 859 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0. 860 if (DivI->isExact()) 861 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize)); 862 if (CmpRHSV == 0) { // (X / neg) op 0 863 // e.g. X/-5 op 0 --> [-4, 5) 864 LoBound = AddOne(RangeSize); 865 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize)); 866 if (HiBound == DivRHS) { // -INTMIN = INTMIN 867 HiOverflow = 1; // [INTMIN+1, overflow) 868 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN 869 } 870 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos 871 // e.g. X/-5 op 3 --> [-19, -14) 872 HiBound = AddOne(Prod); 873 HiOverflow = LoOverflow = ProdOV ? -1 : 0; 874 if (!LoOverflow) 875 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0; 876 } else { // (X / neg) op neg 877 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) 878 LoOverflow = HiOverflow = ProdOV; 879 if (!HiOverflow) 880 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true); 881 } 882 883 // Dividing by a negative swaps the condition. LT <-> GT 884 Pred = ICmpInst::getSwappedPredicate(Pred); 885 } 886 887 Value *X = DivI->getOperand(0); 888 switch (Pred) { 889 default: llvm_unreachable("Unhandled icmp opcode!"); 890 case ICmpInst::ICMP_EQ: 891 if (LoOverflow && HiOverflow) 892 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext())); 893 if (HiOverflow) 894 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 895 ICmpInst::ICMP_UGE, X, LoBound); 896 if (LoOverflow) 897 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 898 ICmpInst::ICMP_ULT, X, HiBound); 899 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound, 900 DivIsSigned, true)); 901 case ICmpInst::ICMP_NE: 902 if (LoOverflow && HiOverflow) 903 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext())); 904 if (HiOverflow) 905 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 906 ICmpInst::ICMP_ULT, X, LoBound); 907 if (LoOverflow) 908 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 909 ICmpInst::ICMP_UGE, X, HiBound); 910 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound, 911 DivIsSigned, false)); 912 case ICmpInst::ICMP_ULT: 913 case ICmpInst::ICMP_SLT: 914 if (LoOverflow == +1) // Low bound is greater than input range. 915 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext())); 916 if (LoOverflow == -1) // Low bound is less than input range. 917 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext())); 918 return new ICmpInst(Pred, X, LoBound); 919 case ICmpInst::ICMP_UGT: 920 case ICmpInst::ICMP_SGT: 921 if (HiOverflow == +1) // High bound greater than input range. 922 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext())); 923 if (HiOverflow == -1) // High bound less than input range. 924 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext())); 925 if (Pred == ICmpInst::ICMP_UGT) 926 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound); 927 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound); 928 } 929} 930 931 932/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)". 933/// 934Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI, 935 Instruction *LHSI, 936 ConstantInt *RHS) { 937 const APInt &RHSV = RHS->getValue(); 938 939 switch (LHSI->getOpcode()) { 940 case Instruction::Trunc: 941 if (ICI.isEquality() && LHSI->hasOneUse()) { 942 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all 943 // of the high bits truncated out of x are known. 944 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(), 945 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits(); 946 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits)); 947 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0); 948 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne); 949 950 // If all the high bits are known, we can do this xform. 951 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) { 952 // Pull in the high bits from known-ones set. 953 APInt NewRHS = RHS->getValue().zext(SrcBits); 954 NewRHS |= KnownOne; 955 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 956 ConstantInt::get(ICI.getContext(), NewRHS)); 957 } 958 } 959 break; 960 961 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI) 962 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) { 963 // If this is a comparison that tests the signbit (X < 0) or (x > -1), 964 // fold the xor. 965 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) || 966 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) { 967 Value *CompareVal = LHSI->getOperand(0); 968 969 // If the sign bit of the XorCST is not set, there is no change to 970 // the operation, just stop using the Xor. 971 if (!XorCST->getValue().isNegative()) { 972 ICI.setOperand(0, CompareVal); 973 Worklist.Add(LHSI); 974 return &ICI; 975 } 976 977 // Was the old condition true if the operand is positive? 978 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT; 979 980 // If so, the new one isn't. 981 isTrueIfPositive ^= true; 982 983 if (isTrueIfPositive) 984 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, 985 SubOne(RHS)); 986 else 987 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, 988 AddOne(RHS)); 989 } 990 991 if (LHSI->hasOneUse()) { 992 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit)) 993 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) { 994 const APInt &SignBit = XorCST->getValue(); 995 ICmpInst::Predicate Pred = ICI.isSigned() 996 ? ICI.getUnsignedPredicate() 997 : ICI.getSignedPredicate(); 998 return new ICmpInst(Pred, LHSI->getOperand(0), 999 ConstantInt::get(ICI.getContext(), 1000 RHSV ^ SignBit)); 1001 } 1002 1003 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A) 1004 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) { 1005 const APInt &NotSignBit = XorCST->getValue(); 1006 ICmpInst::Predicate Pred = ICI.isSigned() 1007 ? ICI.getUnsignedPredicate() 1008 : ICI.getSignedPredicate(); 1009 Pred = ICI.getSwappedPredicate(Pred); 1010 return new ICmpInst(Pred, LHSI->getOperand(0), 1011 ConstantInt::get(ICI.getContext(), 1012 RHSV ^ NotSignBit)); 1013 } 1014 } 1015 } 1016 break; 1017 case Instruction::And: // (icmp pred (and X, AndCST), RHS) 1018 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) && 1019 LHSI->getOperand(0)->hasOneUse()) { 1020 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1)); 1021 1022 // If the LHS is an AND of a truncating cast, we can widen the 1023 // and/compare to be the input width without changing the value 1024 // produced, eliminating a cast. 1025 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) { 1026 // We can do this transformation if either the AND constant does not 1027 // have its sign bit set or if it is an equality comparison. 1028 // Extending a relational comparison when we're checking the sign 1029 // bit would not work. 1030 if (Cast->hasOneUse() && 1031 (ICI.isEquality() || 1032 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) { 1033 uint32_t BitWidth = 1034 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth(); 1035 APInt NewCST = AndCST->getValue().zext(BitWidth); 1036 APInt NewCI = RHSV.zext(BitWidth); 1037 Value *NewAnd = 1038 Builder->CreateAnd(Cast->getOperand(0), 1039 ConstantInt::get(ICI.getContext(), NewCST), 1040 LHSI->getName()); 1041 return new ICmpInst(ICI.getPredicate(), NewAnd, 1042 ConstantInt::get(ICI.getContext(), NewCI)); 1043 } 1044 } 1045 1046 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare 1047 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This 1048 // happens a LOT in code produced by the C front-end, for bitfield 1049 // access. 1050 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0)); 1051 if (Shift && !Shift->isShift()) 1052 Shift = 0; 1053 1054 ConstantInt *ShAmt; 1055 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0; 1056 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift. 1057 const Type *AndTy = AndCST->getType(); // Type of the and. 1058 1059 // We can fold this as long as we can't shift unknown bits 1060 // into the mask. This can only happen with signed shift 1061 // rights, as they sign-extend. 1062 if (ShAmt) { 1063 bool CanFold = Shift->isLogicalShift(); 1064 if (!CanFold) { 1065 // To test for the bad case of the signed shr, see if any 1066 // of the bits shifted in could be tested after the mask. 1067 uint32_t TyBits = Ty->getPrimitiveSizeInBits(); 1068 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits); 1069 1070 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits(); 1071 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 1072 AndCST->getValue()) == 0) 1073 CanFold = true; 1074 } 1075 1076 if (CanFold) { 1077 Constant *NewCst; 1078 if (Shift->getOpcode() == Instruction::Shl) 1079 NewCst = ConstantExpr::getLShr(RHS, ShAmt); 1080 else 1081 NewCst = ConstantExpr::getShl(RHS, ShAmt); 1082 1083 // Check to see if we are shifting out any of the bits being 1084 // compared. 1085 if (ConstantExpr::get(Shift->getOpcode(), 1086 NewCst, ShAmt) != RHS) { 1087 // If we shifted bits out, the fold is not going to work out. 1088 // As a special case, check to see if this means that the 1089 // result is always true or false now. 1090 if (ICI.getPredicate() == ICmpInst::ICMP_EQ) 1091 return ReplaceInstUsesWith(ICI, 1092 ConstantInt::getFalse(ICI.getContext())); 1093 if (ICI.getPredicate() == ICmpInst::ICMP_NE) 1094 return ReplaceInstUsesWith(ICI, 1095 ConstantInt::getTrue(ICI.getContext())); 1096 } else { 1097 ICI.setOperand(1, NewCst); 1098 Constant *NewAndCST; 1099 if (Shift->getOpcode() == Instruction::Shl) 1100 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt); 1101 else 1102 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt); 1103 LHSI->setOperand(1, NewAndCST); 1104 LHSI->setOperand(0, Shift->getOperand(0)); 1105 Worklist.Add(Shift); // Shift is dead. 1106 return &ICI; 1107 } 1108 } 1109 } 1110 1111 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is 1112 // preferable because it allows the C<<Y expression to be hoisted out 1113 // of a loop if Y is invariant and X is not. 1114 if (Shift && Shift->hasOneUse() && RHSV == 0 && 1115 ICI.isEquality() && !Shift->isArithmeticShift() && 1116 !isa<Constant>(Shift->getOperand(0))) { 1117 // Compute C << Y. 1118 Value *NS; 1119 if (Shift->getOpcode() == Instruction::LShr) { 1120 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp"); 1121 } else { 1122 // Insert a logical shift. 1123 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp"); 1124 } 1125 1126 // Compute X & (C << Y). 1127 Value *NewAnd = 1128 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName()); 1129 1130 ICI.setOperand(0, NewAnd); 1131 return &ICI; 1132 } 1133 } 1134 1135 // Try to optimize things like "A[i]&42 == 0" to index computations. 1136 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) { 1137 if (GetElementPtrInst *GEP = 1138 dyn_cast<GetElementPtrInst>(LI->getOperand(0))) 1139 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1140 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 1141 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) { 1142 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1)); 1143 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C)) 1144 return Res; 1145 } 1146 } 1147 break; 1148 1149 case Instruction::Or: { 1150 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse()) 1151 break; 1152 Value *P, *Q; 1153 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { 1154 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 1155 // -> and (icmp eq P, null), (icmp eq Q, null). 1156 1157 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P, 1158 Constant::getNullValue(P->getType())); 1159 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q, 1160 Constant::getNullValue(Q->getType())); 1161 Instruction *Op; 1162 if (ICI.getPredicate() == ICmpInst::ICMP_EQ) 1163 Op = BinaryOperator::CreateAnd(ICIP, ICIQ); 1164 else 1165 Op = BinaryOperator::CreateOr(ICIP, ICIQ); 1166 return Op; 1167 } 1168 break; 1169 } 1170 1171 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI) 1172 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1173 if (!ShAmt) break; 1174 1175 uint32_t TypeBits = RHSV.getBitWidth(); 1176 1177 // Check that the shift amount is in range. If not, don't perform 1178 // undefined shifts. When the shift is visited it will be 1179 // simplified. 1180 if (ShAmt->uge(TypeBits)) 1181 break; 1182 1183 if (ICI.isEquality()) { 1184 // If we are comparing against bits always shifted out, the 1185 // comparison cannot succeed. 1186 Constant *Comp = 1187 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), 1188 ShAmt); 1189 if (Comp != RHS) {// Comparing against a bit that we know is zero. 1190 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1191 Constant *Cst = 1192 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE); 1193 return ReplaceInstUsesWith(ICI, Cst); 1194 } 1195 1196 // If the shift is NUW, then it is just shifting out zeros, no need for an 1197 // AND. 1198 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap()) 1199 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 1200 ConstantExpr::getLShr(RHS, ShAmt)); 1201 1202 if (LHSI->hasOneUse()) { 1203 // Otherwise strength reduce the shift into an and. 1204 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); 1205 Constant *Mask = 1206 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits, 1207 TypeBits-ShAmtVal)); 1208 1209 Value *And = 1210 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask"); 1211 return new ICmpInst(ICI.getPredicate(), And, 1212 ConstantExpr::getLShr(RHS, ShAmt)); 1213 } 1214 } 1215 1216 // Otherwise, if this is a comparison of the sign bit, simplify to and/test. 1217 bool TrueIfSigned = false; 1218 if (LHSI->hasOneUse() && 1219 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) { 1220 // (X << 31) <s 0 --> (X&1) != 0 1221 Constant *Mask = ConstantInt::get(ICI.getContext(), APInt(TypeBits, 1) << 1222 (TypeBits-ShAmt->getZExtValue()-1)); 1223 Value *And = 1224 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask"); 1225 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, 1226 And, Constant::getNullValue(And->getType())); 1227 } 1228 break; 1229 } 1230 1231 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI) 1232 case Instruction::AShr: { 1233 // Only handle equality comparisons of shift-by-constant. 1234 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1235 if (!ShAmt || !ICI.isEquality()) break; 1236 1237 // Check that the shift amount is in range. If not, don't perform 1238 // undefined shifts. When the shift is visited it will be 1239 // simplified. 1240 uint32_t TypeBits = RHSV.getBitWidth(); 1241 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); 1242 if (ShAmtVal >= TypeBits) 1243 break; 1244 1245 // If we are comparing against bits always shifted out, the 1246 // comparison cannot succeed. 1247 APInt Comp = RHSV << ShAmtVal; 1248 if (LHSI->getOpcode() == Instruction::LShr) 1249 Comp = Comp.lshr(ShAmtVal); 1250 else 1251 Comp = Comp.ashr(ShAmtVal); 1252 1253 if (Comp != RHSV) { // Comparing against a bit that we know is zero. 1254 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1255 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 1256 IsICMP_NE); 1257 return ReplaceInstUsesWith(ICI, Cst); 1258 } 1259 1260 // Otherwise, check to see if the bits shifted out are known to be zero. 1261 // If so, we can compare against the unshifted value: 1262 // (X & 4) >> 1 == 2 --> (X & 4) == 4. 1263 if (LHSI->hasOneUse() && cast<BinaryOperator>(LHSI)->isExact()) 1264 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 1265 ConstantExpr::getShl(RHS, ShAmt)); 1266 1267 if (LHSI->hasOneUse()) { 1268 // Otherwise strength reduce the shift into an and. 1269 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); 1270 Constant *Mask = ConstantInt::get(ICI.getContext(), Val); 1271 1272 Value *And = Builder->CreateAnd(LHSI->getOperand(0), 1273 Mask, LHSI->getName()+".mask"); 1274 return new ICmpInst(ICI.getPredicate(), And, 1275 ConstantExpr::getShl(RHS, ShAmt)); 1276 } 1277 break; 1278 } 1279 1280 case Instruction::SDiv: 1281 case Instruction::UDiv: 1282 // Fold: icmp pred ([us]div X, C1), C2 -> range test 1283 // Fold this div into the comparison, producing a range check. 1284 // Determine, based on the divide type, what the range is being 1285 // checked. If there is an overflow on the low or high side, remember 1286 // it, otherwise compute the range [low, hi) bounding the new value. 1287 // See: InsertRangeTest above for the kinds of replacements possible. 1288 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) 1289 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI), 1290 DivRHS)) 1291 return R; 1292 break; 1293 1294 case Instruction::Add: 1295 // Fold: icmp pred (add X, C1), C2 1296 if (!ICI.isEquality()) { 1297 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1298 if (!LHSC) break; 1299 const APInt &LHSV = LHSC->getValue(); 1300 1301 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV) 1302 .subtract(LHSV); 1303 1304 if (ICI.isSigned()) { 1305 if (CR.getLower().isSignBit()) { 1306 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0), 1307 ConstantInt::get(ICI.getContext(),CR.getUpper())); 1308 } else if (CR.getUpper().isSignBit()) { 1309 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0), 1310 ConstantInt::get(ICI.getContext(),CR.getLower())); 1311 } 1312 } else { 1313 if (CR.getLower().isMinValue()) { 1314 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), 1315 ConstantInt::get(ICI.getContext(),CR.getUpper())); 1316 } else if (CR.getUpper().isMinValue()) { 1317 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), 1318 ConstantInt::get(ICI.getContext(),CR.getLower())); 1319 } 1320 } 1321 } 1322 break; 1323 } 1324 1325 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS. 1326 if (ICI.isEquality()) { 1327 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1328 1329 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 1330 // the second operand is a constant, simplify a bit. 1331 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) { 1332 switch (BO->getOpcode()) { 1333 case Instruction::SRem: 1334 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. 1335 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){ 1336 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue(); 1337 if (V.sgt(1) && V.isPowerOf2()) { 1338 Value *NewRem = 1339 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1), 1340 BO->getName()); 1341 return new ICmpInst(ICI.getPredicate(), NewRem, 1342 Constant::getNullValue(BO->getType())); 1343 } 1344 } 1345 break; 1346 case Instruction::Add: 1347 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. 1348 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1349 if (BO->hasOneUse()) 1350 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1351 ConstantExpr::getSub(RHS, BOp1C)); 1352 } else if (RHSV == 0) { 1353 // Replace ((add A, B) != 0) with (A != -B) if A or B is 1354 // efficiently invertible, or if the add has just this one use. 1355 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); 1356 1357 if (Value *NegVal = dyn_castNegVal(BOp1)) 1358 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal); 1359 else if (Value *NegVal = dyn_castNegVal(BOp0)) 1360 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1); 1361 else if (BO->hasOneUse()) { 1362 Value *Neg = Builder->CreateNeg(BOp1); 1363 Neg->takeName(BO); 1364 return new ICmpInst(ICI.getPredicate(), BOp0, Neg); 1365 } 1366 } 1367 break; 1368 case Instruction::Xor: 1369 // For the xor case, we can xor two constants together, eliminating 1370 // the explicit xor. 1371 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) 1372 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1373 ConstantExpr::getXor(RHS, BOC)); 1374 1375 // FALLTHROUGH 1376 case Instruction::Sub: 1377 // Replace (([sub|xor] A, B) != 0) with (A != B) 1378 if (RHSV == 0) 1379 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1380 BO->getOperand(1)); 1381 break; 1382 1383 case Instruction::Or: 1384 // If bits are being or'd in that are not present in the constant we 1385 // are comparing against, then the comparison could never succeed! 1386 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1387 Constant *NotCI = ConstantExpr::getNot(RHS); 1388 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue()) 1389 return ReplaceInstUsesWith(ICI, 1390 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 1391 isICMP_NE)); 1392 } 1393 break; 1394 1395 case Instruction::And: 1396 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1397 // If bits are being compared against that are and'd out, then the 1398 // comparison can never succeed! 1399 if ((RHSV & ~BOC->getValue()) != 0) 1400 return ReplaceInstUsesWith(ICI, 1401 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 1402 isICMP_NE)); 1403 1404 // If we have ((X & C) == C), turn it into ((X & C) != 0). 1405 if (RHS == BOC && RHSV.isPowerOf2()) 1406 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : 1407 ICmpInst::ICMP_NE, LHSI, 1408 Constant::getNullValue(RHS->getType())); 1409 1410 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 1411 if (BOC->getValue().isSignBit()) { 1412 Value *X = BO->getOperand(0); 1413 Constant *Zero = Constant::getNullValue(X->getType()); 1414 ICmpInst::Predicate pred = isICMP_NE ? 1415 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; 1416 return new ICmpInst(pred, X, Zero); 1417 } 1418 1419 // ((X & ~7) == 0) --> X < 8 1420 if (RHSV == 0 && isHighOnes(BOC)) { 1421 Value *X = BO->getOperand(0); 1422 Constant *NegX = ConstantExpr::getNeg(BOC); 1423 ICmpInst::Predicate pred = isICMP_NE ? 1424 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 1425 return new ICmpInst(pred, X, NegX); 1426 } 1427 } 1428 default: break; 1429 } 1430 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) { 1431 // Handle icmp {eq|ne} <intrinsic>, intcst. 1432 switch (II->getIntrinsicID()) { 1433 case Intrinsic::bswap: 1434 Worklist.Add(II); 1435 ICI.setOperand(0, II->getArgOperand(0)); 1436 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap())); 1437 return &ICI; 1438 case Intrinsic::ctlz: 1439 case Intrinsic::cttz: 1440 // ctz(A) == bitwidth(a) -> A == 0 and likewise for != 1441 if (RHSV == RHS->getType()->getBitWidth()) { 1442 Worklist.Add(II); 1443 ICI.setOperand(0, II->getArgOperand(0)); 1444 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0)); 1445 return &ICI; 1446 } 1447 break; 1448 case Intrinsic::ctpop: 1449 // popcount(A) == 0 -> A == 0 and likewise for != 1450 if (RHS->isZero()) { 1451 Worklist.Add(II); 1452 ICI.setOperand(0, II->getArgOperand(0)); 1453 ICI.setOperand(1, RHS); 1454 return &ICI; 1455 } 1456 break; 1457 default: 1458 break; 1459 } 1460 } 1461 } 1462 return 0; 1463} 1464 1465/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst). 1466/// We only handle extending casts so far. 1467/// 1468Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) { 1469 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0)); 1470 Value *LHSCIOp = LHSCI->getOperand(0); 1471 const Type *SrcTy = LHSCIOp->getType(); 1472 const Type *DestTy = LHSCI->getType(); 1473 Value *RHSCIOp; 1474 1475 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 1476 // integer type is the same size as the pointer type. 1477 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt && 1478 TD->getPointerSizeInBits() == 1479 cast<IntegerType>(DestTy)->getBitWidth()) { 1480 Value *RHSOp = 0; 1481 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) { 1482 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); 1483 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) { 1484 RHSOp = RHSC->getOperand(0); 1485 // If the pointer types don't match, insert a bitcast. 1486 if (LHSCIOp->getType() != RHSOp->getType()) 1487 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType()); 1488 } 1489 1490 if (RHSOp) 1491 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp); 1492 } 1493 1494 // The code below only handles extension cast instructions, so far. 1495 // Enforce this. 1496 if (LHSCI->getOpcode() != Instruction::ZExt && 1497 LHSCI->getOpcode() != Instruction::SExt) 1498 return 0; 1499 1500 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; 1501 bool isSignedCmp = ICI.isSigned(); 1502 1503 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) { 1504 // Not an extension from the same type? 1505 RHSCIOp = CI->getOperand(0); 1506 if (RHSCIOp->getType() != LHSCIOp->getType()) 1507 return 0; 1508 1509 // If the signedness of the two casts doesn't agree (i.e. one is a sext 1510 // and the other is a zext), then we can't handle this. 1511 if (CI->getOpcode() != LHSCI->getOpcode()) 1512 return 0; 1513 1514 // Deal with equality cases early. 1515 if (ICI.isEquality()) 1516 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); 1517 1518 // A signed comparison of sign extended values simplifies into a 1519 // signed comparison. 1520 if (isSignedCmp && isSignedExt) 1521 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); 1522 1523 // The other three cases all fold into an unsigned comparison. 1524 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp); 1525 } 1526 1527 // If we aren't dealing with a constant on the RHS, exit early 1528 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1)); 1529 if (!CI) 1530 return 0; 1531 1532 // Compute the constant that would happen if we truncated to SrcTy then 1533 // reextended to DestTy. 1534 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy); 1535 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), 1536 Res1, DestTy); 1537 1538 // If the re-extended constant didn't change... 1539 if (Res2 == CI) { 1540 // Deal with equality cases early. 1541 if (ICI.isEquality()) 1542 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1); 1543 1544 // A signed comparison of sign extended values simplifies into a 1545 // signed comparison. 1546 if (isSignedExt && isSignedCmp) 1547 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1); 1548 1549 // The other three cases all fold into an unsigned comparison. 1550 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1); 1551 } 1552 1553 // The re-extended constant changed so the constant cannot be represented 1554 // in the shorter type. Consequently, we cannot emit a simple comparison. 1555 // All the cases that fold to true or false will have already been handled 1556 // by SimplifyICmpInst, so only deal with the tricky case. 1557 1558 if (isSignedCmp || !isSignedExt) 1559 return 0; 1560 1561 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases 1562 // should have been folded away previously and not enter in here. 1563 1564 // We're performing an unsigned comp with a sign extended value. 1565 // This is true if the input is >= 0. [aka >s -1] 1566 Constant *NegOne = Constant::getAllOnesValue(SrcTy); 1567 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName()); 1568 1569 // Finally, return the value computed. 1570 if (ICI.getPredicate() == ICmpInst::ICMP_ULT) 1571 return ReplaceInstUsesWith(ICI, Result); 1572 1573 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); 1574 return BinaryOperator::CreateNot(Result); 1575} 1576 1577/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form: 1578/// I = icmp ugt (add (add A, B), CI2), CI1 1579/// If this is of the form: 1580/// sum = a + b 1581/// if (sum+128 >u 255) 1582/// Then replace it with llvm.sadd.with.overflow.i8. 1583/// 1584static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, 1585 ConstantInt *CI2, ConstantInt *CI1, 1586 InstCombiner &IC) { 1587 // The transformation we're trying to do here is to transform this into an 1588 // llvm.sadd.with.overflow. To do this, we have to replace the original add 1589 // with a narrower add, and discard the add-with-constant that is part of the 1590 // range check (if we can't eliminate it, this isn't profitable). 1591 1592 // In order to eliminate the add-with-constant, the compare can be its only 1593 // use. 1594 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0)); 1595 if (!AddWithCst->hasOneUse()) return 0; 1596 1597 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. 1598 if (!CI2->getValue().isPowerOf2()) return 0; 1599 unsigned NewWidth = CI2->getValue().countTrailingZeros(); 1600 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0; 1601 1602 // The width of the new add formed is 1 more than the bias. 1603 ++NewWidth; 1604 1605 // Check to see that CI1 is an all-ones value with NewWidth bits. 1606 if (CI1->getBitWidth() == NewWidth || 1607 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) 1608 return 0; 1609 1610 // In order to replace the original add with a narrower 1611 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant 1612 // and truncates that discard the high bits of the add. Verify that this is 1613 // the case. 1614 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0)); 1615 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end(); 1616 UI != E; ++UI) { 1617 if (*UI == AddWithCst) continue; 1618 1619 // Only accept truncates for now. We would really like a nice recursive 1620 // predicate like SimplifyDemandedBits, but which goes downwards the use-def 1621 // chain to see which bits of a value are actually demanded. If the 1622 // original add had another add which was then immediately truncated, we 1623 // could still do the transformation. 1624 TruncInst *TI = dyn_cast<TruncInst>(*UI); 1625 if (TI == 0 || 1626 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0; 1627 } 1628 1629 // If the pattern matches, truncate the inputs to the narrower type and 1630 // use the sadd_with_overflow intrinsic to efficiently compute both the 1631 // result and the overflow bit. 1632 Module *M = I.getParent()->getParent()->getParent(); 1633 1634 const Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); 1635 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow, 1636 &NewType, 1); 1637 1638 InstCombiner::BuilderTy *Builder = IC.Builder; 1639 1640 // Put the new code above the original add, in case there are any uses of the 1641 // add between the add and the compare. 1642 Builder->SetInsertPoint(OrigAdd); 1643 1644 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc"); 1645 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc"); 1646 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd"); 1647 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result"); 1648 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType()); 1649 1650 // The inner add was the result of the narrow add, zero extended to the 1651 // wider type. Replace it with the result computed by the intrinsic. 1652 IC.ReplaceInstUsesWith(*OrigAdd, ZExt); 1653 1654 // The original icmp gets replaced with the overflow value. 1655 return ExtractValueInst::Create(Call, 1, "sadd.overflow"); 1656} 1657 1658static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV, 1659 InstCombiner &IC) { 1660 // Don't bother doing this transformation for pointers, don't do it for 1661 // vectors. 1662 if (!isa<IntegerType>(OrigAddV->getType())) return 0; 1663 1664 // If the add is a constant expr, then we don't bother transforming it. 1665 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV); 1666 if (OrigAdd == 0) return 0; 1667 1668 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1); 1669 1670 // Put the new code above the original add, in case there are any uses of the 1671 // add between the add and the compare. 1672 InstCombiner::BuilderTy *Builder = IC.Builder; 1673 Builder->SetInsertPoint(OrigAdd); 1674 1675 Module *M = I.getParent()->getParent()->getParent(); 1676 const Type *Ty = LHS->getType(); 1677 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, &Ty,1); 1678 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd"); 1679 Value *Add = Builder->CreateExtractValue(Call, 0); 1680 1681 IC.ReplaceInstUsesWith(*OrigAdd, Add); 1682 1683 // The original icmp gets replaced with the overflow value. 1684 return ExtractValueInst::Create(Call, 1, "uadd.overflow"); 1685} 1686 1687// DemandedBitsLHSMask - When performing a comparison against a constant, 1688// it is possible that not all the bits in the LHS are demanded. This helper 1689// method computes the mask that IS demanded. 1690static APInt DemandedBitsLHSMask(ICmpInst &I, 1691 unsigned BitWidth, bool isSignCheck) { 1692 if (isSignCheck) 1693 return APInt::getSignBit(BitWidth); 1694 1695 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1)); 1696 if (!CI) return APInt::getAllOnesValue(BitWidth); 1697 const APInt &RHS = CI->getValue(); 1698 1699 switch (I.getPredicate()) { 1700 // For a UGT comparison, we don't care about any bits that 1701 // correspond to the trailing ones of the comparand. The value of these 1702 // bits doesn't impact the outcome of the comparison, because any value 1703 // greater than the RHS must differ in a bit higher than these due to carry. 1704 case ICmpInst::ICMP_UGT: { 1705 unsigned trailingOnes = RHS.countTrailingOnes(); 1706 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes); 1707 return ~lowBitsSet; 1708 } 1709 1710 // Similarly, for a ULT comparison, we don't care about the trailing zeros. 1711 // Any value less than the RHS must differ in a higher bit because of carries. 1712 case ICmpInst::ICMP_ULT: { 1713 unsigned trailingZeros = RHS.countTrailingZeros(); 1714 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros); 1715 return ~lowBitsSet; 1716 } 1717 1718 default: 1719 return APInt::getAllOnesValue(BitWidth); 1720 } 1721 1722} 1723 1724Instruction *InstCombiner::visitICmpInst(ICmpInst &I) { 1725 bool Changed = false; 1726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1727 1728 /// Orders the operands of the compare so that they are listed from most 1729 /// complex to least complex. This puts constants before unary operators, 1730 /// before binary operators. 1731 if (getComplexity(Op0) < getComplexity(Op1)) { 1732 I.swapOperands(); 1733 std::swap(Op0, Op1); 1734 Changed = true; 1735 } 1736 1737 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD)) 1738 return ReplaceInstUsesWith(I, V); 1739 1740 const Type *Ty = Op0->getType(); 1741 1742 // icmp's with boolean values can always be turned into bitwise operations 1743 if (Ty->isIntegerTy(1)) { 1744 switch (I.getPredicate()) { 1745 default: llvm_unreachable("Invalid icmp instruction!"); 1746 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B) 1747 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp"); 1748 return BinaryOperator::CreateNot(Xor); 1749 } 1750 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B 1751 return BinaryOperator::CreateXor(Op0, Op1); 1752 1753 case ICmpInst::ICMP_UGT: 1754 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult 1755 // FALL THROUGH 1756 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B 1757 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp"); 1758 return BinaryOperator::CreateAnd(Not, Op1); 1759 } 1760 case ICmpInst::ICMP_SGT: 1761 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt 1762 // FALL THROUGH 1763 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B 1764 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp"); 1765 return BinaryOperator::CreateAnd(Not, Op0); 1766 } 1767 case ICmpInst::ICMP_UGE: 1768 std::swap(Op0, Op1); // Change icmp uge -> icmp ule 1769 // FALL THROUGH 1770 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B 1771 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp"); 1772 return BinaryOperator::CreateOr(Not, Op1); 1773 } 1774 case ICmpInst::ICMP_SGE: 1775 std::swap(Op0, Op1); // Change icmp sge -> icmp sle 1776 // FALL THROUGH 1777 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B 1778 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp"); 1779 return BinaryOperator::CreateOr(Not, Op0); 1780 } 1781 } 1782 } 1783 1784 unsigned BitWidth = 0; 1785 if (Ty->isIntOrIntVectorTy()) 1786 BitWidth = Ty->getScalarSizeInBits(); 1787 else if (TD) // Pointers require TD info to get their size. 1788 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType()); 1789 1790 bool isSignBit = false; 1791 1792 // See if we are doing a comparison with a constant. 1793 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1794 Value *A = 0, *B = 0; 1795 1796 // Match the following pattern, which is a common idiom when writing 1797 // overflow-safe integer arithmetic function. The source performs an 1798 // addition in wider type, and explicitly checks for overflow using 1799 // comparisons against INT_MIN and INT_MAX. Simplify this by using the 1800 // sadd_with_overflow intrinsic. 1801 // 1802 // TODO: This could probably be generalized to handle other overflow-safe 1803 // operations if we worked out the formulas to compute the appropriate 1804 // magic constants. 1805 // 1806 // sum = a + b 1807 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8 1808 { 1809 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI 1810 if (I.getPredicate() == ICmpInst::ICMP_UGT && 1811 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2)))) 1812 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this)) 1813 return Res; 1814 } 1815 1816 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B) 1817 if (I.isEquality() && CI->isZero() && 1818 match(Op0, m_Sub(m_Value(A), m_Value(B)))) { 1819 // (icmp cond A B) if cond is equality 1820 return new ICmpInst(I.getPredicate(), A, B); 1821 } 1822 1823 // If we have an icmp le or icmp ge instruction, turn it into the 1824 // appropriate icmp lt or icmp gt instruction. This allows us to rely on 1825 // them being folded in the code below. The SimplifyICmpInst code has 1826 // already handled the edge cases for us, so we just assert on them. 1827 switch (I.getPredicate()) { 1828 default: break; 1829 case ICmpInst::ICMP_ULE: 1830 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE 1831 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, 1832 ConstantInt::get(CI->getContext(), CI->getValue()+1)); 1833 case ICmpInst::ICMP_SLE: 1834 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE 1835 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, 1836 ConstantInt::get(CI->getContext(), CI->getValue()+1)); 1837 case ICmpInst::ICMP_UGE: 1838 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE 1839 return new ICmpInst(ICmpInst::ICMP_UGT, Op0, 1840 ConstantInt::get(CI->getContext(), CI->getValue()-1)); 1841 case ICmpInst::ICMP_SGE: 1842 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE 1843 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, 1844 ConstantInt::get(CI->getContext(), CI->getValue()-1)); 1845 } 1846 1847 // If this comparison is a normal comparison, it demands all 1848 // bits, if it is a sign bit comparison, it only demands the sign bit. 1849 bool UnusedBit; 1850 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit); 1851 } 1852 1853 // See if we can fold the comparison based on range information we can get 1854 // by checking whether bits are known to be zero or one in the input. 1855 if (BitWidth != 0) { 1856 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0); 1857 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0); 1858 1859 if (SimplifyDemandedBits(I.getOperandUse(0), 1860 DemandedBitsLHSMask(I, BitWidth, isSignBit), 1861 Op0KnownZero, Op0KnownOne, 0)) 1862 return &I; 1863 if (SimplifyDemandedBits(I.getOperandUse(1), 1864 APInt::getAllOnesValue(BitWidth), 1865 Op1KnownZero, Op1KnownOne, 0)) 1866 return &I; 1867 1868 // Given the known and unknown bits, compute a range that the LHS could be 1869 // in. Compute the Min, Max and RHS values based on the known bits. For the 1870 // EQ and NE we use unsigned values. 1871 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); 1872 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); 1873 if (I.isSigned()) { 1874 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, 1875 Op0Min, Op0Max); 1876 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, 1877 Op1Min, Op1Max); 1878 } else { 1879 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, 1880 Op0Min, Op0Max); 1881 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, 1882 Op1Min, Op1Max); 1883 } 1884 1885 // If Min and Max are known to be the same, then SimplifyDemandedBits 1886 // figured out that the LHS is a constant. Just constant fold this now so 1887 // that code below can assume that Min != Max. 1888 if (!isa<Constant>(Op0) && Op0Min == Op0Max) 1889 return new ICmpInst(I.getPredicate(), 1890 ConstantInt::get(I.getContext(), Op0Min), Op1); 1891 if (!isa<Constant>(Op1) && Op1Min == Op1Max) 1892 return new ICmpInst(I.getPredicate(), Op0, 1893 ConstantInt::get(I.getContext(), Op1Min)); 1894 1895 // Based on the range information we know about the LHS, see if we can 1896 // simplify this comparison. For example, (x&4) < 8 is always true. 1897 switch (I.getPredicate()) { 1898 default: llvm_unreachable("Unknown icmp opcode!"); 1899 case ICmpInst::ICMP_EQ: { 1900 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) 1901 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1902 1903 // If all bits are known zero except for one, then we know at most one 1904 // bit is set. If the comparison is against zero, then this is a check 1905 // to see if *that* bit is set. 1906 APInt Op0KnownZeroInverted = ~Op0KnownZero; 1907 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) { 1908 // If the LHS is an AND with the same constant, look through it. 1909 Value *LHS = 0; 1910 ConstantInt *LHSC = 0; 1911 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) || 1912 LHSC->getValue() != Op0KnownZeroInverted) 1913 LHS = Op0; 1914 1915 // If the LHS is 1 << x, and we know the result is a power of 2 like 8, 1916 // then turn "((1 << x)&8) == 0" into "x != 3". 1917 Value *X = 0; 1918 if (match(LHS, m_Shl(m_One(), m_Value(X)))) { 1919 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros(); 1920 return new ICmpInst(ICmpInst::ICMP_NE, X, 1921 ConstantInt::get(X->getType(), CmpVal)); 1922 } 1923 1924 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1, 1925 // then turn "((8 >>u x)&1) == 0" into "x != 3". 1926 const APInt *CI; 1927 if (Op0KnownZeroInverted == 1 && 1928 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) 1929 return new ICmpInst(ICmpInst::ICMP_NE, X, 1930 ConstantInt::get(X->getType(), 1931 CI->countTrailingZeros())); 1932 } 1933 1934 break; 1935 } 1936 case ICmpInst::ICMP_NE: { 1937 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) 1938 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1939 1940 // If all bits are known zero except for one, then we know at most one 1941 // bit is set. If the comparison is against zero, then this is a check 1942 // to see if *that* bit is set. 1943 APInt Op0KnownZeroInverted = ~Op0KnownZero; 1944 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) { 1945 // If the LHS is an AND with the same constant, look through it. 1946 Value *LHS = 0; 1947 ConstantInt *LHSC = 0; 1948 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) || 1949 LHSC->getValue() != Op0KnownZeroInverted) 1950 LHS = Op0; 1951 1952 // If the LHS is 1 << x, and we know the result is a power of 2 like 8, 1953 // then turn "((1 << x)&8) != 0" into "x == 3". 1954 Value *X = 0; 1955 if (match(LHS, m_Shl(m_One(), m_Value(X)))) { 1956 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros(); 1957 return new ICmpInst(ICmpInst::ICMP_EQ, X, 1958 ConstantInt::get(X->getType(), CmpVal)); 1959 } 1960 1961 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1, 1962 // then turn "((8 >>u x)&1) != 0" into "x == 3". 1963 const APInt *CI; 1964 if (Op0KnownZeroInverted == 1 && 1965 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) 1966 return new ICmpInst(ICmpInst::ICMP_EQ, X, 1967 ConstantInt::get(X->getType(), 1968 CI->countTrailingZeros())); 1969 } 1970 1971 break; 1972 } 1973 case ICmpInst::ICMP_ULT: 1974 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) 1975 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1976 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) 1977 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1978 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) 1979 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 1980 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 1981 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C 1982 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 1983 ConstantInt::get(CI->getContext(), CI->getValue()-1)); 1984 1985 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear 1986 if (CI->isMinValue(true)) 1987 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, 1988 Constant::getAllOnesValue(Op0->getType())); 1989 } 1990 break; 1991 case ICmpInst::ICMP_UGT: 1992 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) 1993 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 1994 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) 1995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 1996 1997 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) 1998 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 1999 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2000 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C 2001 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 2002 ConstantInt::get(CI->getContext(), CI->getValue()+1)); 2003 2004 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set 2005 if (CI->isMaxValue(true)) 2006 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, 2007 Constant::getNullValue(Op0->getType())); 2008 } 2009 break; 2010 case ICmpInst::ICMP_SLT: 2011 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) 2012 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2013 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) 2014 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2015 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) 2016 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 2017 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2018 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C 2019 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 2020 ConstantInt::get(CI->getContext(), CI->getValue()-1)); 2021 } 2022 break; 2023 case ICmpInst::ICMP_SGT: 2024 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) 2025 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2026 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) 2027 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2028 2029 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) 2030 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 2031 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2032 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C 2033 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 2034 ConstantInt::get(CI->getContext(), CI->getValue()+1)); 2035 } 2036 break; 2037 case ICmpInst::ICMP_SGE: 2038 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); 2039 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) 2040 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2041 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) 2042 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2043 break; 2044 case ICmpInst::ICMP_SLE: 2045 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); 2046 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) 2047 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2048 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) 2049 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2050 break; 2051 case ICmpInst::ICMP_UGE: 2052 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); 2053 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) 2054 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2055 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) 2056 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2057 break; 2058 case ICmpInst::ICMP_ULE: 2059 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); 2060 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) 2061 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2062 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) 2063 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2064 break; 2065 } 2066 2067 // Turn a signed comparison into an unsigned one if both operands 2068 // are known to have the same sign. 2069 if (I.isSigned() && 2070 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) || 2071 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative()))) 2072 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); 2073 } 2074 2075 // Test if the ICmpInst instruction is used exclusively by a select as 2076 // part of a minimum or maximum operation. If so, refrain from doing 2077 // any other folding. This helps out other analyses which understand 2078 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 2079 // and CodeGen. And in this case, at least one of the comparison 2080 // operands has at least one user besides the compare (the select), 2081 // which would often largely negate the benefit of folding anyway. 2082 if (I.hasOneUse()) 2083 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin())) 2084 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || 2085 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) 2086 return 0; 2087 2088 // See if we are doing a comparison between a constant and an instruction that 2089 // can be folded into the comparison. 2090 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2091 // Since the RHS is a ConstantInt (CI), if the left hand side is an 2092 // instruction, see if that instruction also has constants so that the 2093 // instruction can be folded into the icmp 2094 if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 2095 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI)) 2096 return Res; 2097 } 2098 2099 // Handle icmp with constant (but not simple integer constant) RHS 2100 if (Constant *RHSC = dyn_cast<Constant>(Op1)) { 2101 if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 2102 switch (LHSI->getOpcode()) { 2103 case Instruction::GetElementPtr: 2104 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null 2105 if (RHSC->isNullValue() && 2106 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) 2107 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), 2108 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2109 break; 2110 case Instruction::PHI: 2111 // Only fold icmp into the PHI if the phi and icmp are in the same 2112 // block. If in the same block, we're encouraging jump threading. If 2113 // not, we are just pessimizing the code by making an i1 phi. 2114 if (LHSI->getParent() == I.getParent()) 2115 if (Instruction *NV = FoldOpIntoPhi(I)) 2116 return NV; 2117 break; 2118 case Instruction::Select: { 2119 // If either operand of the select is a constant, we can fold the 2120 // comparison into the select arms, which will cause one to be 2121 // constant folded and the select turned into a bitwise or. 2122 Value *Op1 = 0, *Op2 = 0; 2123 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) 2124 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2125 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) 2126 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2127 2128 // We only want to perform this transformation if it will not lead to 2129 // additional code. This is true if either both sides of the select 2130 // fold to a constant (in which case the icmp is replaced with a select 2131 // which will usually simplify) or this is the only user of the 2132 // select (in which case we are trading a select+icmp for a simpler 2133 // select+icmp). 2134 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) { 2135 if (!Op1) 2136 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), 2137 RHSC, I.getName()); 2138 if (!Op2) 2139 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), 2140 RHSC, I.getName()); 2141 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 2142 } 2143 break; 2144 } 2145 case Instruction::IntToPtr: 2146 // icmp pred inttoptr(X), null -> icmp pred X, 0 2147 if (RHSC->isNullValue() && TD && 2148 TD->getIntPtrType(RHSC->getContext()) == 2149 LHSI->getOperand(0)->getType()) 2150 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), 2151 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2152 break; 2153 2154 case Instruction::Load: 2155 // Try to optimize things like "A[i] > 4" to index computations. 2156 if (GetElementPtrInst *GEP = 2157 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 2158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 2159 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 2160 !cast<LoadInst>(LHSI)->isVolatile()) 2161 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) 2162 return Res; 2163 } 2164 break; 2165 } 2166 } 2167 2168 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. 2169 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0)) 2170 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I)) 2171 return NI; 2172 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) 2173 if (Instruction *NI = FoldGEPICmp(GEP, Op0, 2174 ICmpInst::getSwappedPredicate(I.getPredicate()), I)) 2175 return NI; 2176 2177 // Test to see if the operands of the icmp are casted versions of other 2178 // values. If the ptr->ptr cast can be stripped off both arguments, we do so 2179 // now. 2180 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) { 2181 if (Op0->getType()->isPointerTy() && 2182 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 2183 // We keep moving the cast from the left operand over to the right 2184 // operand, where it can often be eliminated completely. 2185 Op0 = CI->getOperand(0); 2186 2187 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast 2188 // so eliminate it as well. 2189 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1)) 2190 Op1 = CI2->getOperand(0); 2191 2192 // If Op1 is a constant, we can fold the cast into the constant. 2193 if (Op0->getType() != Op1->getType()) { 2194 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 2195 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType()); 2196 } else { 2197 // Otherwise, cast the RHS right before the icmp 2198 Op1 = Builder->CreateBitCast(Op1, Op0->getType()); 2199 } 2200 } 2201 return new ICmpInst(I.getPredicate(), Op0, Op1); 2202 } 2203 } 2204 2205 if (isa<CastInst>(Op0)) { 2206 // Handle the special case of: icmp (cast bool to X), <cst> 2207 // This comes up when you have code like 2208 // int X = A < B; 2209 // if (X) ... 2210 // For generality, we handle any zero-extension of any operand comparison 2211 // with a constant or another cast from the same type. 2212 if (isa<Constant>(Op1) || isa<CastInst>(Op1)) 2213 if (Instruction *R = visitICmpInstWithCastAndCast(I)) 2214 return R; 2215 } 2216 2217 // See if it's the same type of instruction on the left and right. 2218 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) { 2219 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) { 2220 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() && 2221 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) { 2222 switch (Op0I->getOpcode()) { 2223 default: break; 2224 case Instruction::Add: 2225 case Instruction::Sub: 2226 case Instruction::Xor: 2227 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b 2228 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0), 2229 Op1I->getOperand(0)); 2230 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b 2231 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) { 2232 if (CI->getValue().isSignBit()) { 2233 ICmpInst::Predicate Pred = I.isSigned() 2234 ? I.getUnsignedPredicate() 2235 : I.getSignedPredicate(); 2236 return new ICmpInst(Pred, Op0I->getOperand(0), 2237 Op1I->getOperand(0)); 2238 } 2239 2240 if (CI->getValue().isMaxSignedValue()) { 2241 ICmpInst::Predicate Pred = I.isSigned() 2242 ? I.getUnsignedPredicate() 2243 : I.getSignedPredicate(); 2244 Pred = I.getSwappedPredicate(Pred); 2245 return new ICmpInst(Pred, Op0I->getOperand(0), 2246 Op1I->getOperand(0)); 2247 } 2248 } 2249 break; 2250 case Instruction::Mul: 2251 if (!I.isEquality()) 2252 break; 2253 2254 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) { 2255 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask 2256 // Mask = -1 >> count-trailing-zeros(Cst). 2257 if (!CI->isZero() && !CI->isOne()) { 2258 const APInt &AP = CI->getValue(); 2259 ConstantInt *Mask = ConstantInt::get(I.getContext(), 2260 APInt::getLowBitsSet(AP.getBitWidth(), 2261 AP.getBitWidth() - 2262 AP.countTrailingZeros())); 2263 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask); 2264 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask); 2265 return new ICmpInst(I.getPredicate(), And1, And2); 2266 } 2267 } 2268 break; 2269 } 2270 } 2271 } 2272 } 2273 2274 { Value *A, *B; 2275 // ~x < ~y --> y < x 2276 // ~x < cst --> ~cst < x 2277 if (match(Op0, m_Not(m_Value(A)))) { 2278 if (match(Op1, m_Not(m_Value(B)))) 2279 return new ICmpInst(I.getPredicate(), B, A); 2280 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) 2281 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A); 2282 } 2283 2284 // (a+b) <u a --> llvm.uadd.with.overflow. 2285 // (a+b) <u b --> llvm.uadd.with.overflow. 2286 if (I.getPredicate() == ICmpInst::ICMP_ULT && 2287 match(Op0, m_Add(m_Value(A), m_Value(B))) && 2288 (Op1 == A || Op1 == B)) 2289 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this)) 2290 return R; 2291 2292 // a >u (a+b) --> llvm.uadd.with.overflow. 2293 // b >u (a+b) --> llvm.uadd.with.overflow. 2294 if (I.getPredicate() == ICmpInst::ICMP_UGT && 2295 match(Op1, m_Add(m_Value(A), m_Value(B))) && 2296 (Op0 == A || Op0 == B)) 2297 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this)) 2298 return R; 2299 } 2300 2301 if (I.isEquality()) { 2302 Value *A, *B, *C, *D; 2303 2304 // -x == -y --> x == y 2305 if (match(Op0, m_Neg(m_Value(A))) && 2306 match(Op1, m_Neg(m_Value(B)))) 2307 return new ICmpInst(I.getPredicate(), A, B); 2308 2309 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { 2310 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 2311 Value *OtherVal = A == Op1 ? B : A; 2312 return new ICmpInst(I.getPredicate(), OtherVal, 2313 Constant::getNullValue(A->getType())); 2314 } 2315 2316 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { 2317 // A^c1 == C^c2 --> A == C^(c1^c2) 2318 ConstantInt *C1, *C2; 2319 if (match(B, m_ConstantInt(C1)) && 2320 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) { 2321 Constant *NC = ConstantInt::get(I.getContext(), 2322 C1->getValue() ^ C2->getValue()); 2323 Value *Xor = Builder->CreateXor(C, NC, "tmp"); 2324 return new ICmpInst(I.getPredicate(), A, Xor); 2325 } 2326 2327 // A^B == A^D -> B == D 2328 if (A == C) return new ICmpInst(I.getPredicate(), B, D); 2329 if (A == D) return new ICmpInst(I.getPredicate(), B, C); 2330 if (B == C) return new ICmpInst(I.getPredicate(), A, D); 2331 if (B == D) return new ICmpInst(I.getPredicate(), A, C); 2332 } 2333 } 2334 2335 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && 2336 (A == Op0 || B == Op0)) { 2337 // A == (A^B) -> B == 0 2338 Value *OtherVal = A == Op0 ? B : A; 2339 return new ICmpInst(I.getPredicate(), OtherVal, 2340 Constant::getNullValue(A->getType())); 2341 } 2342 2343 // (A-B) == A -> B == 0 2344 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)))) 2345 return new ICmpInst(I.getPredicate(), B, 2346 Constant::getNullValue(B->getType())); 2347 2348 // A == (A-B) -> B == 0 2349 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)))) 2350 return new ICmpInst(I.getPredicate(), B, 2351 Constant::getNullValue(B->getType())); 2352 2353 // (A+B) == A -> B == 0 2354 if (match(Op0, m_Add(m_Specific(Op1), m_Value(B))) || 2355 match(Op0, m_Add(m_Value(B), m_Specific(Op1)))) 2356 return new ICmpInst(I.getPredicate(), B, 2357 Constant::getNullValue(B->getType())); 2358 2359 // A == (A+B) -> B == 0 2360 if (match(Op1, m_Add(m_Specific(Op0), m_Value(B))) || 2361 match(Op1, m_Add(m_Value(B), m_Specific(Op0)))) 2362 return new ICmpInst(I.getPredicate(), B, 2363 Constant::getNullValue(B->getType())); 2364 2365 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 2366 if (Op0->hasOneUse() && Op1->hasOneUse() && 2367 match(Op0, m_And(m_Value(A), m_Value(B))) && 2368 match(Op1, m_And(m_Value(C), m_Value(D)))) { 2369 Value *X = 0, *Y = 0, *Z = 0; 2370 2371 if (A == C) { 2372 X = B; Y = D; Z = A; 2373 } else if (A == D) { 2374 X = B; Y = C; Z = A; 2375 } else if (B == C) { 2376 X = A; Y = D; Z = B; 2377 } else if (B == D) { 2378 X = A; Y = C; Z = B; 2379 } 2380 2381 if (X) { // Build (X^Y) & Z 2382 Op1 = Builder->CreateXor(X, Y, "tmp"); 2383 Op1 = Builder->CreateAnd(Op1, Z, "tmp"); 2384 I.setOperand(0, Op1); 2385 I.setOperand(1, Constant::getNullValue(Op1->getType())); 2386 return &I; 2387 } 2388 } 2389 } 2390 2391 { 2392 Value *X; ConstantInt *Cst; 2393 // icmp X+Cst, X 2394 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X) 2395 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0); 2396 2397 // icmp X, X+Cst 2398 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X) 2399 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1); 2400 } 2401 return Changed ? &I : 0; 2402} 2403 2404 2405 2406 2407 2408 2409/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible. 2410/// 2411Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I, 2412 Instruction *LHSI, 2413 Constant *RHSC) { 2414 if (!isa<ConstantFP>(RHSC)) return 0; 2415 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); 2416 2417 // Get the width of the mantissa. We don't want to hack on conversions that 2418 // might lose information from the integer, e.g. "i64 -> float" 2419 int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); 2420 if (MantissaWidth == -1) return 0; // Unknown. 2421 2422 // Check to see that the input is converted from an integer type that is small 2423 // enough that preserves all bits. TODO: check here for "known" sign bits. 2424 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. 2425 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits(); 2426 2427 // If this is a uitofp instruction, we need an extra bit to hold the sign. 2428 bool LHSUnsigned = isa<UIToFPInst>(LHSI); 2429 if (LHSUnsigned) 2430 ++InputSize; 2431 2432 // If the conversion would lose info, don't hack on this. 2433 if ((int)InputSize > MantissaWidth) 2434 return 0; 2435 2436 // Otherwise, we can potentially simplify the comparison. We know that it 2437 // will always come through as an integer value and we know the constant is 2438 // not a NAN (it would have been previously simplified). 2439 assert(!RHS.isNaN() && "NaN comparison not already folded!"); 2440 2441 ICmpInst::Predicate Pred; 2442 switch (I.getPredicate()) { 2443 default: llvm_unreachable("Unexpected predicate!"); 2444 case FCmpInst::FCMP_UEQ: 2445 case FCmpInst::FCMP_OEQ: 2446 Pred = ICmpInst::ICMP_EQ; 2447 break; 2448 case FCmpInst::FCMP_UGT: 2449 case FCmpInst::FCMP_OGT: 2450 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; 2451 break; 2452 case FCmpInst::FCMP_UGE: 2453 case FCmpInst::FCMP_OGE: 2454 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; 2455 break; 2456 case FCmpInst::FCMP_ULT: 2457 case FCmpInst::FCMP_OLT: 2458 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; 2459 break; 2460 case FCmpInst::FCMP_ULE: 2461 case FCmpInst::FCMP_OLE: 2462 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; 2463 break; 2464 case FCmpInst::FCMP_UNE: 2465 case FCmpInst::FCMP_ONE: 2466 Pred = ICmpInst::ICMP_NE; 2467 break; 2468 case FCmpInst::FCMP_ORD: 2469 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2470 case FCmpInst::FCMP_UNO: 2471 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2472 } 2473 2474 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); 2475 2476 // Now we know that the APFloat is a normal number, zero or inf. 2477 2478 // See if the FP constant is too large for the integer. For example, 2479 // comparing an i8 to 300.0. 2480 unsigned IntWidth = IntTy->getScalarSizeInBits(); 2481 2482 if (!LHSUnsigned) { 2483 // If the RHS value is > SignedMax, fold the comparison. This handles +INF 2484 // and large values. 2485 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false); 2486 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, 2487 APFloat::rmNearestTiesToEven); 2488 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0 2489 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || 2490 Pred == ICmpInst::ICMP_SLE) 2491 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2492 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2493 } 2494 } else { 2495 // If the RHS value is > UnsignedMax, fold the comparison. This handles 2496 // +INF and large values. 2497 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false); 2498 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, 2499 APFloat::rmNearestTiesToEven); 2500 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0 2501 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || 2502 Pred == ICmpInst::ICMP_ULE) 2503 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2504 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2505 } 2506 } 2507 2508 if (!LHSUnsigned) { 2509 // See if the RHS value is < SignedMin. 2510 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false); 2511 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, 2512 APFloat::rmNearestTiesToEven); 2513 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0 2514 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || 2515 Pred == ICmpInst::ICMP_SGE) 2516 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2517 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2518 } 2519 } 2520 2521 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or 2522 // [0, UMAX], but it may still be fractional. See if it is fractional by 2523 // casting the FP value to the integer value and back, checking for equality. 2524 // Don't do this for zero, because -0.0 is not fractional. 2525 Constant *RHSInt = LHSUnsigned 2526 ? ConstantExpr::getFPToUI(RHSC, IntTy) 2527 : ConstantExpr::getFPToSI(RHSC, IntTy); 2528 if (!RHS.isZero()) { 2529 bool Equal = LHSUnsigned 2530 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC 2531 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; 2532 if (!Equal) { 2533 // If we had a comparison against a fractional value, we have to adjust 2534 // the compare predicate and sometimes the value. RHSC is rounded towards 2535 // zero at this point. 2536 switch (Pred) { 2537 default: llvm_unreachable("Unexpected integer comparison!"); 2538 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true 2539 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2540 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false 2541 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2542 case ICmpInst::ICMP_ULE: 2543 // (float)int <= 4.4 --> int <= 4 2544 // (float)int <= -4.4 --> false 2545 if (RHS.isNegative()) 2546 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2547 break; 2548 case ICmpInst::ICMP_SLE: 2549 // (float)int <= 4.4 --> int <= 4 2550 // (float)int <= -4.4 --> int < -4 2551 if (RHS.isNegative()) 2552 Pred = ICmpInst::ICMP_SLT; 2553 break; 2554 case ICmpInst::ICMP_ULT: 2555 // (float)int < -4.4 --> false 2556 // (float)int < 4.4 --> int <= 4 2557 if (RHS.isNegative()) 2558 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext())); 2559 Pred = ICmpInst::ICMP_ULE; 2560 break; 2561 case ICmpInst::ICMP_SLT: 2562 // (float)int < -4.4 --> int < -4 2563 // (float)int < 4.4 --> int <= 4 2564 if (!RHS.isNegative()) 2565 Pred = ICmpInst::ICMP_SLE; 2566 break; 2567 case ICmpInst::ICMP_UGT: 2568 // (float)int > 4.4 --> int > 4 2569 // (float)int > -4.4 --> true 2570 if (RHS.isNegative()) 2571 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2572 break; 2573 case ICmpInst::ICMP_SGT: 2574 // (float)int > 4.4 --> int > 4 2575 // (float)int > -4.4 --> int >= -4 2576 if (RHS.isNegative()) 2577 Pred = ICmpInst::ICMP_SGE; 2578 break; 2579 case ICmpInst::ICMP_UGE: 2580 // (float)int >= -4.4 --> true 2581 // (float)int >= 4.4 --> int > 4 2582 if (!RHS.isNegative()) 2583 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())); 2584 Pred = ICmpInst::ICMP_UGT; 2585 break; 2586 case ICmpInst::ICMP_SGE: 2587 // (float)int >= -4.4 --> int >= -4 2588 // (float)int >= 4.4 --> int > 4 2589 if (!RHS.isNegative()) 2590 Pred = ICmpInst::ICMP_SGT; 2591 break; 2592 } 2593 } 2594 } 2595 2596 // Lower this FP comparison into an appropriate integer version of the 2597 // comparison. 2598 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); 2599} 2600 2601Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) { 2602 bool Changed = false; 2603 2604 /// Orders the operands of the compare so that they are listed from most 2605 /// complex to least complex. This puts constants before unary operators, 2606 /// before binary operators. 2607 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 2608 I.swapOperands(); 2609 Changed = true; 2610 } 2611 2612 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 2613 2614 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD)) 2615 return ReplaceInstUsesWith(I, V); 2616 2617 // Simplify 'fcmp pred X, X' 2618 if (Op0 == Op1) { 2619 switch (I.getPredicate()) { 2620 default: llvm_unreachable("Unknown predicate!"); 2621 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) 2622 case FCmpInst::FCMP_ULT: // True if unordered or less than 2623 case FCmpInst::FCMP_UGT: // True if unordered or greater than 2624 case FCmpInst::FCMP_UNE: // True if unordered or not equal 2625 // Canonicalize these to be 'fcmp uno %X, 0.0'. 2626 I.setPredicate(FCmpInst::FCMP_UNO); 2627 I.setOperand(1, Constant::getNullValue(Op0->getType())); 2628 return &I; 2629 2630 case FCmpInst::FCMP_ORD: // True if ordered (no nans) 2631 case FCmpInst::FCMP_OEQ: // True if ordered and equal 2632 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal 2633 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal 2634 // Canonicalize these to be 'fcmp ord %X, 0.0'. 2635 I.setPredicate(FCmpInst::FCMP_ORD); 2636 I.setOperand(1, Constant::getNullValue(Op0->getType())); 2637 return &I; 2638 } 2639 } 2640 2641 // Handle fcmp with constant RHS 2642 if (Constant *RHSC = dyn_cast<Constant>(Op1)) { 2643 if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 2644 switch (LHSI->getOpcode()) { 2645 case Instruction::PHI: 2646 // Only fold fcmp into the PHI if the phi and fcmp are in the same 2647 // block. If in the same block, we're encouraging jump threading. If 2648 // not, we are just pessimizing the code by making an i1 phi. 2649 if (LHSI->getParent() == I.getParent()) 2650 if (Instruction *NV = FoldOpIntoPhi(I)) 2651 return NV; 2652 break; 2653 case Instruction::SIToFP: 2654 case Instruction::UIToFP: 2655 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC)) 2656 return NV; 2657 break; 2658 case Instruction::Select: { 2659 // If either operand of the select is a constant, we can fold the 2660 // comparison into the select arms, which will cause one to be 2661 // constant folded and the select turned into a bitwise or. 2662 Value *Op1 = 0, *Op2 = 0; 2663 if (LHSI->hasOneUse()) { 2664 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { 2665 // Fold the known value into the constant operand. 2666 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); 2667 // Insert a new FCmp of the other select operand. 2668 Op2 = Builder->CreateFCmp(I.getPredicate(), 2669 LHSI->getOperand(2), RHSC, I.getName()); 2670 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { 2671 // Fold the known value into the constant operand. 2672 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); 2673 // Insert a new FCmp of the other select operand. 2674 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1), 2675 RHSC, I.getName()); 2676 } 2677 } 2678 2679 if (Op1) 2680 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 2681 break; 2682 } 2683 case Instruction::Load: 2684 if (GetElementPtrInst *GEP = 2685 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 2686 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 2687 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 2688 !cast<LoadInst>(LHSI)->isVolatile()) 2689 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) 2690 return Res; 2691 } 2692 break; 2693 } 2694 } 2695 2696 return Changed ? &I : 0; 2697} 2698