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 "InstCombineInternal.h" 15 #include "llvm/ADT/APSInt.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/IR/ConstantRange.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/GetElementPtrTypeIterator.h" 24 #include "llvm/IR/IntrinsicInst.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/Support/Debug.h" 27 #include "llvm/Support/KnownBits.h" 28 29 using namespace llvm; 30 using namespace PatternMatch; 31 32 #define DEBUG_TYPE "instcombine" 33 34 // How many times is a select replaced by one of its operands? 35 STATISTIC(NumSel, "Number of select opts"); 36 37 38 /// Compute Result = In1+In2, returning true if the result overflowed for this 39 /// type. 40 static bool addWithOverflow(APInt &Result, const APInt &In1, 41 const APInt &In2, bool IsSigned = false) { 42 bool Overflow; 43 if (IsSigned) 44 Result = In1.sadd_ov(In2, Overflow); 45 else 46 Result = In1.uadd_ov(In2, Overflow); 47 48 return Overflow; 49 } 50 51 /// Compute Result = In1-In2, returning true if the result overflowed for this 52 /// type. 53 static bool subWithOverflow(APInt &Result, const APInt &In1, 54 const APInt &In2, bool IsSigned = false) { 55 bool Overflow; 56 if (IsSigned) 57 Result = In1.ssub_ov(In2, Overflow); 58 else 59 Result = In1.usub_ov(In2, Overflow); 60 61 return Overflow; 62 } 63 64 /// Given an icmp instruction, return true if any use of this comparison is a 65 /// branch on sign bit comparison. 66 static bool hasBranchUse(ICmpInst &I) { 67 for (auto *U : I.users()) 68 if (isa<BranchInst>(U)) 69 return true; 70 return false; 71 } 72 73 /// Given an exploded icmp instruction, return true if the comparison only 74 /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the 75 /// result of the comparison is true when the input value is signed. 76 static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, 77 bool &TrueIfSigned) { 78 switch (Pred) { 79 case ICmpInst::ICMP_SLT: // True if LHS s< 0 80 TrueIfSigned = true; 81 return RHS.isNullValue(); 82 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 83 TrueIfSigned = true; 84 return RHS.isAllOnesValue(); 85 case ICmpInst::ICMP_SGT: // True if LHS s> -1 86 TrueIfSigned = false; 87 return RHS.isAllOnesValue(); 88 case ICmpInst::ICMP_UGT: 89 // True if LHS u> RHS and RHS == high-bit-mask - 1 90 TrueIfSigned = true; 91 return RHS.isMaxSignedValue(); 92 case ICmpInst::ICMP_UGE: 93 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) 94 TrueIfSigned = true; 95 return RHS.isSignMask(); 96 default: 97 return false; 98 } 99 } 100 101 /// Returns true if the exploded icmp can be expressed as a signed comparison 102 /// to zero and updates the predicate accordingly. 103 /// The signedness of the comparison is preserved. 104 /// TODO: Refactor with decomposeBitTestICmp()? 105 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) { 106 if (!ICmpInst::isSigned(Pred)) 107 return false; 108 109 if (C.isNullValue()) 110 return ICmpInst::isRelational(Pred); 111 112 if (C.isOneValue()) { 113 if (Pred == ICmpInst::ICMP_SLT) { 114 Pred = ICmpInst::ICMP_SLE; 115 return true; 116 } 117 } else if (C.isAllOnesValue()) { 118 if (Pred == ICmpInst::ICMP_SGT) { 119 Pred = ICmpInst::ICMP_SGE; 120 return true; 121 } 122 } 123 124 return false; 125 } 126 127 /// Given a signed integer type and a set of known zero and one bits, compute 128 /// the maximum and minimum values that could have the specified known zero and 129 /// known one bits, returning them in Min/Max. 130 /// TODO: Move to method on KnownBits struct? 131 static void computeSignedMinMaxValuesFromKnownBits(const KnownBits &Known, 132 APInt &Min, APInt &Max) { 133 assert(Known.getBitWidth() == Min.getBitWidth() && 134 Known.getBitWidth() == Max.getBitWidth() && 135 "KnownZero, KnownOne and Min, Max must have equal bitwidth."); 136 APInt UnknownBits = ~(Known.Zero|Known.One); 137 138 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign 139 // bit if it is unknown. 140 Min = Known.One; 141 Max = Known.One|UnknownBits; 142 143 if (UnknownBits.isNegative()) { // Sign bit is unknown 144 Min.setSignBit(); 145 Max.clearSignBit(); 146 } 147 } 148 149 /// Given an unsigned integer type and a set of known zero and one bits, compute 150 /// the maximum and minimum values that could have the specified known zero and 151 /// known one bits, returning them in Min/Max. 152 /// TODO: Move to method on KnownBits struct? 153 static void computeUnsignedMinMaxValuesFromKnownBits(const KnownBits &Known, 154 APInt &Min, APInt &Max) { 155 assert(Known.getBitWidth() == Min.getBitWidth() && 156 Known.getBitWidth() == Max.getBitWidth() && 157 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); 158 APInt UnknownBits = ~(Known.Zero|Known.One); 159 160 // The minimum value is when the unknown bits are all zeros. 161 Min = Known.One; 162 // The maximum value is when the unknown bits are all ones. 163 Max = Known.One|UnknownBits; 164 } 165 166 /// This is called when we see this pattern: 167 /// cmp pred (load (gep GV, ...)), cmpcst 168 /// where GV is a global variable with a constant initializer. Try to simplify 169 /// this into some simple computation that does not need the load. For example 170 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". 171 /// 172 /// If AndCst is non-null, then the loaded value is masked with that constant 173 /// before doing the comparison. This handles cases like "A[i]&4 == 0". 174 Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, 175 GlobalVariable *GV, 176 CmpInst &ICI, 177 ConstantInt *AndCst) { 178 Constant *Init = GV->getInitializer(); 179 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init)) 180 return nullptr; 181 182 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements(); 183 // Don't blow up on huge arrays. 184 if (ArrayElementCount > MaxArraySizeForCombine) 185 return nullptr; 186 187 // There are many forms of this optimization we can handle, for now, just do 188 // the simple index into a single-dimensional array. 189 // 190 // Require: GEP GV, 0, i {{, constant indices}} 191 if (GEP->getNumOperands() < 3 || 192 !isa<ConstantInt>(GEP->getOperand(1)) || 193 !cast<ConstantInt>(GEP->getOperand(1))->isZero() || 194 isa<Constant>(GEP->getOperand(2))) 195 return nullptr; 196 197 // Check that indices after the variable are constants and in-range for the 198 // type they index. Collect the indices. This is typically for arrays of 199 // structs. 200 SmallVector<unsigned, 4> LaterIndices; 201 202 Type *EltTy = Init->getType()->getArrayElementType(); 203 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { 204 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 205 if (!Idx) return nullptr; // Variable index. 206 207 uint64_t IdxVal = Idx->getZExtValue(); 208 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index. 209 210 if (StructType *STy = dyn_cast<StructType>(EltTy)) 211 EltTy = STy->getElementType(IdxVal); 212 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { 213 if (IdxVal >= ATy->getNumElements()) return nullptr; 214 EltTy = ATy->getElementType(); 215 } else { 216 return nullptr; // Unknown type. 217 } 218 219 LaterIndices.push_back(IdxVal); 220 } 221 222 enum { Overdefined = -3, Undefined = -2 }; 223 224 // Variables for our state machines. 225 226 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form 227 // "i == 47 | i == 87", where 47 is the first index the condition is true for, 228 // and 87 is the second (and last) index. FirstTrueElement is -2 when 229 // undefined, otherwise set to the first true element. SecondTrueElement is 230 // -2 when undefined, -3 when overdefined and >= 0 when that index is true. 231 int FirstTrueElement = Undefined, SecondTrueElement = Undefined; 232 233 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the 234 // form "i != 47 & i != 87". Same state transitions as for true elements. 235 int FirstFalseElement = Undefined, SecondFalseElement = Undefined; 236 237 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these 238 /// define a state machine that triggers for ranges of values that the index 239 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. 240 /// This is -2 when undefined, -3 when overdefined, and otherwise the last 241 /// index in the range (inclusive). We use -2 for undefined here because we 242 /// use relative comparisons and don't want 0-1 to match -1. 243 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; 244 245 // MagicBitvector - This is a magic bitvector where we set a bit if the 246 // comparison is true for element 'i'. If there are 64 elements or less in 247 // the array, this will fully represent all the comparison results. 248 uint64_t MagicBitvector = 0; 249 250 // Scan the array and see if one of our patterns matches. 251 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); 252 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) { 253 Constant *Elt = Init->getAggregateElement(i); 254 if (!Elt) return nullptr; 255 256 // If this is indexing an array of structures, get the structure element. 257 if (!LaterIndices.empty()) 258 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices); 259 260 // If the element is masked, handle it. 261 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); 262 263 // Find out if the comparison would be true or false for the i'th element. 264 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, 265 CompareRHS, DL, &TLI); 266 // If the result is undef for this element, ignore it. 267 if (isa<UndefValue>(C)) { 268 // Extend range state machines to cover this element in case there is an 269 // undef in the middle of the range. 270 if (TrueRangeEnd == (int)i-1) 271 TrueRangeEnd = i; 272 if (FalseRangeEnd == (int)i-1) 273 FalseRangeEnd = i; 274 continue; 275 } 276 277 // If we can't compute the result for any of the elements, we have to give 278 // up evaluating the entire conditional. 279 if (!isa<ConstantInt>(C)) return nullptr; 280 281 // Otherwise, we know if the comparison is true or false for this element, 282 // update our state machines. 283 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); 284 285 // State machine for single/double/range index comparison. 286 if (IsTrueForElt) { 287 // Update the TrueElement state machine. 288 if (FirstTrueElement == Undefined) 289 FirstTrueElement = TrueRangeEnd = i; // First true element. 290 else { 291 // Update double-compare state machine. 292 if (SecondTrueElement == Undefined) 293 SecondTrueElement = i; 294 else 295 SecondTrueElement = Overdefined; 296 297 // Update range state machine. 298 if (TrueRangeEnd == (int)i-1) 299 TrueRangeEnd = i; 300 else 301 TrueRangeEnd = Overdefined; 302 } 303 } else { 304 // Update the FalseElement state machine. 305 if (FirstFalseElement == Undefined) 306 FirstFalseElement = FalseRangeEnd = i; // First false element. 307 else { 308 // Update double-compare state machine. 309 if (SecondFalseElement == Undefined) 310 SecondFalseElement = i; 311 else 312 SecondFalseElement = Overdefined; 313 314 // Update range state machine. 315 if (FalseRangeEnd == (int)i-1) 316 FalseRangeEnd = i; 317 else 318 FalseRangeEnd = Overdefined; 319 } 320 } 321 322 // If this element is in range, update our magic bitvector. 323 if (i < 64 && IsTrueForElt) 324 MagicBitvector |= 1ULL << i; 325 326 // If all of our states become overdefined, bail out early. Since the 327 // predicate is expensive, only check it every 8 elements. This is only 328 // really useful for really huge arrays. 329 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && 330 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && 331 FalseRangeEnd == Overdefined) 332 return nullptr; 333 } 334 335 // Now that we've scanned the entire array, emit our new comparison(s). We 336 // order the state machines in complexity of the generated code. 337 Value *Idx = GEP->getOperand(2); 338 339 // If the index is larger than the pointer size of the target, truncate the 340 // index down like the GEP would do implicitly. We don't have to do this for 341 // an inbounds GEP because the index can't be out of range. 342 if (!GEP->isInBounds()) { 343 Type *IntPtrTy = DL.getIntPtrType(GEP->getType()); 344 unsigned PtrSize = IntPtrTy->getIntegerBitWidth(); 345 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize) 346 Idx = Builder.CreateTrunc(Idx, IntPtrTy); 347 } 348 349 // If the comparison is only true for one or two elements, emit direct 350 // comparisons. 351 if (SecondTrueElement != Overdefined) { 352 // None true -> false. 353 if (FirstTrueElement == Undefined) 354 return replaceInstUsesWith(ICI, Builder.getFalse()); 355 356 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); 357 358 // True for one element -> 'i == 47'. 359 if (SecondTrueElement == Undefined) 360 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); 361 362 // True for two elements -> 'i == 47 | i == 72'. 363 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx); 364 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); 365 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx); 366 return BinaryOperator::CreateOr(C1, C2); 367 } 368 369 // If the comparison is only false for one or two elements, emit direct 370 // comparisons. 371 if (SecondFalseElement != Overdefined) { 372 // None false -> true. 373 if (FirstFalseElement == Undefined) 374 return replaceInstUsesWith(ICI, Builder.getTrue()); 375 376 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); 377 378 // False for one element -> 'i != 47'. 379 if (SecondFalseElement == Undefined) 380 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); 381 382 // False for two elements -> 'i != 47 & i != 72'. 383 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx); 384 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); 385 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx); 386 return BinaryOperator::CreateAnd(C1, C2); 387 } 388 389 // If the comparison can be replaced with a range comparison for the elements 390 // where it is true, emit the range check. 391 if (TrueRangeEnd != Overdefined) { 392 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); 393 394 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). 395 if (FirstTrueElement) { 396 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); 397 Idx = Builder.CreateAdd(Idx, Offs); 398 } 399 400 Value *End = ConstantInt::get(Idx->getType(), 401 TrueRangeEnd-FirstTrueElement+1); 402 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); 403 } 404 405 // False range check. 406 if (FalseRangeEnd != Overdefined) { 407 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); 408 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). 409 if (FirstFalseElement) { 410 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); 411 Idx = Builder.CreateAdd(Idx, Offs); 412 } 413 414 Value *End = ConstantInt::get(Idx->getType(), 415 FalseRangeEnd-FirstFalseElement); 416 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); 417 } 418 419 // If a magic bitvector captures the entire comparison state 420 // of this load, replace it with computation that does: 421 // ((magic_cst >> i) & 1) != 0 422 { 423 Type *Ty = nullptr; 424 425 // Look for an appropriate type: 426 // - The type of Idx if the magic fits 427 // - The smallest fitting legal type 428 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth()) 429 Ty = Idx->getType(); 430 else 431 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount); 432 433 if (Ty) { 434 Value *V = Builder.CreateIntCast(Idx, Ty, false); 435 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); 436 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V); 437 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); 438 } 439 } 440 441 return nullptr; 442 } 443 444 /// Return a value that can be used to compare the *offset* implied by a GEP to 445 /// zero. For example, if we have &A[i], we want to return 'i' for 446 /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales 447 /// are involved. The above expression would also be legal to codegen as 448 /// "icmp ne (i*4), 0" (assuming A is a pointer to i32). 449 /// This latter form is less amenable to optimization though, and we are allowed 450 /// to generate the first by knowing that pointer arithmetic doesn't overflow. 451 /// 452 /// If we can't emit an optimized form for this expression, this returns null. 453 /// 454 static Value *evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC, 455 const DataLayout &DL) { 456 gep_type_iterator GTI = gep_type_begin(GEP); 457 458 // Check to see if this gep only has a single variable index. If so, and if 459 // any constant indices are a multiple of its scale, then we can compute this 460 // in terms of the scale of the variable index. For example, if the GEP 461 // implies an offset of "12 + i*4", then we can codegen this as "3 + i", 462 // because the expression will cross zero at the same point. 463 unsigned i, e = GEP->getNumOperands(); 464 int64_t Offset = 0; 465 for (i = 1; i != e; ++i, ++GTI) { 466 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 467 // Compute the aggregate offset of constant indices. 468 if (CI->isZero()) continue; 469 470 // Handle a struct index, which adds its field offset to the pointer. 471 if (StructType *STy = GTI.getStructTypeOrNull()) { 472 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 473 } else { 474 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); 475 Offset += Size*CI->getSExtValue(); 476 } 477 } else { 478 // Found our variable index. 479 break; 480 } 481 } 482 483 // If there are no variable indices, we must have a constant offset, just 484 // evaluate it the general way. 485 if (i == e) return nullptr; 486 487 Value *VariableIdx = GEP->getOperand(i); 488 // Determine the scale factor of the variable element. For example, this is 489 // 4 if the variable index is into an array of i32. 490 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType()); 491 492 // Verify that there are no other variable indices. If so, emit the hard way. 493 for (++i, ++GTI; i != e; ++i, ++GTI) { 494 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); 495 if (!CI) return nullptr; 496 497 // Compute the aggregate offset of constant indices. 498 if (CI->isZero()) continue; 499 500 // Handle a struct index, which adds its field offset to the pointer. 501 if (StructType *STy = GTI.getStructTypeOrNull()) { 502 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 503 } else { 504 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); 505 Offset += Size*CI->getSExtValue(); 506 } 507 } 508 509 // Okay, we know we have a single variable index, which must be a 510 // pointer/array/vector index. If there is no offset, life is simple, return 511 // the index. 512 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType()); 513 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth(); 514 if (Offset == 0) { 515 // Cast to intptrty in case a truncation occurs. If an extension is needed, 516 // we don't need to bother extending: the extension won't affect where the 517 // computation crosses zero. 518 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) { 519 VariableIdx = IC.Builder.CreateTrunc(VariableIdx, IntPtrTy); 520 } 521 return VariableIdx; 522 } 523 524 // Otherwise, there is an index. The computation we will do will be modulo 525 // the pointer size, so get it. 526 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); 527 528 Offset &= PtrSizeMask; 529 VariableScale &= PtrSizeMask; 530 531 // To do this transformation, any constant index must be a multiple of the 532 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", 533 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a 534 // multiple of the variable scale. 535 int64_t NewOffs = Offset / (int64_t)VariableScale; 536 if (Offset != NewOffs*(int64_t)VariableScale) 537 return nullptr; 538 539 // Okay, we can do this evaluation. Start by converting the index to intptr. 540 if (VariableIdx->getType() != IntPtrTy) 541 VariableIdx = IC.Builder.CreateIntCast(VariableIdx, IntPtrTy, 542 true /*Signed*/); 543 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); 544 return IC.Builder.CreateAdd(VariableIdx, OffsetVal, "offset"); 545 } 546 547 /// Returns true if we can rewrite Start as a GEP with pointer Base 548 /// and some integer offset. The nodes that need to be re-written 549 /// for this transformation will be added to Explored. 550 static bool canRewriteGEPAsOffset(Value *Start, Value *Base, 551 const DataLayout &DL, 552 SetVector<Value *> &Explored) { 553 SmallVector<Value *, 16> WorkList(1, Start); 554 Explored.insert(Base); 555 556 // The following traversal gives us an order which can be used 557 // when doing the final transformation. Since in the final 558 // transformation we create the PHI replacement instructions first, 559 // we don't have to get them in any particular order. 560 // 561 // However, for other instructions we will have to traverse the 562 // operands of an instruction first, which means that we have to 563 // do a post-order traversal. 564 while (!WorkList.empty()) { 565 SetVector<PHINode *> PHIs; 566 567 while (!WorkList.empty()) { 568 if (Explored.size() >= 100) 569 return false; 570 571 Value *V = WorkList.back(); 572 573 if (Explored.count(V) != 0) { 574 WorkList.pop_back(); 575 continue; 576 } 577 578 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) && 579 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V)) 580 // We've found some value that we can't explore which is different from 581 // the base. Therefore we can't do this transformation. 582 return false; 583 584 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) { 585 auto *CI = dyn_cast<CastInst>(V); 586 if (!CI->isNoopCast(DL)) 587 return false; 588 589 if (Explored.count(CI->getOperand(0)) == 0) 590 WorkList.push_back(CI->getOperand(0)); 591 } 592 593 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 594 // We're limiting the GEP to having one index. This will preserve 595 // the original pointer type. We could handle more cases in the 596 // future. 597 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() || 598 GEP->getType() != Start->getType()) 599 return false; 600 601 if (Explored.count(GEP->getOperand(0)) == 0) 602 WorkList.push_back(GEP->getOperand(0)); 603 } 604 605 if (WorkList.back() == V) { 606 WorkList.pop_back(); 607 // We've finished visiting this node, mark it as such. 608 Explored.insert(V); 609 } 610 611 if (auto *PN = dyn_cast<PHINode>(V)) { 612 // We cannot transform PHIs on unsplittable basic blocks. 613 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator())) 614 return false; 615 Explored.insert(PN); 616 PHIs.insert(PN); 617 } 618 } 619 620 // Explore the PHI nodes further. 621 for (auto *PN : PHIs) 622 for (Value *Op : PN->incoming_values()) 623 if (Explored.count(Op) == 0) 624 WorkList.push_back(Op); 625 } 626 627 // Make sure that we can do this. Since we can't insert GEPs in a basic 628 // block before a PHI node, we can't easily do this transformation if 629 // we have PHI node users of transformed instructions. 630 for (Value *Val : Explored) { 631 for (Value *Use : Val->uses()) { 632 633 auto *PHI = dyn_cast<PHINode>(Use); 634 auto *Inst = dyn_cast<Instruction>(Val); 635 636 if (Inst == Base || Inst == PHI || !Inst || !PHI || 637 Explored.count(PHI) == 0) 638 continue; 639 640 if (PHI->getParent() == Inst->getParent()) 641 return false; 642 } 643 } 644 return true; 645 } 646 647 // Sets the appropriate insert point on Builder where we can add 648 // a replacement Instruction for V (if that is possible). 649 static void setInsertionPoint(IRBuilder<> &Builder, Value *V, 650 bool Before = true) { 651 if (auto *PHI = dyn_cast<PHINode>(V)) { 652 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt()); 653 return; 654 } 655 if (auto *I = dyn_cast<Instruction>(V)) { 656 if (!Before) 657 I = &*std::next(I->getIterator()); 658 Builder.SetInsertPoint(I); 659 return; 660 } 661 if (auto *A = dyn_cast<Argument>(V)) { 662 // Set the insertion point in the entry block. 663 BasicBlock &Entry = A->getParent()->getEntryBlock(); 664 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt()); 665 return; 666 } 667 // Otherwise, this is a constant and we don't need to set a new 668 // insertion point. 669 assert(isa<Constant>(V) && "Setting insertion point for unknown value!"); 670 } 671 672 /// Returns a re-written value of Start as an indexed GEP using Base as a 673 /// pointer. 674 static Value *rewriteGEPAsOffset(Value *Start, Value *Base, 675 const DataLayout &DL, 676 SetVector<Value *> &Explored) { 677 // Perform all the substitutions. This is a bit tricky because we can 678 // have cycles in our use-def chains. 679 // 1. Create the PHI nodes without any incoming values. 680 // 2. Create all the other values. 681 // 3. Add the edges for the PHI nodes. 682 // 4. Emit GEPs to get the original pointers. 683 // 5. Remove the original instructions. 684 Type *IndexType = IntegerType::get( 685 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType())); 686 687 DenseMap<Value *, Value *> NewInsts; 688 NewInsts[Base] = ConstantInt::getNullValue(IndexType); 689 690 // Create the new PHI nodes, without adding any incoming values. 691 for (Value *Val : Explored) { 692 if (Val == Base) 693 continue; 694 // Create empty phi nodes. This avoids cyclic dependencies when creating 695 // the remaining instructions. 696 if (auto *PHI = dyn_cast<PHINode>(Val)) 697 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(), 698 PHI->getName() + ".idx", PHI); 699 } 700 IRBuilder<> Builder(Base->getContext()); 701 702 // Create all the other instructions. 703 for (Value *Val : Explored) { 704 705 if (NewInsts.find(Val) != NewInsts.end()) 706 continue; 707 708 if (auto *CI = dyn_cast<CastInst>(Val)) { 709 NewInsts[CI] = NewInsts[CI->getOperand(0)]; 710 continue; 711 } 712 if (auto *GEP = dyn_cast<GEPOperator>(Val)) { 713 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)] 714 : GEP->getOperand(1); 715 setInsertionPoint(Builder, GEP); 716 // Indices might need to be sign extended. GEPs will magically do 717 // this, but we need to do it ourselves here. 718 if (Index->getType()->getScalarSizeInBits() != 719 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) { 720 Index = Builder.CreateSExtOrTrunc( 721 Index, NewInsts[GEP->getOperand(0)]->getType(), 722 GEP->getOperand(0)->getName() + ".sext"); 723 } 724 725 auto *Op = NewInsts[GEP->getOperand(0)]; 726 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero()) 727 NewInsts[GEP] = Index; 728 else 729 NewInsts[GEP] = Builder.CreateNSWAdd( 730 Op, Index, GEP->getOperand(0)->getName() + ".add"); 731 continue; 732 } 733 if (isa<PHINode>(Val)) 734 continue; 735 736 llvm_unreachable("Unexpected instruction type"); 737 } 738 739 // Add the incoming values to the PHI nodes. 740 for (Value *Val : Explored) { 741 if (Val == Base) 742 continue; 743 // All the instructions have been created, we can now add edges to the 744 // phi nodes. 745 if (auto *PHI = dyn_cast<PHINode>(Val)) { 746 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]); 747 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) { 748 Value *NewIncoming = PHI->getIncomingValue(I); 749 750 if (NewInsts.find(NewIncoming) != NewInsts.end()) 751 NewIncoming = NewInsts[NewIncoming]; 752 753 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I)); 754 } 755 } 756 } 757 758 for (Value *Val : Explored) { 759 if (Val == Base) 760 continue; 761 762 // Depending on the type, for external users we have to emit 763 // a GEP or a GEP + ptrtoint. 764 setInsertionPoint(Builder, Val, false); 765 766 // If required, create an inttoptr instruction for Base. 767 Value *NewBase = Base; 768 if (!Base->getType()->isPointerTy()) 769 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(), 770 Start->getName() + "to.ptr"); 771 772 Value *GEP = Builder.CreateInBoundsGEP( 773 Start->getType()->getPointerElementType(), NewBase, 774 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr"); 775 776 if (!Val->getType()->isPointerTy()) { 777 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(), 778 Val->getName() + ".conv"); 779 GEP = Cast; 780 } 781 Val->replaceAllUsesWith(GEP); 782 } 783 784 return NewInsts[Start]; 785 } 786 787 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express 788 /// the input Value as a constant indexed GEP. Returns a pair containing 789 /// the GEPs Pointer and Index. 790 static std::pair<Value *, Value *> 791 getAsConstantIndexedAddress(Value *V, const DataLayout &DL) { 792 Type *IndexType = IntegerType::get(V->getContext(), 793 DL.getIndexTypeSizeInBits(V->getType())); 794 795 Constant *Index = ConstantInt::getNullValue(IndexType); 796 while (true) { 797 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 798 // We accept only inbouds GEPs here to exclude the possibility of 799 // overflow. 800 if (!GEP->isInBounds()) 801 break; 802 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 && 803 GEP->getType() == V->getType()) { 804 V = GEP->getOperand(0); 805 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1)); 806 Index = ConstantExpr::getAdd( 807 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType)); 808 continue; 809 } 810 break; 811 } 812 if (auto *CI = dyn_cast<IntToPtrInst>(V)) { 813 if (!CI->isNoopCast(DL)) 814 break; 815 V = CI->getOperand(0); 816 continue; 817 } 818 if (auto *CI = dyn_cast<PtrToIntInst>(V)) { 819 if (!CI->isNoopCast(DL)) 820 break; 821 V = CI->getOperand(0); 822 continue; 823 } 824 break; 825 } 826 return {V, Index}; 827 } 828 829 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant. 830 /// We can look through PHIs, GEPs and casts in order to determine a common base 831 /// between GEPLHS and RHS. 832 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, 833 ICmpInst::Predicate Cond, 834 const DataLayout &DL) { 835 if (!GEPLHS->hasAllConstantIndices()) 836 return nullptr; 837 838 // Make sure the pointers have the same type. 839 if (GEPLHS->getType() != RHS->getType()) 840 return nullptr; 841 842 Value *PtrBase, *Index; 843 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL); 844 845 // The set of nodes that will take part in this transformation. 846 SetVector<Value *> Nodes; 847 848 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes)) 849 return nullptr; 850 851 // We know we can re-write this as 852 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) 853 // Since we've only looked through inbouds GEPs we know that we 854 // can't have overflow on either side. We can therefore re-write 855 // this as: 856 // OFFSET1 cmp OFFSET2 857 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes); 858 859 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written 860 // GEP having PtrBase as the pointer base, and has returned in NewRHS the 861 // offset. Since Index is the offset of LHS to the base pointer, we will now 862 // compare the offsets instead of comparing the pointers. 863 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS); 864 } 865 866 /// Fold comparisons between a GEP instruction and something else. At this point 867 /// we know that the GEP is on the LHS of the comparison. 868 Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, 869 ICmpInst::Predicate Cond, 870 Instruction &I) { 871 // Don't transform signed compares of GEPs into index compares. Even if the 872 // GEP is inbounds, the final add of the base pointer can have signed overflow 873 // and would change the result of the icmp. 874 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be 875 // the maximum signed value for the pointer type. 876 if (ICmpInst::isSigned(Cond)) 877 return nullptr; 878 879 // Look through bitcasts and addrspacecasts. We do not however want to remove 880 // 0 GEPs. 881 if (!isa<GetElementPtrInst>(RHS)) 882 RHS = RHS->stripPointerCasts(); 883 884 Value *PtrBase = GEPLHS->getOperand(0); 885 if (PtrBase == RHS && GEPLHS->isInBounds()) { 886 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). 887 // This transformation (ignoring the base and scales) is valid because we 888 // know pointers can't overflow since the gep is inbounds. See if we can 889 // output an optimized form. 890 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL); 891 892 // If not, synthesize the offset the hard way. 893 if (!Offset) 894 Offset = EmitGEPOffset(GEPLHS); 895 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, 896 Constant::getNullValue(Offset->getType())); 897 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { 898 // If the base pointers are different, but the indices are the same, just 899 // compare the base pointer. 900 if (PtrBase != GEPRHS->getOperand(0)) { 901 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); 902 IndicesTheSame &= GEPLHS->getOperand(0)->getType() == 903 GEPRHS->getOperand(0)->getType(); 904 if (IndicesTheSame) 905 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 906 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 907 IndicesTheSame = false; 908 break; 909 } 910 911 // If all indices are the same, just compare the base pointers. 912 Type *BaseType = GEPLHS->getOperand(0)->getType(); 913 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType()) 914 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0)); 915 916 // If we're comparing GEPs with two base pointers that only differ in type 917 // and both GEPs have only constant indices or just one use, then fold 918 // the compare with the adjusted indices. 919 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() && 920 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) && 921 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) && 922 PtrBase->stripPointerCasts() == 923 GEPRHS->getOperand(0)->stripPointerCasts()) { 924 Value *LOffset = EmitGEPOffset(GEPLHS); 925 Value *ROffset = EmitGEPOffset(GEPRHS); 926 927 // If we looked through an addrspacecast between different sized address 928 // spaces, the LHS and RHS pointers are different sized 929 // integers. Truncate to the smaller one. 930 Type *LHSIndexTy = LOffset->getType(); 931 Type *RHSIndexTy = ROffset->getType(); 932 if (LHSIndexTy != RHSIndexTy) { 933 if (LHSIndexTy->getPrimitiveSizeInBits() < 934 RHSIndexTy->getPrimitiveSizeInBits()) { 935 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy); 936 } else 937 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy); 938 } 939 940 Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond), 941 LOffset, ROffset); 942 return replaceInstUsesWith(I, Cmp); 943 } 944 945 // Otherwise, the base pointers are different and the indices are 946 // different. Try convert this to an indexed compare by looking through 947 // PHIs/casts. 948 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 949 } 950 951 // If one of the GEPs has all zero indices, recurse. 952 if (GEPLHS->hasAllZeroIndices()) 953 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0), 954 ICmpInst::getSwappedPredicate(Cond), I); 955 956 // If the other GEP has all zero indices, recurse. 957 if (GEPRHS->hasAllZeroIndices()) 958 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); 959 960 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds(); 961 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { 962 // If the GEPs only differ by one index, compare it. 963 unsigned NumDifferences = 0; // Keep track of # differences. 964 unsigned DiffOperand = 0; // The operand that differs. 965 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 966 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 967 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != 968 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { 969 // Irreconcilable differences. 970 NumDifferences = 2; 971 break; 972 } else { 973 if (NumDifferences++) break; 974 DiffOperand = i; 975 } 976 } 977 978 if (NumDifferences == 0) // SAME GEP? 979 return replaceInstUsesWith(I, // No comparison is needed here. 980 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond))); 981 982 else if (NumDifferences == 1 && GEPsInBounds) { 983 Value *LHSV = GEPLHS->getOperand(DiffOperand); 984 Value *RHSV = GEPRHS->getOperand(DiffOperand); 985 // Make sure we do a signed comparison here. 986 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); 987 } 988 } 989 990 // Only lower this if the icmp is the only user of the GEP or if we expect 991 // the result to fold to a constant! 992 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && 993 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { 994 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) 995 Value *L = EmitGEPOffset(GEPLHS); 996 Value *R = EmitGEPOffset(GEPRHS); 997 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); 998 } 999 } 1000 1001 // Try convert this to an indexed compare by looking through PHIs/casts as a 1002 // last resort. 1003 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 1004 } 1005 1006 Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI, 1007 const AllocaInst *Alloca, 1008 const Value *Other) { 1009 assert(ICI.isEquality() && "Cannot fold non-equality comparison."); 1010 1011 // It would be tempting to fold away comparisons between allocas and any 1012 // pointer not based on that alloca (e.g. an argument). However, even 1013 // though such pointers cannot alias, they can still compare equal. 1014 // 1015 // But LLVM doesn't specify where allocas get their memory, so if the alloca 1016 // doesn't escape we can argue that it's impossible to guess its value, and we 1017 // can therefore act as if any such guesses are wrong. 1018 // 1019 // The code below checks that the alloca doesn't escape, and that it's only 1020 // used in a comparison once (the current instruction). The 1021 // single-comparison-use condition ensures that we're trivially folding all 1022 // comparisons against the alloca consistently, and avoids the risk of 1023 // erroneously folding a comparison of the pointer with itself. 1024 1025 unsigned MaxIter = 32; // Break cycles and bound to constant-time. 1026 1027 SmallVector<const Use *, 32> Worklist; 1028 for (const Use &U : Alloca->uses()) { 1029 if (Worklist.size() >= MaxIter) 1030 return nullptr; 1031 Worklist.push_back(&U); 1032 } 1033 1034 unsigned NumCmps = 0; 1035 while (!Worklist.empty()) { 1036 assert(Worklist.size() <= MaxIter); 1037 const Use *U = Worklist.pop_back_val(); 1038 const Value *V = U->getUser(); 1039 --MaxIter; 1040 1041 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) || 1042 isa<SelectInst>(V)) { 1043 // Track the uses. 1044 } else if (isa<LoadInst>(V)) { 1045 // Loading from the pointer doesn't escape it. 1046 continue; 1047 } else if (const auto *SI = dyn_cast<StoreInst>(V)) { 1048 // Storing *to* the pointer is fine, but storing the pointer escapes it. 1049 if (SI->getValueOperand() == U->get()) 1050 return nullptr; 1051 continue; 1052 } else if (isa<ICmpInst>(V)) { 1053 if (NumCmps++) 1054 return nullptr; // Found more than one cmp. 1055 continue; 1056 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) { 1057 switch (Intrin->getIntrinsicID()) { 1058 // These intrinsics don't escape or compare the pointer. Memset is safe 1059 // because we don't allow ptrtoint. Memcpy and memmove are safe because 1060 // we don't allow stores, so src cannot point to V. 1061 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: 1062 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: 1063 continue; 1064 default: 1065 return nullptr; 1066 } 1067 } else { 1068 return nullptr; 1069 } 1070 for (const Use &U : V->uses()) { 1071 if (Worklist.size() >= MaxIter) 1072 return nullptr; 1073 Worklist.push_back(&U); 1074 } 1075 } 1076 1077 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType()); 1078 return replaceInstUsesWith( 1079 ICI, 1080 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate()))); 1081 } 1082 1083 /// Fold "icmp pred (X+C), X". 1084 Instruction *InstCombiner::foldICmpAddOpConst(Value *X, const APInt &C, 1085 ICmpInst::Predicate Pred) { 1086 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, 1087 // so the values can never be equal. Similarly for all other "or equals" 1088 // operators. 1089 assert(!!C && "C should not be zero!"); 1090 1091 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 1092 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 1093 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 1094 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 1095 Constant *R = ConstantInt::get(X->getType(), 1096 APInt::getMaxValue(C.getBitWidth()) - C); 1097 return new ICmpInst(ICmpInst::ICMP_UGT, X, R); 1098 } 1099 1100 // (X+1) >u X --> X <u (0-1) --> X != 255 1101 // (X+2) >u X --> X <u (0-2) --> X <u 254 1102 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 1103 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) 1104 return new ICmpInst(ICmpInst::ICMP_ULT, X, 1105 ConstantInt::get(X->getType(), -C)); 1106 1107 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth()); 1108 1109 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 1110 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 1111 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 1112 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 1113 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 1114 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 1115 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 1116 return new ICmpInst(ICmpInst::ICMP_SGT, X, 1117 ConstantInt::get(X->getType(), SMax - C)); 1118 1119 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 1120 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 1121 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 1122 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 1123 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 1124 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 1125 1126 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); 1127 return new ICmpInst(ICmpInst::ICMP_SLT, X, 1128 ConstantInt::get(X->getType(), SMax - (C - 1))); 1129 } 1130 1131 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> 1132 /// (icmp eq/ne A, Log2(AP2/AP1)) -> 1133 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)). 1134 Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A, 1135 const APInt &AP1, 1136 const APInt &AP2) { 1137 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1138 1139 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1140 if (I.getPredicate() == I.ICMP_NE) 1141 Pred = CmpInst::getInversePredicate(Pred); 1142 return new ICmpInst(Pred, LHS, RHS); 1143 }; 1144 1145 // Don't bother doing any work for cases which InstSimplify handles. 1146 if (AP2.isNullValue()) 1147 return nullptr; 1148 1149 bool IsAShr = isa<AShrOperator>(I.getOperand(0)); 1150 if (IsAShr) { 1151 if (AP2.isAllOnesValue()) 1152 return nullptr; 1153 if (AP2.isNegative() != AP1.isNegative()) 1154 return nullptr; 1155 if (AP2.sgt(AP1)) 1156 return nullptr; 1157 } 1158 1159 if (!AP1) 1160 // 'A' must be large enough to shift out the highest set bit. 1161 return getICmp(I.ICMP_UGT, A, 1162 ConstantInt::get(A->getType(), AP2.logBase2())); 1163 1164 if (AP1 == AP2) 1165 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1166 1167 int Shift; 1168 if (IsAShr && AP1.isNegative()) 1169 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes(); 1170 else 1171 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros(); 1172 1173 if (Shift > 0) { 1174 if (IsAShr && AP1 == AP2.ashr(Shift)) { 1175 // There are multiple solutions if we are comparing against -1 and the LHS 1176 // of the ashr is not a power of two. 1177 if (AP1.isAllOnesValue() && !AP2.isPowerOf2()) 1178 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift)); 1179 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1180 } else if (AP1 == AP2.lshr(Shift)) { 1181 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1182 } 1183 } 1184 1185 // Shifting const2 will never be equal to const1. 1186 // FIXME: This should always be handled by InstSimplify? 1187 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1188 return replaceInstUsesWith(I, TorF); 1189 } 1190 1191 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" -> 1192 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)). 1193 Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A, 1194 const APInt &AP1, 1195 const APInt &AP2) { 1196 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1197 1198 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1199 if (I.getPredicate() == I.ICMP_NE) 1200 Pred = CmpInst::getInversePredicate(Pred); 1201 return new ICmpInst(Pred, LHS, RHS); 1202 }; 1203 1204 // Don't bother doing any work for cases which InstSimplify handles. 1205 if (AP2.isNullValue()) 1206 return nullptr; 1207 1208 unsigned AP2TrailingZeros = AP2.countTrailingZeros(); 1209 1210 if (!AP1 && AP2TrailingZeros != 0) 1211 return getICmp( 1212 I.ICMP_UGE, A, 1213 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros)); 1214 1215 if (AP1 == AP2) 1216 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1217 1218 // Get the distance between the lowest bits that are set. 1219 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros; 1220 1221 if (Shift > 0 && AP2.shl(Shift) == AP1) 1222 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1223 1224 // Shifting const2 will never be equal to const1. 1225 // FIXME: This should always be handled by InstSimplify? 1226 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1227 return replaceInstUsesWith(I, TorF); 1228 } 1229 1230 /// The caller has matched a pattern of the form: 1231 /// I = icmp ugt (add (add A, B), CI2), CI1 1232 /// If this is of the form: 1233 /// sum = a + b 1234 /// if (sum+128 >u 255) 1235 /// Then replace it with llvm.sadd.with.overflow.i8. 1236 /// 1237 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, 1238 ConstantInt *CI2, ConstantInt *CI1, 1239 InstCombiner &IC) { 1240 // The transformation we're trying to do here is to transform this into an 1241 // llvm.sadd.with.overflow. To do this, we have to replace the original add 1242 // with a narrower add, and discard the add-with-constant that is part of the 1243 // range check (if we can't eliminate it, this isn't profitable). 1244 1245 // In order to eliminate the add-with-constant, the compare can be its only 1246 // use. 1247 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0)); 1248 if (!AddWithCst->hasOneUse()) 1249 return nullptr; 1250 1251 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. 1252 if (!CI2->getValue().isPowerOf2()) 1253 return nullptr; 1254 unsigned NewWidth = CI2->getValue().countTrailingZeros(); 1255 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) 1256 return nullptr; 1257 1258 // The width of the new add formed is 1 more than the bias. 1259 ++NewWidth; 1260 1261 // Check to see that CI1 is an all-ones value with NewWidth bits. 1262 if (CI1->getBitWidth() == NewWidth || 1263 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) 1264 return nullptr; 1265 1266 // This is only really a signed overflow check if the inputs have been 1267 // sign-extended; check for that condition. For example, if CI2 is 2^31 and 1268 // the operands of the add are 64 bits wide, we need at least 33 sign bits. 1269 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1; 1270 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits || 1271 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits) 1272 return nullptr; 1273 1274 // In order to replace the original add with a narrower 1275 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant 1276 // and truncates that discard the high bits of the add. Verify that this is 1277 // the case. 1278 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0)); 1279 for (User *U : OrigAdd->users()) { 1280 if (U == AddWithCst) 1281 continue; 1282 1283 // Only accept truncates for now. We would really like a nice recursive 1284 // predicate like SimplifyDemandedBits, but which goes downwards the use-def 1285 // chain to see which bits of a value are actually demanded. If the 1286 // original add had another add which was then immediately truncated, we 1287 // could still do the transformation. 1288 TruncInst *TI = dyn_cast<TruncInst>(U); 1289 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth) 1290 return nullptr; 1291 } 1292 1293 // If the pattern matches, truncate the inputs to the narrower type and 1294 // use the sadd_with_overflow intrinsic to efficiently compute both the 1295 // result and the overflow bit. 1296 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); 1297 Value *F = Intrinsic::getDeclaration(I.getModule(), 1298 Intrinsic::sadd_with_overflow, NewType); 1299 1300 InstCombiner::BuilderTy &Builder = IC.Builder; 1301 1302 // Put the new code above the original add, in case there are any uses of the 1303 // add between the add and the compare. 1304 Builder.SetInsertPoint(OrigAdd); 1305 1306 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc"); 1307 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc"); 1308 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd"); 1309 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result"); 1310 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType()); 1311 1312 // The inner add was the result of the narrow add, zero extended to the 1313 // wider type. Replace it with the result computed by the intrinsic. 1314 IC.replaceInstUsesWith(*OrigAdd, ZExt); 1315 1316 // The original icmp gets replaced with the overflow value. 1317 return ExtractValueInst::Create(Call, 1, "sadd.overflow"); 1318 } 1319 1320 // Handle (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0) 1321 Instruction *InstCombiner::foldICmpWithZero(ICmpInst &Cmp) { 1322 CmpInst::Predicate Pred = Cmp.getPredicate(); 1323 Value *X = Cmp.getOperand(0); 1324 1325 if (match(Cmp.getOperand(1), m_Zero()) && Pred == ICmpInst::ICMP_SGT) { 1326 Value *A, *B; 1327 SelectPatternResult SPR = matchSelectPattern(X, A, B); 1328 if (SPR.Flavor == SPF_SMIN) { 1329 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT)) 1330 return new ICmpInst(Pred, B, Cmp.getOperand(1)); 1331 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT)) 1332 return new ICmpInst(Pred, A, Cmp.getOperand(1)); 1333 } 1334 } 1335 return nullptr; 1336 } 1337 1338 /// Fold icmp Pred X, C. 1339 /// TODO: This code structure does not make sense. The saturating add fold 1340 /// should be moved to some other helper and extended as noted below (it is also 1341 /// possible that code has been made unnecessary - do we canonicalize IR to 1342 /// overflow/saturating intrinsics or not?). 1343 Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) { 1344 // Match the following pattern, which is a common idiom when writing 1345 // overflow-safe integer arithmetic functions. The source performs an addition 1346 // in wider type and explicitly checks for overflow using comparisons against 1347 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic. 1348 // 1349 // TODO: This could probably be generalized to handle other overflow-safe 1350 // operations if we worked out the formulas to compute the appropriate magic 1351 // constants. 1352 // 1353 // sum = a + b 1354 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8 1355 CmpInst::Predicate Pred = Cmp.getPredicate(); 1356 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1); 1357 Value *A, *B; 1358 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI 1359 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) && 1360 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2)))) 1361 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this)) 1362 return Res; 1363 1364 return nullptr; 1365 } 1366 1367 /// Canonicalize icmp instructions based on dominating conditions. 1368 Instruction *InstCombiner::foldICmpWithDominatingICmp(ICmpInst &Cmp) { 1369 // This is a cheap/incomplete check for dominance - just match a single 1370 // predecessor with a conditional branch. 1371 BasicBlock *CmpBB = Cmp.getParent(); 1372 BasicBlock *DomBB = CmpBB->getSinglePredecessor(); 1373 if (!DomBB) 1374 return nullptr; 1375 1376 Value *DomCond; 1377 BasicBlock *TrueBB, *FalseBB; 1378 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB))) 1379 return nullptr; 1380 1381 assert((TrueBB == CmpBB || FalseBB == CmpBB) && 1382 "Predecessor block does not point to successor?"); 1383 1384 // The branch should get simplified. Don't bother simplifying this condition. 1385 if (TrueBB == FalseBB) 1386 return nullptr; 1387 1388 CmpInst::Predicate Pred = Cmp.getPredicate(); 1389 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1); 1390 ICmpInst::Predicate DomPred; 1391 const APInt *C, *DomC; 1392 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) && 1393 match(Y, m_APInt(C))) { 1394 // We have 2 compares of a variable with constants. Calculate the constant 1395 // ranges of those compares to see if we can transform the 2nd compare: 1396 // DomBB: 1397 // DomCond = icmp DomPred X, DomC 1398 // br DomCond, CmpBB, FalseBB 1399 // CmpBB: 1400 // Cmp = icmp Pred X, C 1401 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(Pred, *C); 1402 ConstantRange DominatingCR = 1403 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC) 1404 : ConstantRange::makeExactICmpRegion( 1405 CmpInst::getInversePredicate(DomPred), *DomC); 1406 ConstantRange Intersection = DominatingCR.intersectWith(CR); 1407 ConstantRange Difference = DominatingCR.difference(CR); 1408 if (Intersection.isEmptySet()) 1409 return replaceInstUsesWith(Cmp, Builder.getFalse()); 1410 if (Difference.isEmptySet()) 1411 return replaceInstUsesWith(Cmp, Builder.getTrue()); 1412 1413 // Canonicalizing a sign bit comparison that gets used in a branch, 1414 // pessimizes codegen by generating branch on zero instruction instead 1415 // of a test and branch. So we avoid canonicalizing in such situations 1416 // because test and branch instruction has better branch displacement 1417 // than compare and branch instruction. 1418 bool UnusedBit; 1419 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit); 1420 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp))) 1421 return nullptr; 1422 1423 if (const APInt *EqC = Intersection.getSingleElement()) 1424 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC)); 1425 if (const APInt *NeC = Difference.getSingleElement()) 1426 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC)); 1427 } 1428 1429 return nullptr; 1430 } 1431 1432 /// Fold icmp (trunc X, Y), C. 1433 Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp, 1434 TruncInst *Trunc, 1435 const APInt &C) { 1436 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1437 Value *X = Trunc->getOperand(0); 1438 if (C.isOneValue() && C.getBitWidth() > 1) { 1439 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1 1440 Value *V = nullptr; 1441 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V)))) 1442 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1443 ConstantInt::get(V->getType(), 1)); 1444 } 1445 1446 if (Cmp.isEquality() && Trunc->hasOneUse()) { 1447 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all 1448 // of the high bits truncated out of x are known. 1449 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(), 1450 SrcBits = X->getType()->getScalarSizeInBits(); 1451 KnownBits Known = computeKnownBits(X, 0, &Cmp); 1452 1453 // If all the high bits are known, we can do this xform. 1454 if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) { 1455 // Pull in the high bits from known-ones set. 1456 APInt NewRHS = C.zext(SrcBits); 1457 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits); 1458 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS)); 1459 } 1460 } 1461 1462 return nullptr; 1463 } 1464 1465 /// Fold icmp (xor X, Y), C. 1466 Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp, 1467 BinaryOperator *Xor, 1468 const APInt &C) { 1469 Value *X = Xor->getOperand(0); 1470 Value *Y = Xor->getOperand(1); 1471 const APInt *XorC; 1472 if (!match(Y, m_APInt(XorC))) 1473 return nullptr; 1474 1475 // If this is a comparison that tests the signbit (X < 0) or (x > -1), 1476 // fold the xor. 1477 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1478 bool TrueIfSigned = false; 1479 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) { 1480 1481 // If the sign bit of the XorCst is not set, there is no change to 1482 // the operation, just stop using the Xor. 1483 if (!XorC->isNegative()) { 1484 Cmp.setOperand(0, X); 1485 Worklist.Add(Xor); 1486 return &Cmp; 1487 } 1488 1489 // Emit the opposite comparison. 1490 if (TrueIfSigned) 1491 return new ICmpInst(ICmpInst::ICMP_SGT, X, 1492 ConstantInt::getAllOnesValue(X->getType())); 1493 else 1494 return new ICmpInst(ICmpInst::ICMP_SLT, X, 1495 ConstantInt::getNullValue(X->getType())); 1496 } 1497 1498 if (Xor->hasOneUse()) { 1499 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask)) 1500 if (!Cmp.isEquality() && XorC->isSignMask()) { 1501 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() 1502 : Cmp.getSignedPredicate(); 1503 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC)); 1504 } 1505 1506 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask)) 1507 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) { 1508 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() 1509 : Cmp.getSignedPredicate(); 1510 Pred = Cmp.getSwappedPredicate(Pred); 1511 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC)); 1512 } 1513 } 1514 1515 // Mask constant magic can eliminate an 'xor' with unsigned compares. 1516 if (Pred == ICmpInst::ICMP_UGT) { 1517 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2) 1518 if (*XorC == ~C && (C + 1).isPowerOf2()) 1519 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 1520 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2) 1521 if (*XorC == C && (C + 1).isPowerOf2()) 1522 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); 1523 } 1524 if (Pred == ICmpInst::ICMP_ULT) { 1525 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2) 1526 if (*XorC == -C && C.isPowerOf2()) 1527 return new ICmpInst(ICmpInst::ICMP_UGT, X, 1528 ConstantInt::get(X->getType(), ~C)); 1529 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2) 1530 if (*XorC == C && (-C).isPowerOf2()) 1531 return new ICmpInst(ICmpInst::ICMP_UGT, X, 1532 ConstantInt::get(X->getType(), ~C)); 1533 } 1534 return nullptr; 1535 } 1536 1537 /// Fold icmp (and (sh X, Y), C2), C1. 1538 Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And, 1539 const APInt &C1, const APInt &C2) { 1540 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0)); 1541 if (!Shift || !Shift->isShift()) 1542 return nullptr; 1543 1544 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could 1545 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in 1546 // code produced by the clang front-end, for bitfield access. 1547 // This seemingly simple opportunity to fold away a shift turns out to be 1548 // rather complicated. See PR17827 for details. 1549 unsigned ShiftOpcode = Shift->getOpcode(); 1550 bool IsShl = ShiftOpcode == Instruction::Shl; 1551 const APInt *C3; 1552 if (match(Shift->getOperand(1), m_APInt(C3))) { 1553 bool CanFold = false; 1554 if (ShiftOpcode == Instruction::Shl) { 1555 // For a left shift, we can fold if the comparison is not signed. We can 1556 // also fold a signed comparison if the mask value and comparison value 1557 // are not negative. These constraints may not be obvious, but we can 1558 // prove that they are correct using an SMT solver. 1559 if (!Cmp.isSigned() || (!C2.isNegative() && !C1.isNegative())) 1560 CanFold = true; 1561 } else { 1562 bool IsAshr = ShiftOpcode == Instruction::AShr; 1563 // For a logical right shift, we can fold if the comparison is not signed. 1564 // We can also fold a signed comparison if the shifted mask value and the 1565 // shifted comparison value are not negative. These constraints may not be 1566 // obvious, but we can prove that they are correct using an SMT solver. 1567 // For an arithmetic shift right we can do the same, if we ensure 1568 // the And doesn't use any bits being shifted in. Normally these would 1569 // be turned into lshr by SimplifyDemandedBits, but not if there is an 1570 // additional user. 1571 if (!IsAshr || (C2.shl(*C3).lshr(*C3) == C2)) { 1572 if (!Cmp.isSigned() || 1573 (!C2.shl(*C3).isNegative() && !C1.shl(*C3).isNegative())) 1574 CanFold = true; 1575 } 1576 } 1577 1578 if (CanFold) { 1579 APInt NewCst = IsShl ? C1.lshr(*C3) : C1.shl(*C3); 1580 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3); 1581 // Check to see if we are shifting out any of the bits being compared. 1582 if (SameAsC1 != C1) { 1583 // If we shifted bits out, the fold is not going to work out. As a 1584 // special case, check to see if this means that the result is always 1585 // true or false now. 1586 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ) 1587 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType())); 1588 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) 1589 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType())); 1590 } else { 1591 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst)); 1592 APInt NewAndCst = IsShl ? C2.lshr(*C3) : C2.shl(*C3); 1593 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst)); 1594 And->setOperand(0, Shift->getOperand(0)); 1595 Worklist.Add(Shift); // Shift is dead. 1596 return &Cmp; 1597 } 1598 } 1599 } 1600 1601 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is 1602 // preferable because it allows the C2 << Y expression to be hoisted out of a 1603 // loop if Y is invariant and X is not. 1604 if (Shift->hasOneUse() && C1.isNullValue() && Cmp.isEquality() && 1605 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) { 1606 // Compute C2 << Y. 1607 Value *NewShift = 1608 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1)) 1609 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1)); 1610 1611 // Compute X & (C2 << Y). 1612 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift); 1613 Cmp.setOperand(0, NewAnd); 1614 return &Cmp; 1615 } 1616 1617 return nullptr; 1618 } 1619 1620 /// Fold icmp (and X, C2), C1. 1621 Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp, 1622 BinaryOperator *And, 1623 const APInt &C1) { 1624 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1 1625 // TODO: We canonicalize to the longer form for scalars because we have 1626 // better analysis/folds for icmp, and codegen may be better with icmp. 1627 if (Cmp.getPredicate() == CmpInst::ICMP_NE && Cmp.getType()->isVectorTy() && 1628 C1.isNullValue() && match(And->getOperand(1), m_One())) 1629 return new TruncInst(And->getOperand(0), Cmp.getType()); 1630 1631 const APInt *C2; 1632 if (!match(And->getOperand(1), m_APInt(C2))) 1633 return nullptr; 1634 1635 if (!And->hasOneUse()) 1636 return nullptr; 1637 1638 // If the LHS is an 'and' of a truncate and we can widen the and/compare to 1639 // the input width without changing the value produced, eliminate the cast: 1640 // 1641 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1' 1642 // 1643 // We can do this transformation if the constants do not have their sign bits 1644 // set or if it is an equality comparison. Extending a relational comparison 1645 // when we're checking the sign bit would not work. 1646 Value *W; 1647 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) && 1648 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) { 1649 // TODO: Is this a good transform for vectors? Wider types may reduce 1650 // throughput. Should this transform be limited (even for scalars) by using 1651 // shouldChangeType()? 1652 if (!Cmp.getType()->isVectorTy()) { 1653 Type *WideType = W->getType(); 1654 unsigned WideScalarBits = WideType->getScalarSizeInBits(); 1655 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits)); 1656 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits)); 1657 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName()); 1658 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1); 1659 } 1660 } 1661 1662 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2)) 1663 return I; 1664 1665 // (icmp pred (and (or (lshr A, B), A), 1), 0) --> 1666 // (icmp pred (and A, (or (shl 1, B), 1), 0)) 1667 // 1668 // iff pred isn't signed 1669 if (!Cmp.isSigned() && C1.isNullValue() && And->getOperand(0)->hasOneUse() && 1670 match(And->getOperand(1), m_One())) { 1671 Constant *One = cast<Constant>(And->getOperand(1)); 1672 Value *Or = And->getOperand(0); 1673 Value *A, *B, *LShr; 1674 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) && 1675 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) { 1676 unsigned UsesRemoved = 0; 1677 if (And->hasOneUse()) 1678 ++UsesRemoved; 1679 if (Or->hasOneUse()) 1680 ++UsesRemoved; 1681 if (LShr->hasOneUse()) 1682 ++UsesRemoved; 1683 1684 // Compute A & ((1 << B) | 1) 1685 Value *NewOr = nullptr; 1686 if (auto *C = dyn_cast<Constant>(B)) { 1687 if (UsesRemoved >= 1) 1688 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One); 1689 } else { 1690 if (UsesRemoved >= 3) 1691 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(), 1692 /*HasNUW=*/true), 1693 One, Or->getName()); 1694 } 1695 if (NewOr) { 1696 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName()); 1697 Cmp.setOperand(0, NewAnd); 1698 return &Cmp; 1699 } 1700 } 1701 } 1702 1703 return nullptr; 1704 } 1705 1706 /// Fold icmp (and X, Y), C. 1707 Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp, 1708 BinaryOperator *And, 1709 const APInt &C) { 1710 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C)) 1711 return I; 1712 1713 // TODO: These all require that Y is constant too, so refactor with the above. 1714 1715 // Try to optimize things like "A[i] & 42 == 0" to index computations. 1716 Value *X = And->getOperand(0); 1717 Value *Y = And->getOperand(1); 1718 if (auto *LI = dyn_cast<LoadInst>(X)) 1719 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) 1720 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1721 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 1722 !LI->isVolatile() && isa<ConstantInt>(Y)) { 1723 ConstantInt *C2 = cast<ConstantInt>(Y); 1724 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2)) 1725 return Res; 1726 } 1727 1728 if (!Cmp.isEquality()) 1729 return nullptr; 1730 1731 // X & -C == -C -> X > u ~C 1732 // X & -C != -C -> X <= u ~C 1733 // iff C is a power of 2 1734 if (Cmp.getOperand(1) == Y && (-C).isPowerOf2()) { 1735 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT 1736 : CmpInst::ICMP_ULE; 1737 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1)))); 1738 } 1739 1740 // (X & C2) == 0 -> (trunc X) >= 0 1741 // (X & C2) != 0 -> (trunc X) < 0 1742 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type. 1743 const APInt *C2; 1744 if (And->hasOneUse() && C.isNullValue() && match(Y, m_APInt(C2))) { 1745 int32_t ExactLogBase2 = C2->exactLogBase2(); 1746 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) { 1747 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1); 1748 if (And->getType()->isVectorTy()) 1749 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements()); 1750 Value *Trunc = Builder.CreateTrunc(X, NTy); 1751 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE 1752 : CmpInst::ICMP_SLT; 1753 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy)); 1754 } 1755 } 1756 1757 return nullptr; 1758 } 1759 1760 /// Fold icmp (or X, Y), C. 1761 Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, 1762 const APInt &C) { 1763 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1764 if (C.isOneValue()) { 1765 // icmp slt signum(V) 1 --> icmp slt V, 1 1766 Value *V = nullptr; 1767 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V)))) 1768 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1769 ConstantInt::get(V->getType(), 1)); 1770 } 1771 1772 // X | C == C --> X <=u C 1773 // X | C != C --> X >u C 1774 // iff C+1 is a power of 2 (C is a bitmask of the low bits) 1775 if (Cmp.isEquality() && Cmp.getOperand(1) == Or->getOperand(1) && 1776 (C + 1).isPowerOf2()) { 1777 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT; 1778 return new ICmpInst(Pred, Or->getOperand(0), Or->getOperand(1)); 1779 } 1780 1781 if (!Cmp.isEquality() || !C.isNullValue() || !Or->hasOneUse()) 1782 return nullptr; 1783 1784 Value *P, *Q; 1785 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { 1786 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 1787 // -> and (icmp eq P, null), (icmp eq Q, null). 1788 Value *CmpP = 1789 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType())); 1790 Value *CmpQ = 1791 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType())); 1792 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1793 return BinaryOperator::Create(BOpc, CmpP, CmpQ); 1794 } 1795 1796 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to 1797 // a shorter form that has more potential to be folded even further. 1798 Value *X1, *X2, *X3, *X4; 1799 if (match(Or->getOperand(0), m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) && 1800 match(Or->getOperand(1), m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) { 1801 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4) 1802 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4) 1803 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2); 1804 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4); 1805 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1806 return BinaryOperator::Create(BOpc, Cmp12, Cmp34); 1807 } 1808 1809 return nullptr; 1810 } 1811 1812 /// Fold icmp (mul X, Y), C. 1813 Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp, 1814 BinaryOperator *Mul, 1815 const APInt &C) { 1816 const APInt *MulC; 1817 if (!match(Mul->getOperand(1), m_APInt(MulC))) 1818 return nullptr; 1819 1820 // If this is a test of the sign bit and the multiply is sign-preserving with 1821 // a constant operand, use the multiply LHS operand instead. 1822 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1823 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) { 1824 if (MulC->isNegative()) 1825 Pred = ICmpInst::getSwappedPredicate(Pred); 1826 return new ICmpInst(Pred, Mul->getOperand(0), 1827 Constant::getNullValue(Mul->getType())); 1828 } 1829 1830 return nullptr; 1831 } 1832 1833 /// Fold icmp (shl 1, Y), C. 1834 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, 1835 const APInt &C) { 1836 Value *Y; 1837 if (!match(Shl, m_Shl(m_One(), m_Value(Y)))) 1838 return nullptr; 1839 1840 Type *ShiftType = Shl->getType(); 1841 unsigned TypeBits = C.getBitWidth(); 1842 bool CIsPowerOf2 = C.isPowerOf2(); 1843 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1844 if (Cmp.isUnsigned()) { 1845 // (1 << Y) pred C -> Y pred Log2(C) 1846 if (!CIsPowerOf2) { 1847 // (1 << Y) < 30 -> Y <= 4 1848 // (1 << Y) <= 30 -> Y <= 4 1849 // (1 << Y) >= 30 -> Y > 4 1850 // (1 << Y) > 30 -> Y > 4 1851 if (Pred == ICmpInst::ICMP_ULT) 1852 Pred = ICmpInst::ICMP_ULE; 1853 else if (Pred == ICmpInst::ICMP_UGE) 1854 Pred = ICmpInst::ICMP_UGT; 1855 } 1856 1857 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31 1858 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31 1859 unsigned CLog2 = C.logBase2(); 1860 if (CLog2 == TypeBits - 1) { 1861 if (Pred == ICmpInst::ICMP_UGE) 1862 Pred = ICmpInst::ICMP_EQ; 1863 else if (Pred == ICmpInst::ICMP_ULT) 1864 Pred = ICmpInst::ICMP_NE; 1865 } 1866 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2)); 1867 } else if (Cmp.isSigned()) { 1868 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1); 1869 if (C.isAllOnesValue()) { 1870 // (1 << Y) <= -1 -> Y == 31 1871 if (Pred == ICmpInst::ICMP_SLE) 1872 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 1873 1874 // (1 << Y) > -1 -> Y != 31 1875 if (Pred == ICmpInst::ICMP_SGT) 1876 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 1877 } else if (!C) { 1878 // (1 << Y) < 0 -> Y == 31 1879 // (1 << Y) <= 0 -> Y == 31 1880 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 1881 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 1882 1883 // (1 << Y) >= 0 -> Y != 31 1884 // (1 << Y) > 0 -> Y != 31 1885 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) 1886 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 1887 } 1888 } else if (Cmp.isEquality() && CIsPowerOf2) { 1889 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C.logBase2())); 1890 } 1891 1892 return nullptr; 1893 } 1894 1895 /// Fold icmp (shl X, Y), C. 1896 Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp, 1897 BinaryOperator *Shl, 1898 const APInt &C) { 1899 const APInt *ShiftVal; 1900 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal))) 1901 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal); 1902 1903 const APInt *ShiftAmt; 1904 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt))) 1905 return foldICmpShlOne(Cmp, Shl, C); 1906 1907 // Check that the shift amount is in range. If not, don't perform undefined 1908 // shifts. When the shift is visited, it will be simplified. 1909 unsigned TypeBits = C.getBitWidth(); 1910 if (ShiftAmt->uge(TypeBits)) 1911 return nullptr; 1912 1913 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1914 Value *X = Shl->getOperand(0); 1915 Type *ShType = Shl->getType(); 1916 1917 // NSW guarantees that we are only shifting out sign bits from the high bits, 1918 // so we can ASHR the compare constant without needing a mask and eliminate 1919 // the shift. 1920 if (Shl->hasNoSignedWrap()) { 1921 if (Pred == ICmpInst::ICMP_SGT) { 1922 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt) 1923 APInt ShiftedC = C.ashr(*ShiftAmt); 1924 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1925 } 1926 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) && 1927 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) { 1928 APInt ShiftedC = C.ashr(*ShiftAmt); 1929 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1930 } 1931 if (Pred == ICmpInst::ICMP_SLT) { 1932 // SLE is the same as above, but SLE is canonicalized to SLT, so convert: 1933 // (X << S) <=s C is equiv to X <=s (C >> S) for all C 1934 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX 1935 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN 1936 assert(!C.isMinSignedValue() && "Unexpected icmp slt"); 1937 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1; 1938 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1939 } 1940 // If this is a signed comparison to 0 and the shift is sign preserving, 1941 // use the shift LHS operand instead; isSignTest may change 'Pred', so only 1942 // do that if we're sure to not continue on in this function. 1943 if (isSignTest(Pred, C)) 1944 return new ICmpInst(Pred, X, Constant::getNullValue(ShType)); 1945 } 1946 1947 // NUW guarantees that we are only shifting out zero bits from the high bits, 1948 // so we can LSHR the compare constant without needing a mask and eliminate 1949 // the shift. 1950 if (Shl->hasNoUnsignedWrap()) { 1951 if (Pred == ICmpInst::ICMP_UGT) { 1952 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt) 1953 APInt ShiftedC = C.lshr(*ShiftAmt); 1954 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1955 } 1956 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) && 1957 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) { 1958 APInt ShiftedC = C.lshr(*ShiftAmt); 1959 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1960 } 1961 if (Pred == ICmpInst::ICMP_ULT) { 1962 // ULE is the same as above, but ULE is canonicalized to ULT, so convert: 1963 // (X << S) <=u C is equiv to X <=u (C >> S) for all C 1964 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u 1965 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0 1966 assert(C.ugt(0) && "ult 0 should have been eliminated"); 1967 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1; 1968 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1969 } 1970 } 1971 1972 if (Cmp.isEquality() && Shl->hasOneUse()) { 1973 // Strength-reduce the shift into an 'and'. 1974 Constant *Mask = ConstantInt::get( 1975 ShType, 1976 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue())); 1977 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask"); 1978 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt)); 1979 return new ICmpInst(Pred, And, LShrC); 1980 } 1981 1982 // Otherwise, if this is a comparison of the sign bit, simplify to and/test. 1983 bool TrueIfSigned = false; 1984 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) { 1985 // (X << 31) <s 0 --> (X & 1) != 0 1986 Constant *Mask = ConstantInt::get( 1987 ShType, 1988 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1)); 1989 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask"); 1990 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, 1991 And, Constant::getNullValue(ShType)); 1992 } 1993 1994 // Transform (icmp pred iM (shl iM %v, N), C) 1995 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N)) 1996 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N. 1997 // This enables us to get rid of the shift in favor of a trunc that may be 1998 // free on the target. It has the additional benefit of comparing to a 1999 // smaller constant that may be more target-friendly. 2000 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1); 2001 if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt && 2002 DL.isLegalInteger(TypeBits - Amt)) { 2003 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt); 2004 if (ShType->isVectorTy()) 2005 TruncTy = VectorType::get(TruncTy, ShType->getVectorNumElements()); 2006 Constant *NewC = 2007 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt)); 2008 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC); 2009 } 2010 2011 return nullptr; 2012 } 2013 2014 /// Fold icmp ({al}shr X, Y), C. 2015 Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp, 2016 BinaryOperator *Shr, 2017 const APInt &C) { 2018 // An exact shr only shifts out zero bits, so: 2019 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0 2020 Value *X = Shr->getOperand(0); 2021 CmpInst::Predicate Pred = Cmp.getPredicate(); 2022 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && 2023 C.isNullValue()) 2024 return new ICmpInst(Pred, X, Cmp.getOperand(1)); 2025 2026 const APInt *ShiftVal; 2027 if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal))) 2028 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftVal); 2029 2030 const APInt *ShiftAmt; 2031 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt))) 2032 return nullptr; 2033 2034 // Check that the shift amount is in range. If not, don't perform undefined 2035 // shifts. When the shift is visited it will be simplified. 2036 unsigned TypeBits = C.getBitWidth(); 2037 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits); 2038 if (ShAmtVal >= TypeBits || ShAmtVal == 0) 2039 return nullptr; 2040 2041 bool IsAShr = Shr->getOpcode() == Instruction::AShr; 2042 bool IsExact = Shr->isExact(); 2043 Type *ShrTy = Shr->getType(); 2044 // TODO: If we could guarantee that InstSimplify would handle all of the 2045 // constant-value-based preconditions in the folds below, then we could assert 2046 // those conditions rather than checking them. This is difficult because of 2047 // undef/poison (PR34838). 2048 if (IsAShr) { 2049 if (Pred == CmpInst::ICMP_SLT || (Pred == CmpInst::ICMP_SGT && IsExact)) { 2050 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, (C << ShAmtC) 2051 // icmp sgt (ashr exact X, ShAmtC), C --> icmp sgt X, (C << ShAmtC) 2052 APInt ShiftedC = C.shl(ShAmtVal); 2053 if (ShiftedC.ashr(ShAmtVal) == C) 2054 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2055 } 2056 if (Pred == CmpInst::ICMP_SGT) { 2057 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1 2058 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1; 2059 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() && 2060 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1)) 2061 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2062 } 2063 } else { 2064 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) { 2065 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC) 2066 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC) 2067 APInt ShiftedC = C.shl(ShAmtVal); 2068 if (ShiftedC.lshr(ShAmtVal) == C) 2069 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2070 } 2071 if (Pred == CmpInst::ICMP_UGT) { 2072 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1 2073 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1; 2074 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1)) 2075 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2076 } 2077 } 2078 2079 if (!Cmp.isEquality()) 2080 return nullptr; 2081 2082 // Handle equality comparisons of shift-by-constant. 2083 2084 // If the comparison constant changes with the shift, the comparison cannot 2085 // succeed (bits of the comparison constant cannot match the shifted value). 2086 // This should be known by InstSimplify and already be folded to true/false. 2087 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) || 2088 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) && 2089 "Expected icmp+shr simplify did not occur."); 2090 2091 // If the bits shifted out are known zero, compare the unshifted value: 2092 // (X & 4) >> 1 == 2 --> (X & 4) == 4. 2093 if (Shr->isExact()) 2094 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal)); 2095 2096 if (Shr->hasOneUse()) { 2097 // Canonicalize the shift into an 'and': 2098 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt) 2099 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); 2100 Constant *Mask = ConstantInt::get(ShrTy, Val); 2101 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask"); 2102 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal)); 2103 } 2104 2105 return nullptr; 2106 } 2107 2108 /// Fold icmp (udiv X, Y), C. 2109 Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp, 2110 BinaryOperator *UDiv, 2111 const APInt &C) { 2112 const APInt *C2; 2113 if (!match(UDiv->getOperand(0), m_APInt(C2))) 2114 return nullptr; 2115 2116 assert(*C2 != 0 && "udiv 0, X should have been simplified already."); 2117 2118 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1)) 2119 Value *Y = UDiv->getOperand(1); 2120 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) { 2121 assert(!C.isMaxValue() && 2122 "icmp ugt X, UINT_MAX should have been simplified already."); 2123 return new ICmpInst(ICmpInst::ICMP_ULE, Y, 2124 ConstantInt::get(Y->getType(), C2->udiv(C + 1))); 2125 } 2126 2127 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C) 2128 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) { 2129 assert(C != 0 && "icmp ult X, 0 should have been simplified already."); 2130 return new ICmpInst(ICmpInst::ICMP_UGT, Y, 2131 ConstantInt::get(Y->getType(), C2->udiv(C))); 2132 } 2133 2134 return nullptr; 2135 } 2136 2137 /// Fold icmp ({su}div X, Y), C. 2138 Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp, 2139 BinaryOperator *Div, 2140 const APInt &C) { 2141 // Fold: icmp pred ([us]div X, C2), C -> range test 2142 // Fold this div into the comparison, producing a range check. 2143 // Determine, based on the divide type, what the range is being 2144 // checked. If there is an overflow on the low or high side, remember 2145 // it, otherwise compute the range [low, hi) bounding the new value. 2146 // See: InsertRangeTest above for the kinds of replacements possible. 2147 const APInt *C2; 2148 if (!match(Div->getOperand(1), m_APInt(C2))) 2149 return nullptr; 2150 2151 // FIXME: If the operand types don't match the type of the divide 2152 // then don't attempt this transform. The code below doesn't have the 2153 // logic to deal with a signed divide and an unsigned compare (and 2154 // vice versa). This is because (x /s C2) <s C produces different 2155 // results than (x /s C2) <u C or (x /u C2) <s C or even 2156 // (x /u C2) <u C. Simply casting the operands and result won't 2157 // work. :( The if statement below tests that condition and bails 2158 // if it finds it. 2159 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv; 2160 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) 2161 return nullptr; 2162 2163 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with 2164 // INT_MIN will also fail if the divisor is 1. Although folds of all these 2165 // division-by-constant cases should be present, we can not assert that they 2166 // have happened before we reach this icmp instruction. 2167 if (C2->isNullValue() || C2->isOneValue() || 2168 (DivIsSigned && C2->isAllOnesValue())) 2169 return nullptr; 2170 2171 // Compute Prod = C * C2. We are essentially solving an equation of 2172 // form X / C2 = C. We solve for X by multiplying C2 and C. 2173 // By solving for X, we can turn this into a range check instead of computing 2174 // a divide. 2175 APInt Prod = C * *C2; 2176 2177 // Determine if the product overflows by seeing if the product is not equal to 2178 // the divide. Make sure we do the same kind of divide as in the LHS 2179 // instruction that we're folding. 2180 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C; 2181 2182 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2183 2184 // If the division is known to be exact, then there is no remainder from the 2185 // divide, so the covered range size is unit, otherwise it is the divisor. 2186 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2; 2187 2188 // Figure out the interval that is being checked. For example, a comparison 2189 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 2190 // Compute this interval based on the constants involved and the signedness of 2191 // the compare/divide. This computes a half-open interval, keeping track of 2192 // whether either value in the interval overflows. After analysis each 2193 // overflow variable is set to 0 if it's corresponding bound variable is valid 2194 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. 2195 int LoOverflow = 0, HiOverflow = 0; 2196 APInt LoBound, HiBound; 2197 2198 if (!DivIsSigned) { // udiv 2199 // e.g. X/5 op 3 --> [15, 20) 2200 LoBound = Prod; 2201 HiOverflow = LoOverflow = ProdOV; 2202 if (!HiOverflow) { 2203 // If this is not an exact divide, then many values in the range collapse 2204 // to the same result value. 2205 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false); 2206 } 2207 } else if (C2->isStrictlyPositive()) { // Divisor is > 0. 2208 if (C.isNullValue()) { // (X / pos) op 0 2209 // Can't overflow. e.g. X/2 op 0 --> [-1, 2) 2210 LoBound = -(RangeSize - 1); 2211 HiBound = RangeSize; 2212 } else if (C.isStrictlyPositive()) { // (X / pos) op pos 2213 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) 2214 HiOverflow = LoOverflow = ProdOV; 2215 if (!HiOverflow) 2216 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true); 2217 } else { // (X / pos) op neg 2218 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) 2219 HiBound = Prod + 1; 2220 LoOverflow = HiOverflow = ProdOV ? -1 : 0; 2221 if (!LoOverflow) { 2222 APInt DivNeg = -RangeSize; 2223 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; 2224 } 2225 } 2226 } else if (C2->isNegative()) { // Divisor is < 0. 2227 if (Div->isExact()) 2228 RangeSize.negate(); 2229 if (C.isNullValue()) { // (X / neg) op 0 2230 // e.g. X/-5 op 0 --> [-4, 5) 2231 LoBound = RangeSize + 1; 2232 HiBound = -RangeSize; 2233 if (HiBound == *C2) { // -INTMIN = INTMIN 2234 HiOverflow = 1; // [INTMIN+1, overflow) 2235 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN 2236 } 2237 } else if (C.isStrictlyPositive()) { // (X / neg) op pos 2238 // e.g. X/-5 op 3 --> [-19, -14) 2239 HiBound = Prod + 1; 2240 HiOverflow = LoOverflow = ProdOV ? -1 : 0; 2241 if (!LoOverflow) 2242 LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0; 2243 } else { // (X / neg) op neg 2244 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) 2245 LoOverflow = HiOverflow = ProdOV; 2246 if (!HiOverflow) 2247 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true); 2248 } 2249 2250 // Dividing by a negative swaps the condition. LT <-> GT 2251 Pred = ICmpInst::getSwappedPredicate(Pred); 2252 } 2253 2254 Value *X = Div->getOperand(0); 2255 switch (Pred) { 2256 default: llvm_unreachable("Unhandled icmp opcode!"); 2257 case ICmpInst::ICMP_EQ: 2258 if (LoOverflow && HiOverflow) 2259 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2260 if (HiOverflow) 2261 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 2262 ICmpInst::ICMP_UGE, X, 2263 ConstantInt::get(Div->getType(), LoBound)); 2264 if (LoOverflow) 2265 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 2266 ICmpInst::ICMP_ULT, X, 2267 ConstantInt::get(Div->getType(), HiBound)); 2268 return replaceInstUsesWith( 2269 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true)); 2270 case ICmpInst::ICMP_NE: 2271 if (LoOverflow && HiOverflow) 2272 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2273 if (HiOverflow) 2274 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 2275 ICmpInst::ICMP_ULT, X, 2276 ConstantInt::get(Div->getType(), LoBound)); 2277 if (LoOverflow) 2278 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 2279 ICmpInst::ICMP_UGE, X, 2280 ConstantInt::get(Div->getType(), HiBound)); 2281 return replaceInstUsesWith(Cmp, 2282 insertRangeTest(X, LoBound, HiBound, 2283 DivIsSigned, false)); 2284 case ICmpInst::ICMP_ULT: 2285 case ICmpInst::ICMP_SLT: 2286 if (LoOverflow == +1) // Low bound is greater than input range. 2287 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2288 if (LoOverflow == -1) // Low bound is less than input range. 2289 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2290 return new ICmpInst(Pred, X, ConstantInt::get(Div->getType(), LoBound)); 2291 case ICmpInst::ICMP_UGT: 2292 case ICmpInst::ICMP_SGT: 2293 if (HiOverflow == +1) // High bound greater than input range. 2294 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2295 if (HiOverflow == -1) // High bound less than input range. 2296 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2297 if (Pred == ICmpInst::ICMP_UGT) 2298 return new ICmpInst(ICmpInst::ICMP_UGE, X, 2299 ConstantInt::get(Div->getType(), HiBound)); 2300 return new ICmpInst(ICmpInst::ICMP_SGE, X, 2301 ConstantInt::get(Div->getType(), HiBound)); 2302 } 2303 2304 return nullptr; 2305 } 2306 2307 /// Fold icmp (sub X, Y), C. 2308 Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp, 2309 BinaryOperator *Sub, 2310 const APInt &C) { 2311 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1); 2312 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2313 2314 // The following transforms are only worth it if the only user of the subtract 2315 // is the icmp. 2316 if (!Sub->hasOneUse()) 2317 return nullptr; 2318 2319 if (Sub->hasNoSignedWrap()) { 2320 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y) 2321 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnesValue()) 2322 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 2323 2324 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y) 2325 if (Pred == ICmpInst::ICMP_SGT && C.isNullValue()) 2326 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 2327 2328 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y) 2329 if (Pred == ICmpInst::ICMP_SLT && C.isNullValue()) 2330 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 2331 2332 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y) 2333 if (Pred == ICmpInst::ICMP_SLT && C.isOneValue()) 2334 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 2335 } 2336 2337 const APInt *C2; 2338 if (!match(X, m_APInt(C2))) 2339 return nullptr; 2340 2341 // C2 - Y <u C -> (Y | (C - 1)) == C2 2342 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2 2343 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && 2344 (*C2 & (C - 1)) == (C - 1)) 2345 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X); 2346 2347 // C2 - Y >u C -> (Y | C) != C2 2348 // iff C2 & C == C and C + 1 is a power of 2 2349 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C) 2350 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X); 2351 2352 return nullptr; 2353 } 2354 2355 /// Fold icmp (add X, Y), C. 2356 Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp, 2357 BinaryOperator *Add, 2358 const APInt &C) { 2359 Value *Y = Add->getOperand(1); 2360 const APInt *C2; 2361 if (Cmp.isEquality() || !match(Y, m_APInt(C2))) 2362 return nullptr; 2363 2364 // Fold icmp pred (add X, C2), C. 2365 Value *X = Add->getOperand(0); 2366 Type *Ty = Add->getType(); 2367 CmpInst::Predicate Pred = Cmp.getPredicate(); 2368 2369 if (!Add->hasOneUse()) 2370 return nullptr; 2371 2372 // If the add does not wrap, we can always adjust the compare by subtracting 2373 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE 2374 // are canonicalized to SGT/SLT/UGT/ULT. 2375 if ((Add->hasNoSignedWrap() && 2376 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) || 2377 (Add->hasNoUnsignedWrap() && 2378 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) { 2379 bool Overflow; 2380 APInt NewC = 2381 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow); 2382 // If there is overflow, the result must be true or false. 2383 // TODO: Can we assert there is no overflow because InstSimplify always 2384 // handles those cases? 2385 if (!Overflow) 2386 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2) 2387 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC)); 2388 } 2389 2390 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2); 2391 const APInt &Upper = CR.getUpper(); 2392 const APInt &Lower = CR.getLower(); 2393 if (Cmp.isSigned()) { 2394 if (Lower.isSignMask()) 2395 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper)); 2396 if (Upper.isSignMask()) 2397 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower)); 2398 } else { 2399 if (Lower.isMinValue()) 2400 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper)); 2401 if (Upper.isMinValue()) 2402 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower)); 2403 } 2404 2405 // X+C <u C2 -> (X & -C2) == C 2406 // iff C & (C2-1) == 0 2407 // C2 is a power of 2 2408 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0) 2409 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C), 2410 ConstantExpr::getNeg(cast<Constant>(Y))); 2411 2412 // X+C >u C2 -> (X & ~C2) != C 2413 // iff C & C2 == 0 2414 // C2+1 is a power of 2 2415 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0) 2416 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C), 2417 ConstantExpr::getNeg(cast<Constant>(Y))); 2418 2419 return nullptr; 2420 } 2421 2422 bool InstCombiner::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, 2423 Value *&RHS, ConstantInt *&Less, 2424 ConstantInt *&Equal, 2425 ConstantInt *&Greater) { 2426 // TODO: Generalize this to work with other comparison idioms or ensure 2427 // they get canonicalized into this form. 2428 2429 // select i1 (a == b), i32 Equal, i32 (select i1 (a < b), i32 Less, i32 2430 // Greater), where Equal, Less and Greater are placeholders for any three 2431 // constants. 2432 ICmpInst::Predicate PredA, PredB; 2433 if (match(SI->getTrueValue(), m_ConstantInt(Equal)) && 2434 match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) && 2435 PredA == ICmpInst::ICMP_EQ && 2436 match(SI->getFalseValue(), 2437 m_Select(m_ICmp(PredB, m_Specific(LHS), m_Specific(RHS)), 2438 m_ConstantInt(Less), m_ConstantInt(Greater))) && 2439 PredB == ICmpInst::ICMP_SLT) { 2440 return true; 2441 } 2442 return false; 2443 } 2444 2445 Instruction *InstCombiner::foldICmpSelectConstant(ICmpInst &Cmp, 2446 SelectInst *Select, 2447 ConstantInt *C) { 2448 2449 assert(C && "Cmp RHS should be a constant int!"); 2450 // If we're testing a constant value against the result of a three way 2451 // comparison, the result can be expressed directly in terms of the 2452 // original values being compared. Note: We could possibly be more 2453 // aggressive here and remove the hasOneUse test. The original select is 2454 // really likely to simplify or sink when we remove a test of the result. 2455 Value *OrigLHS, *OrigRHS; 2456 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan; 2457 if (Cmp.hasOneUse() && 2458 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal, 2459 C3GreaterThan)) { 2460 assert(C1LessThan && C2Equal && C3GreaterThan); 2461 2462 bool TrueWhenLessThan = 2463 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C) 2464 ->isAllOnesValue(); 2465 bool TrueWhenEqual = 2466 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C) 2467 ->isAllOnesValue(); 2468 bool TrueWhenGreaterThan = 2469 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C) 2470 ->isAllOnesValue(); 2471 2472 // This generates the new instruction that will replace the original Cmp 2473 // Instruction. Instead of enumerating the various combinations when 2474 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus 2475 // false, we rely on chaining of ORs and future passes of InstCombine to 2476 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b). 2477 2478 // When none of the three constants satisfy the predicate for the RHS (C), 2479 // the entire original Cmp can be simplified to a false. 2480 Value *Cond = Builder.getFalse(); 2481 if (TrueWhenLessThan) 2482 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS)); 2483 if (TrueWhenEqual) 2484 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS)); 2485 if (TrueWhenGreaterThan) 2486 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS)); 2487 2488 return replaceInstUsesWith(Cmp, Cond); 2489 } 2490 return nullptr; 2491 } 2492 2493 Instruction *InstCombiner::foldICmpBitCastConstant(ICmpInst &Cmp, 2494 BitCastInst *Bitcast, 2495 const APInt &C) { 2496 // Folding: icmp <pred> iN X, C 2497 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN 2498 // and C is a splat of a K-bit pattern 2499 // and SC is a constant vector = <C', C', C', ..., C'> 2500 // Into: 2501 // %E = extractelement <M x iK> %vec, i32 C' 2502 // icmp <pred> iK %E, trunc(C) 2503 if (!Bitcast->getType()->isIntegerTy() || 2504 !Bitcast->getSrcTy()->isIntOrIntVectorTy()) 2505 return nullptr; 2506 2507 Value *BCIOp = Bitcast->getOperand(0); 2508 Value *Vec = nullptr; // 1st vector arg of the shufflevector 2509 Constant *Mask = nullptr; // Mask arg of the shufflevector 2510 if (match(BCIOp, 2511 m_ShuffleVector(m_Value(Vec), m_Undef(), m_Constant(Mask)))) { 2512 // Check whether every element of Mask is the same constant 2513 if (auto *Elem = dyn_cast_or_null<ConstantInt>(Mask->getSplatValue())) { 2514 auto *VecTy = cast<VectorType>(BCIOp->getType()); 2515 auto *EltTy = cast<IntegerType>(VecTy->getElementType()); 2516 auto Pred = Cmp.getPredicate(); 2517 if (C.isSplat(EltTy->getBitWidth())) { 2518 // Fold the icmp based on the value of C 2519 // If C is M copies of an iK sized bit pattern, 2520 // then: 2521 // => %E = extractelement <N x iK> %vec, i32 Elem 2522 // icmp <pred> iK %SplatVal, <pattern> 2523 Value *Extract = Builder.CreateExtractElement(Vec, Elem); 2524 Value *NewC = ConstantInt::get(EltTy, C.trunc(EltTy->getBitWidth())); 2525 return new ICmpInst(Pred, Extract, NewC); 2526 } 2527 } 2528 } 2529 return nullptr; 2530 } 2531 2532 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C 2533 /// where X is some kind of instruction. 2534 Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) { 2535 const APInt *C; 2536 if (!match(Cmp.getOperand(1), m_APInt(C))) 2537 return nullptr; 2538 2539 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0))) { 2540 switch (BO->getOpcode()) { 2541 case Instruction::Xor: 2542 if (Instruction *I = foldICmpXorConstant(Cmp, BO, *C)) 2543 return I; 2544 break; 2545 case Instruction::And: 2546 if (Instruction *I = foldICmpAndConstant(Cmp, BO, *C)) 2547 return I; 2548 break; 2549 case Instruction::Or: 2550 if (Instruction *I = foldICmpOrConstant(Cmp, BO, *C)) 2551 return I; 2552 break; 2553 case Instruction::Mul: 2554 if (Instruction *I = foldICmpMulConstant(Cmp, BO, *C)) 2555 return I; 2556 break; 2557 case Instruction::Shl: 2558 if (Instruction *I = foldICmpShlConstant(Cmp, BO, *C)) 2559 return I; 2560 break; 2561 case Instruction::LShr: 2562 case Instruction::AShr: 2563 if (Instruction *I = foldICmpShrConstant(Cmp, BO, *C)) 2564 return I; 2565 break; 2566 case Instruction::UDiv: 2567 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, *C)) 2568 return I; 2569 LLVM_FALLTHROUGH; 2570 case Instruction::SDiv: 2571 if (Instruction *I = foldICmpDivConstant(Cmp, BO, *C)) 2572 return I; 2573 break; 2574 case Instruction::Sub: 2575 if (Instruction *I = foldICmpSubConstant(Cmp, BO, *C)) 2576 return I; 2577 break; 2578 case Instruction::Add: 2579 if (Instruction *I = foldICmpAddConstant(Cmp, BO, *C)) 2580 return I; 2581 break; 2582 default: 2583 break; 2584 } 2585 // TODO: These folds could be refactored to be part of the above calls. 2586 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C)) 2587 return I; 2588 } 2589 2590 // Match against CmpInst LHS being instructions other than binary operators. 2591 2592 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0))) { 2593 // For now, we only support constant integers while folding the 2594 // ICMP(SELECT)) pattern. We can extend this to support vector of integers 2595 // similar to the cases handled by binary ops above. 2596 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1))) 2597 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS)) 2598 return I; 2599 } 2600 2601 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0))) { 2602 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C)) 2603 return I; 2604 } 2605 2606 if (auto *BCI = dyn_cast<BitCastInst>(Cmp.getOperand(0))) { 2607 if (Instruction *I = foldICmpBitCastConstant(Cmp, BCI, *C)) 2608 return I; 2609 } 2610 2611 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, *C)) 2612 return I; 2613 2614 return nullptr; 2615 } 2616 2617 /// Fold an icmp equality instruction with binary operator LHS and constant RHS: 2618 /// icmp eq/ne BO, C. 2619 Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp, 2620 BinaryOperator *BO, 2621 const APInt &C) { 2622 // TODO: Some of these folds could work with arbitrary constants, but this 2623 // function is limited to scalar and vector splat constants. 2624 if (!Cmp.isEquality()) 2625 return nullptr; 2626 2627 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2628 bool isICMP_NE = Pred == ICmpInst::ICMP_NE; 2629 Constant *RHS = cast<Constant>(Cmp.getOperand(1)); 2630 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); 2631 2632 switch (BO->getOpcode()) { 2633 case Instruction::SRem: 2634 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. 2635 if (C.isNullValue() && BO->hasOneUse()) { 2636 const APInt *BOC; 2637 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) { 2638 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName()); 2639 return new ICmpInst(Pred, NewRem, 2640 Constant::getNullValue(BO->getType())); 2641 } 2642 } 2643 break; 2644 case Instruction::Add: { 2645 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. 2646 const APInt *BOC; 2647 if (match(BOp1, m_APInt(BOC))) { 2648 if (BO->hasOneUse()) { 2649 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1)); 2650 return new ICmpInst(Pred, BOp0, SubC); 2651 } 2652 } else if (C.isNullValue()) { 2653 // Replace ((add A, B) != 0) with (A != -B) if A or B is 2654 // efficiently invertible, or if the add has just this one use. 2655 if (Value *NegVal = dyn_castNegVal(BOp1)) 2656 return new ICmpInst(Pred, BOp0, NegVal); 2657 if (Value *NegVal = dyn_castNegVal(BOp0)) 2658 return new ICmpInst(Pred, NegVal, BOp1); 2659 if (BO->hasOneUse()) { 2660 Value *Neg = Builder.CreateNeg(BOp1); 2661 Neg->takeName(BO); 2662 return new ICmpInst(Pred, BOp0, Neg); 2663 } 2664 } 2665 break; 2666 } 2667 case Instruction::Xor: 2668 if (BO->hasOneUse()) { 2669 if (Constant *BOC = dyn_cast<Constant>(BOp1)) { 2670 // For the xor case, we can xor two constants together, eliminating 2671 // the explicit xor. 2672 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC)); 2673 } else if (C.isNullValue()) { 2674 // Replace ((xor A, B) != 0) with (A != B) 2675 return new ICmpInst(Pred, BOp0, BOp1); 2676 } 2677 } 2678 break; 2679 case Instruction::Sub: 2680 if (BO->hasOneUse()) { 2681 const APInt *BOC; 2682 if (match(BOp0, m_APInt(BOC))) { 2683 // Replace ((sub BOC, B) != C) with (B != BOC-C). 2684 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS); 2685 return new ICmpInst(Pred, BOp1, SubC); 2686 } else if (C.isNullValue()) { 2687 // Replace ((sub A, B) != 0) with (A != B). 2688 return new ICmpInst(Pred, BOp0, BOp1); 2689 } 2690 } 2691 break; 2692 case Instruction::Or: { 2693 const APInt *BOC; 2694 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) { 2695 // Comparing if all bits outside of a constant mask are set? 2696 // Replace (X | C) == -1 with (X & ~C) == ~C. 2697 // This removes the -1 constant. 2698 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1)); 2699 Value *And = Builder.CreateAnd(BOp0, NotBOC); 2700 return new ICmpInst(Pred, And, NotBOC); 2701 } 2702 break; 2703 } 2704 case Instruction::And: { 2705 const APInt *BOC; 2706 if (match(BOp1, m_APInt(BOC))) { 2707 // If we have ((X & C) == C), turn it into ((X & C) != 0). 2708 if (C == *BOC && C.isPowerOf2()) 2709 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, 2710 BO, Constant::getNullValue(RHS->getType())); 2711 2712 // Don't perform the following transforms if the AND has multiple uses 2713 if (!BO->hasOneUse()) 2714 break; 2715 2716 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 2717 if (BOC->isSignMask()) { 2718 Constant *Zero = Constant::getNullValue(BOp0->getType()); 2719 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; 2720 return new ICmpInst(NewPred, BOp0, Zero); 2721 } 2722 2723 // ((X & ~7) == 0) --> X < 8 2724 if (C.isNullValue() && (~(*BOC) + 1).isPowerOf2()) { 2725 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1)); 2726 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 2727 return new ICmpInst(NewPred, BOp0, NegBOC); 2728 } 2729 } 2730 break; 2731 } 2732 case Instruction::Mul: 2733 if (C.isNullValue() && BO->hasNoSignedWrap()) { 2734 const APInt *BOC; 2735 if (match(BOp1, m_APInt(BOC)) && !BOC->isNullValue()) { 2736 // The trivial case (mul X, 0) is handled by InstSimplify. 2737 // General case : (mul X, C) != 0 iff X != 0 2738 // (mul X, C) == 0 iff X == 0 2739 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType())); 2740 } 2741 } 2742 break; 2743 case Instruction::UDiv: 2744 if (C.isNullValue()) { 2745 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A) 2746 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT; 2747 return new ICmpInst(NewPred, BOp1, BOp0); 2748 } 2749 break; 2750 default: 2751 break; 2752 } 2753 return nullptr; 2754 } 2755 2756 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C. 2757 Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp, 2758 const APInt &C) { 2759 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)); 2760 if (!II || !Cmp.isEquality()) 2761 return nullptr; 2762 2763 // Handle icmp {eq|ne} <intrinsic>, Constant. 2764 Type *Ty = II->getType(); 2765 switch (II->getIntrinsicID()) { 2766 case Intrinsic::bswap: 2767 Worklist.Add(II); 2768 Cmp.setOperand(0, II->getArgOperand(0)); 2769 Cmp.setOperand(1, ConstantInt::get(Ty, C.byteSwap())); 2770 return &Cmp; 2771 2772 case Intrinsic::ctlz: 2773 case Intrinsic::cttz: 2774 // ctz(A) == bitwidth(A) -> A == 0 and likewise for != 2775 if (C == C.getBitWidth()) { 2776 Worklist.Add(II); 2777 Cmp.setOperand(0, II->getArgOperand(0)); 2778 Cmp.setOperand(1, ConstantInt::getNullValue(Ty)); 2779 return &Cmp; 2780 } 2781 break; 2782 2783 case Intrinsic::ctpop: { 2784 // popcount(A) == 0 -> A == 0 and likewise for != 2785 // popcount(A) == bitwidth(A) -> A == -1 and likewise for != 2786 bool IsZero = C.isNullValue(); 2787 if (IsZero || C == C.getBitWidth()) { 2788 Worklist.Add(II); 2789 Cmp.setOperand(0, II->getArgOperand(0)); 2790 auto *NewOp = 2791 IsZero ? Constant::getNullValue(Ty) : Constant::getAllOnesValue(Ty); 2792 Cmp.setOperand(1, NewOp); 2793 return &Cmp; 2794 } 2795 break; 2796 } 2797 default: 2798 break; 2799 } 2800 2801 return nullptr; 2802 } 2803 2804 /// Handle icmp with constant (but not simple integer constant) RHS. 2805 Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) { 2806 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 2807 Constant *RHSC = dyn_cast<Constant>(Op1); 2808 Instruction *LHSI = dyn_cast<Instruction>(Op0); 2809 if (!RHSC || !LHSI) 2810 return nullptr; 2811 2812 switch (LHSI->getOpcode()) { 2813 case Instruction::GetElementPtr: 2814 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null 2815 if (RHSC->isNullValue() && 2816 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) 2817 return new ICmpInst( 2818 I.getPredicate(), LHSI->getOperand(0), 2819 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2820 break; 2821 case Instruction::PHI: 2822 // Only fold icmp into the PHI if the phi and icmp are in the same 2823 // block. If in the same block, we're encouraging jump threading. If 2824 // not, we are just pessimizing the code by making an i1 phi. 2825 if (LHSI->getParent() == I.getParent()) 2826 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI))) 2827 return NV; 2828 break; 2829 case Instruction::Select: { 2830 // If either operand of the select is a constant, we can fold the 2831 // comparison into the select arms, which will cause one to be 2832 // constant folded and the select turned into a bitwise or. 2833 Value *Op1 = nullptr, *Op2 = nullptr; 2834 ConstantInt *CI = nullptr; 2835 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { 2836 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2837 CI = dyn_cast<ConstantInt>(Op1); 2838 } 2839 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { 2840 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2841 CI = dyn_cast<ConstantInt>(Op2); 2842 } 2843 2844 // We only want to perform this transformation if it will not lead to 2845 // additional code. This is true if either both sides of the select 2846 // fold to a constant (in which case the icmp is replaced with a select 2847 // which will usually simplify) or this is the only user of the 2848 // select (in which case we are trading a select+icmp for a simpler 2849 // select+icmp) or all uses of the select can be replaced based on 2850 // dominance information ("Global cases"). 2851 bool Transform = false; 2852 if (Op1 && Op2) 2853 Transform = true; 2854 else if (Op1 || Op2) { 2855 // Local case 2856 if (LHSI->hasOneUse()) 2857 Transform = true; 2858 // Global cases 2859 else if (CI && !CI->isZero()) 2860 // When Op1 is constant try replacing select with second operand. 2861 // Otherwise Op2 is constant and try replacing select with first 2862 // operand. 2863 Transform = 2864 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1); 2865 } 2866 if (Transform) { 2867 if (!Op1) 2868 Op1 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC, 2869 I.getName()); 2870 if (!Op2) 2871 Op2 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC, 2872 I.getName()); 2873 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 2874 } 2875 break; 2876 } 2877 case Instruction::IntToPtr: 2878 // icmp pred inttoptr(X), null -> icmp pred X, 0 2879 if (RHSC->isNullValue() && 2880 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType()) 2881 return new ICmpInst( 2882 I.getPredicate(), LHSI->getOperand(0), 2883 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2884 break; 2885 2886 case Instruction::Load: 2887 // Try to optimize things like "A[i] > 4" to index computations. 2888 if (GetElementPtrInst *GEP = 2889 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 2890 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 2891 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 2892 !cast<LoadInst>(LHSI)->isVolatile()) 2893 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) 2894 return Res; 2895 } 2896 break; 2897 } 2898 2899 return nullptr; 2900 } 2901 2902 /// Some comparisons can be simplified. 2903 /// In this case, we are looking for comparisons that look like 2904 /// a check for a lossy truncation. 2905 /// Folds: 2906 /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask 2907 /// Where Mask is some pattern that produces all-ones in low bits: 2908 /// (-1 >> y) 2909 /// ((-1 << y) >> y) <- non-canonical, has extra uses 2910 /// ~(-1 << y) 2911 /// ((1 << y) + (-1)) <- non-canonical, has extra uses 2912 /// The Mask can be a constant, too. 2913 /// For some predicates, the operands are commutative. 2914 /// For others, x can only be on a specific side. 2915 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I, 2916 InstCombiner::BuilderTy &Builder) { 2917 ICmpInst::Predicate SrcPred; 2918 Value *X, *M, *Y; 2919 auto m_VariableMask = m_CombineOr( 2920 m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())), 2921 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())), 2922 m_CombineOr(m_LShr(m_AllOnes(), m_Value()), 2923 m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y)))); 2924 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask()); 2925 if (!match(&I, m_c_ICmp(SrcPred, 2926 m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)), 2927 m_Deferred(X)))) 2928 return nullptr; 2929 2930 ICmpInst::Predicate DstPred; 2931 switch (SrcPred) { 2932 case ICmpInst::Predicate::ICMP_EQ: 2933 // x & (-1 >> y) == x -> x u<= (-1 >> y) 2934 DstPred = ICmpInst::Predicate::ICMP_ULE; 2935 break; 2936 case ICmpInst::Predicate::ICMP_NE: 2937 // x & (-1 >> y) != x -> x u> (-1 >> y) 2938 DstPred = ICmpInst::Predicate::ICMP_UGT; 2939 break; 2940 case ICmpInst::Predicate::ICMP_UGT: 2941 // x u> x & (-1 >> y) -> x u> (-1 >> y) 2942 assert(X == I.getOperand(0) && "instsimplify took care of commut. variant"); 2943 DstPred = ICmpInst::Predicate::ICMP_UGT; 2944 break; 2945 case ICmpInst::Predicate::ICMP_UGE: 2946 // x & (-1 >> y) u>= x -> x u<= (-1 >> y) 2947 assert(X == I.getOperand(1) && "instsimplify took care of commut. variant"); 2948 DstPred = ICmpInst::Predicate::ICMP_ULE; 2949 break; 2950 case ICmpInst::Predicate::ICMP_ULT: 2951 // x & (-1 >> y) u< x -> x u> (-1 >> y) 2952 assert(X == I.getOperand(1) && "instsimplify took care of commut. variant"); 2953 DstPred = ICmpInst::Predicate::ICMP_UGT; 2954 break; 2955 case ICmpInst::Predicate::ICMP_ULE: 2956 // x u<= x & (-1 >> y) -> x u<= (-1 >> y) 2957 assert(X == I.getOperand(0) && "instsimplify took care of commut. variant"); 2958 DstPred = ICmpInst::Predicate::ICMP_ULE; 2959 break; 2960 case ICmpInst::Predicate::ICMP_SGT: 2961 // x s> x & (-1 >> y) -> x s> (-1 >> y) 2962 if (X != I.getOperand(0)) // X must be on LHS of comparison! 2963 return nullptr; // Ignore the other case. 2964 DstPred = ICmpInst::Predicate::ICMP_SGT; 2965 break; 2966 case ICmpInst::Predicate::ICMP_SGE: 2967 // x & (-1 >> y) s>= x -> x s<= (-1 >> y) 2968 if (X != I.getOperand(1)) // X must be on RHS of comparison! 2969 return nullptr; // Ignore the other case. 2970 if (!match(M, m_Constant())) // Can not do this fold with non-constant. 2971 return nullptr; 2972 DstPred = ICmpInst::Predicate::ICMP_SLE; 2973 break; 2974 case ICmpInst::Predicate::ICMP_SLT: 2975 // x & (-1 >> y) s< x -> x s> (-1 >> y) 2976 if (X != I.getOperand(1)) // X must be on RHS of comparison! 2977 return nullptr; // Ignore the other case. 2978 if (!match(M, m_Constant())) // Can not do this fold with non-constant. 2979 return nullptr; 2980 DstPred = ICmpInst::Predicate::ICMP_SGT; 2981 break; 2982 case ICmpInst::Predicate::ICMP_SLE: 2983 // x s<= x & (-1 >> y) -> x s<= (-1 >> y) 2984 if (X != I.getOperand(0)) // X must be on LHS of comparison! 2985 return nullptr; // Ignore the other case. 2986 DstPred = ICmpInst::Predicate::ICMP_SLE; 2987 break; 2988 default: 2989 llvm_unreachable("All possible folds are handled."); 2990 } 2991 2992 return Builder.CreateICmp(DstPred, X, M); 2993 } 2994 2995 /// Some comparisons can be simplified. 2996 /// In this case, we are looking for comparisons that look like 2997 /// a check for a lossy signed truncation. 2998 /// Folds: (MaskedBits is a constant.) 2999 /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x 3000 /// Into: 3001 /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits) 3002 /// Where KeptBits = bitwidth(%x) - MaskedBits 3003 static Value * 3004 foldICmpWithTruncSignExtendedVal(ICmpInst &I, 3005 InstCombiner::BuilderTy &Builder) { 3006 ICmpInst::Predicate SrcPred; 3007 Value *X; 3008 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef. 3009 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use. 3010 if (!match(&I, m_c_ICmp(SrcPred, 3011 m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)), 3012 m_APInt(C1))), 3013 m_Deferred(X)))) 3014 return nullptr; 3015 3016 // Potential handling of non-splats: for each element: 3017 // * if both are undef, replace with constant 0. 3018 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0. 3019 // * if both are not undef, and are different, bailout. 3020 // * else, only one is undef, then pick the non-undef one. 3021 3022 // The shift amount must be equal. 3023 if (*C0 != *C1) 3024 return nullptr; 3025 const APInt &MaskedBits = *C0; 3026 assert(MaskedBits != 0 && "shift by zero should be folded away already."); 3027 3028 ICmpInst::Predicate DstPred; 3029 switch (SrcPred) { 3030 case ICmpInst::Predicate::ICMP_EQ: 3031 // ((%x << MaskedBits) a>> MaskedBits) == %x 3032 // => 3033 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits) 3034 DstPred = ICmpInst::Predicate::ICMP_ULT; 3035 break; 3036 case ICmpInst::Predicate::ICMP_NE: 3037 // ((%x << MaskedBits) a>> MaskedBits) != %x 3038 // => 3039 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits) 3040 DstPred = ICmpInst::Predicate::ICMP_UGE; 3041 break; 3042 // FIXME: are more folds possible? 3043 default: 3044 return nullptr; 3045 } 3046 3047 auto *XType = X->getType(); 3048 const unsigned XBitWidth = XType->getScalarSizeInBits(); 3049 const APInt BitWidth = APInt(XBitWidth, XBitWidth); 3050 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched"); 3051 3052 // KeptBits = bitwidth(%x) - MaskedBits 3053 const APInt KeptBits = BitWidth - MaskedBits; 3054 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable"); 3055 // ICmpCst = (1 << KeptBits) 3056 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits); 3057 assert(ICmpCst.isPowerOf2()); 3058 // AddCst = (1 << (KeptBits-1)) 3059 const APInt AddCst = ICmpCst.lshr(1); 3060 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2()); 3061 3062 // T0 = add %x, AddCst 3063 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst)); 3064 // T1 = T0 DstPred ICmpCst 3065 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst)); 3066 3067 return T1; 3068 } 3069 3070 /// Try to fold icmp (binop), X or icmp X, (binop). 3071 /// TODO: A large part of this logic is duplicated in InstSimplify's 3072 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code 3073 /// duplication. 3074 Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { 3075 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3076 3077 // Special logic for binary operators. 3078 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0); 3079 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1); 3080 if (!BO0 && !BO1) 3081 return nullptr; 3082 3083 const CmpInst::Predicate Pred = I.getPredicate(); 3084 Value *X; 3085 3086 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare. 3087 // (Op1 + X) <u Op1 --> ~Op1 <u X 3088 // Op0 >u (Op0 + X) --> X >u ~Op0 3089 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) && 3090 Pred == ICmpInst::ICMP_ULT) 3091 return new ICmpInst(Pred, Builder.CreateNot(Op1), X); 3092 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) && 3093 Pred == ICmpInst::ICMP_UGT) 3094 return new ICmpInst(Pred, X, Builder.CreateNot(Op0)); 3095 3096 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false; 3097 if (BO0 && isa<OverflowingBinaryOperator>(BO0)) 3098 NoOp0WrapProblem = 3099 ICmpInst::isEquality(Pred) || 3100 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) || 3101 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap()); 3102 if (BO1 && isa<OverflowingBinaryOperator>(BO1)) 3103 NoOp1WrapProblem = 3104 ICmpInst::isEquality(Pred) || 3105 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) || 3106 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap()); 3107 3108 // Analyze the case when either Op0 or Op1 is an add instruction. 3109 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null). 3110 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 3111 if (BO0 && BO0->getOpcode() == Instruction::Add) { 3112 A = BO0->getOperand(0); 3113 B = BO0->getOperand(1); 3114 } 3115 if (BO1 && BO1->getOpcode() == Instruction::Add) { 3116 C = BO1->getOperand(0); 3117 D = BO1->getOperand(1); 3118 } 3119 3120 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 3121 if ((A == Op1 || B == Op1) && NoOp0WrapProblem) 3122 return new ICmpInst(Pred, A == Op1 ? B : A, 3123 Constant::getNullValue(Op1->getType())); 3124 3125 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 3126 if ((C == Op0 || D == Op0) && NoOp1WrapProblem) 3127 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()), 3128 C == Op0 ? D : C); 3129 3130 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow. 3131 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem && 3132 NoOp1WrapProblem && 3133 // Try not to increase register pressure. 3134 BO0->hasOneUse() && BO1->hasOneUse()) { 3135 // Determine Y and Z in the form icmp (X+Y), (X+Z). 3136 Value *Y, *Z; 3137 if (A == C) { 3138 // C + B == C + D -> B == D 3139 Y = B; 3140 Z = D; 3141 } else if (A == D) { 3142 // D + B == C + D -> B == C 3143 Y = B; 3144 Z = C; 3145 } else if (B == C) { 3146 // A + C == C + D -> A == D 3147 Y = A; 3148 Z = D; 3149 } else { 3150 assert(B == D); 3151 // A + D == C + D -> A == C 3152 Y = A; 3153 Z = C; 3154 } 3155 return new ICmpInst(Pred, Y, Z); 3156 } 3157 3158 // icmp slt (X + -1), Y -> icmp sle X, Y 3159 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT && 3160 match(B, m_AllOnes())) 3161 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1); 3162 3163 // icmp sge (X + -1), Y -> icmp sgt X, Y 3164 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE && 3165 match(B, m_AllOnes())) 3166 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1); 3167 3168 // icmp sle (X + 1), Y -> icmp slt X, Y 3169 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One())) 3170 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1); 3171 3172 // icmp sgt (X + 1), Y -> icmp sge X, Y 3173 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One())) 3174 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1); 3175 3176 // icmp sgt X, (Y + -1) -> icmp sge X, Y 3177 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT && 3178 match(D, m_AllOnes())) 3179 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C); 3180 3181 // icmp sle X, (Y + -1) -> icmp slt X, Y 3182 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE && 3183 match(D, m_AllOnes())) 3184 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C); 3185 3186 // icmp sge X, (Y + 1) -> icmp sgt X, Y 3187 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One())) 3188 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C); 3189 3190 // icmp slt X, (Y + 1) -> icmp sle X, Y 3191 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One())) 3192 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C); 3193 3194 // TODO: The subtraction-related identities shown below also hold, but 3195 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations 3196 // wouldn't happen even if they were implemented. 3197 // 3198 // icmp ult (X - 1), Y -> icmp ule X, Y 3199 // icmp uge (X - 1), Y -> icmp ugt X, Y 3200 // icmp ugt X, (Y - 1) -> icmp uge X, Y 3201 // icmp ule X, (Y - 1) -> icmp ult X, Y 3202 3203 // icmp ule (X + 1), Y -> icmp ult X, Y 3204 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One())) 3205 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1); 3206 3207 // icmp ugt (X + 1), Y -> icmp uge X, Y 3208 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One())) 3209 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1); 3210 3211 // icmp uge X, (Y + 1) -> icmp ugt X, Y 3212 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One())) 3213 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C); 3214 3215 // icmp ult X, (Y + 1) -> icmp ule X, Y 3216 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One())) 3217 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C); 3218 3219 // if C1 has greater magnitude than C2: 3220 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y 3221 // s.t. C3 = C1 - C2 3222 // 3223 // if C2 has greater magnitude than C1: 3224 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3) 3225 // s.t. C3 = C2 - C1 3226 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem && 3227 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) 3228 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B)) 3229 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) { 3230 const APInt &AP1 = C1->getValue(); 3231 const APInt &AP2 = C2->getValue(); 3232 if (AP1.isNegative() == AP2.isNegative()) { 3233 APInt AP1Abs = C1->getValue().abs(); 3234 APInt AP2Abs = C2->getValue().abs(); 3235 if (AP1Abs.uge(AP2Abs)) { 3236 ConstantInt *C3 = Builder.getInt(AP1 - AP2); 3237 Value *NewAdd = Builder.CreateNSWAdd(A, C3); 3238 return new ICmpInst(Pred, NewAdd, C); 3239 } else { 3240 ConstantInt *C3 = Builder.getInt(AP2 - AP1); 3241 Value *NewAdd = Builder.CreateNSWAdd(C, C3); 3242 return new ICmpInst(Pred, A, NewAdd); 3243 } 3244 } 3245 } 3246 3247 // Analyze the case when either Op0 or Op1 is a sub instruction. 3248 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null). 3249 A = nullptr; 3250 B = nullptr; 3251 C = nullptr; 3252 D = nullptr; 3253 if (BO0 && BO0->getOpcode() == Instruction::Sub) { 3254 A = BO0->getOperand(0); 3255 B = BO0->getOperand(1); 3256 } 3257 if (BO1 && BO1->getOpcode() == Instruction::Sub) { 3258 C = BO1->getOperand(0); 3259 D = BO1->getOperand(1); 3260 } 3261 3262 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow. 3263 if (A == Op1 && NoOp0WrapProblem) 3264 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B); 3265 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow. 3266 if (C == Op0 && NoOp1WrapProblem) 3267 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType())); 3268 3269 // (A - B) >u A --> A <u B 3270 if (A == Op1 && Pred == ICmpInst::ICMP_UGT) 3271 return new ICmpInst(ICmpInst::ICMP_ULT, A, B); 3272 // C <u (C - D) --> C <u D 3273 if (C == Op0 && Pred == ICmpInst::ICMP_ULT) 3274 return new ICmpInst(ICmpInst::ICMP_ULT, C, D); 3275 3276 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow. 3277 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem && 3278 // Try not to increase register pressure. 3279 BO0->hasOneUse() && BO1->hasOneUse()) 3280 return new ICmpInst(Pred, A, C); 3281 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow. 3282 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem && 3283 // Try not to increase register pressure. 3284 BO0->hasOneUse() && BO1->hasOneUse()) 3285 return new ICmpInst(Pred, D, B); 3286 3287 // icmp (0-X) < cst --> x > -cst 3288 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) { 3289 Value *X; 3290 if (match(BO0, m_Neg(m_Value(X)))) 3291 if (Constant *RHSC = dyn_cast<Constant>(Op1)) 3292 if (RHSC->isNotMinSignedValue()) 3293 return new ICmpInst(I.getSwappedPredicate(), X, 3294 ConstantExpr::getNeg(RHSC)); 3295 } 3296 3297 BinaryOperator *SRem = nullptr; 3298 // icmp (srem X, Y), Y 3299 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1)) 3300 SRem = BO0; 3301 // icmp Y, (srem X, Y) 3302 else if (BO1 && BO1->getOpcode() == Instruction::SRem && 3303 Op0 == BO1->getOperand(1)) 3304 SRem = BO1; 3305 if (SRem) { 3306 // We don't check hasOneUse to avoid increasing register pressure because 3307 // the value we use is the same value this instruction was already using. 3308 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) { 3309 default: 3310 break; 3311 case ICmpInst::ICMP_EQ: 3312 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 3313 case ICmpInst::ICMP_NE: 3314 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 3315 case ICmpInst::ICMP_SGT: 3316 case ICmpInst::ICMP_SGE: 3317 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1), 3318 Constant::getAllOnesValue(SRem->getType())); 3319 case ICmpInst::ICMP_SLT: 3320 case ICmpInst::ICMP_SLE: 3321 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1), 3322 Constant::getNullValue(SRem->getType())); 3323 } 3324 } 3325 3326 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() && 3327 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) { 3328 switch (BO0->getOpcode()) { 3329 default: 3330 break; 3331 case Instruction::Add: 3332 case Instruction::Sub: 3333 case Instruction::Xor: { 3334 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b 3335 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3336 3337 const APInt *C; 3338 if (match(BO0->getOperand(1), m_APInt(C))) { 3339 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b 3340 if (C->isSignMask()) { 3341 ICmpInst::Predicate NewPred = 3342 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); 3343 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); 3344 } 3345 3346 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b 3347 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) { 3348 ICmpInst::Predicate NewPred = 3349 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); 3350 NewPred = I.getSwappedPredicate(NewPred); 3351 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); 3352 } 3353 } 3354 break; 3355 } 3356 case Instruction::Mul: { 3357 if (!I.isEquality()) 3358 break; 3359 3360 const APInt *C; 3361 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isNullValue() && 3362 !C->isOneValue()) { 3363 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask) 3364 // Mask = -1 >> count-trailing-zeros(C). 3365 if (unsigned TZs = C->countTrailingZeros()) { 3366 Constant *Mask = ConstantInt::get( 3367 BO0->getType(), 3368 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs)); 3369 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask); 3370 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask); 3371 return new ICmpInst(Pred, And1, And2); 3372 } 3373 // If there are no trailing zeros in the multiplier, just eliminate 3374 // the multiplies (no masking is needed): 3375 // icmp eq/ne (X * C), (Y * C) --> icmp eq/ne X, Y 3376 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3377 } 3378 break; 3379 } 3380 case Instruction::UDiv: 3381 case Instruction::LShr: 3382 if (I.isSigned() || !BO0->isExact() || !BO1->isExact()) 3383 break; 3384 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3385 3386 case Instruction::SDiv: 3387 if (!I.isEquality() || !BO0->isExact() || !BO1->isExact()) 3388 break; 3389 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3390 3391 case Instruction::AShr: 3392 if (!BO0->isExact() || !BO1->isExact()) 3393 break; 3394 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3395 3396 case Instruction::Shl: { 3397 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap(); 3398 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap(); 3399 if (!NUW && !NSW) 3400 break; 3401 if (!NSW && I.isSigned()) 3402 break; 3403 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3404 } 3405 } 3406 } 3407 3408 if (BO0) { 3409 // Transform A & (L - 1) `ult` L --> L != 0 3410 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes()); 3411 auto BitwiseAnd = m_c_And(m_Value(), LSubOne); 3412 3413 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) { 3414 auto *Zero = Constant::getNullValue(BO0->getType()); 3415 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero); 3416 } 3417 } 3418 3419 if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder)) 3420 return replaceInstUsesWith(I, V); 3421 3422 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder)) 3423 return replaceInstUsesWith(I, V); 3424 3425 return nullptr; 3426 } 3427 3428 /// Fold icmp Pred min|max(X, Y), X. 3429 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) { 3430 ICmpInst::Predicate Pred = Cmp.getPredicate(); 3431 Value *Op0 = Cmp.getOperand(0); 3432 Value *X = Cmp.getOperand(1); 3433 3434 // Canonicalize minimum or maximum operand to LHS of the icmp. 3435 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) || 3436 match(X, m_c_SMax(m_Specific(Op0), m_Value())) || 3437 match(X, m_c_UMin(m_Specific(Op0), m_Value())) || 3438 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) { 3439 std::swap(Op0, X); 3440 Pred = Cmp.getSwappedPredicate(); 3441 } 3442 3443 Value *Y; 3444 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) { 3445 // smin(X, Y) == X --> X s<= Y 3446 // smin(X, Y) s>= X --> X s<= Y 3447 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE) 3448 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 3449 3450 // smin(X, Y) != X --> X s> Y 3451 // smin(X, Y) s< X --> X s> Y 3452 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT) 3453 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 3454 3455 // These cases should be handled in InstSimplify: 3456 // smin(X, Y) s<= X --> true 3457 // smin(X, Y) s> X --> false 3458 return nullptr; 3459 } 3460 3461 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) { 3462 // smax(X, Y) == X --> X s>= Y 3463 // smax(X, Y) s<= X --> X s>= Y 3464 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE) 3465 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 3466 3467 // smax(X, Y) != X --> X s< Y 3468 // smax(X, Y) s> X --> X s< Y 3469 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT) 3470 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 3471 3472 // These cases should be handled in InstSimplify: 3473 // smax(X, Y) s>= X --> true 3474 // smax(X, Y) s< X --> false 3475 return nullptr; 3476 } 3477 3478 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) { 3479 // umin(X, Y) == X --> X u<= Y 3480 // umin(X, Y) u>= X --> X u<= Y 3481 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE) 3482 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y); 3483 3484 // umin(X, Y) != X --> X u> Y 3485 // umin(X, Y) u< X --> X u> Y 3486 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT) 3487 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); 3488 3489 // These cases should be handled in InstSimplify: 3490 // umin(X, Y) u<= X --> true 3491 // umin(X, Y) u> X --> false 3492 return nullptr; 3493 } 3494 3495 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) { 3496 // umax(X, Y) == X --> X u>= Y 3497 // umax(X, Y) u<= X --> X u>= Y 3498 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE) 3499 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y); 3500 3501 // umax(X, Y) != X --> X u< Y 3502 // umax(X, Y) u> X --> X u< Y 3503 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT) 3504 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 3505 3506 // These cases should be handled in InstSimplify: 3507 // umax(X, Y) u>= X --> true 3508 // umax(X, Y) u< X --> false 3509 return nullptr; 3510 } 3511 3512 return nullptr; 3513 } 3514 3515 Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) { 3516 if (!I.isEquality()) 3517 return nullptr; 3518 3519 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3520 const CmpInst::Predicate Pred = I.getPredicate(); 3521 Value *A, *B, *C, *D; 3522 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { 3523 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 3524 Value *OtherVal = A == Op1 ? B : A; 3525 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType())); 3526 } 3527 3528 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { 3529 // A^c1 == C^c2 --> A == C^(c1^c2) 3530 ConstantInt *C1, *C2; 3531 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) && 3532 Op1->hasOneUse()) { 3533 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue()); 3534 Value *Xor = Builder.CreateXor(C, NC); 3535 return new ICmpInst(Pred, A, Xor); 3536 } 3537 3538 // A^B == A^D -> B == D 3539 if (A == C) 3540 return new ICmpInst(Pred, B, D); 3541 if (A == D) 3542 return new ICmpInst(Pred, B, C); 3543 if (B == C) 3544 return new ICmpInst(Pred, A, D); 3545 if (B == D) 3546 return new ICmpInst(Pred, A, C); 3547 } 3548 } 3549 3550 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) { 3551 // A == (A^B) -> B == 0 3552 Value *OtherVal = A == Op0 ? B : A; 3553 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType())); 3554 } 3555 3556 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 3557 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) && 3558 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) { 3559 Value *X = nullptr, *Y = nullptr, *Z = nullptr; 3560 3561 if (A == C) { 3562 X = B; 3563 Y = D; 3564 Z = A; 3565 } else if (A == D) { 3566 X = B; 3567 Y = C; 3568 Z = A; 3569 } else if (B == C) { 3570 X = A; 3571 Y = D; 3572 Z = B; 3573 } else if (B == D) { 3574 X = A; 3575 Y = C; 3576 Z = B; 3577 } 3578 3579 if (X) { // Build (X^Y) & Z 3580 Op1 = Builder.CreateXor(X, Y); 3581 Op1 = Builder.CreateAnd(Op1, Z); 3582 I.setOperand(0, Op1); 3583 I.setOperand(1, Constant::getNullValue(Op1->getType())); 3584 return &I; 3585 } 3586 } 3587 3588 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B) 3589 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B) 3590 ConstantInt *Cst1; 3591 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) && 3592 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) || 3593 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) && 3594 match(Op1, m_ZExt(m_Value(A))))) { 3595 APInt Pow2 = Cst1->getValue() + 1; 3596 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) && 3597 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth()) 3598 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType())); 3599 } 3600 3601 // (A >> C) == (B >> C) --> (A^B) u< (1 << C) 3602 // For lshr and ashr pairs. 3603 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) && 3604 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) || 3605 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) && 3606 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) { 3607 unsigned TypeBits = Cst1->getBitWidth(); 3608 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); 3609 if (ShAmt < TypeBits && ShAmt != 0) { 3610 ICmpInst::Predicate NewPred = 3611 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 3612 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted"); 3613 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt); 3614 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal)); 3615 } 3616 } 3617 3618 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0 3619 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) && 3620 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) { 3621 unsigned TypeBits = Cst1->getBitWidth(); 3622 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); 3623 if (ShAmt < TypeBits && ShAmt != 0) { 3624 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted"); 3625 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt); 3626 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal), 3627 I.getName() + ".mask"); 3628 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType())); 3629 } 3630 } 3631 3632 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to 3633 // "icmp (and X, mask), cst" 3634 uint64_t ShAmt = 0; 3635 if (Op0->hasOneUse() && 3636 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) && 3637 match(Op1, m_ConstantInt(Cst1)) && 3638 // Only do this when A has multiple uses. This is most important to do 3639 // when it exposes other optimizations. 3640 !A->hasOneUse()) { 3641 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits(); 3642 3643 if (ShAmt < ASize) { 3644 APInt MaskV = 3645 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits()); 3646 MaskV <<= ShAmt; 3647 3648 APInt CmpV = Cst1->getValue().zext(ASize); 3649 CmpV <<= ShAmt; 3650 3651 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV)); 3652 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV)); 3653 } 3654 } 3655 3656 // If both operands are byte-swapped or bit-reversed, just compare the 3657 // original values. 3658 // TODO: Move this to a function similar to foldICmpIntrinsicWithConstant() 3659 // and handle more intrinsics. 3660 if ((match(Op0, m_BSwap(m_Value(A))) && match(Op1, m_BSwap(m_Value(B)))) || 3661 (match(Op0, m_BitReverse(m_Value(A))) && 3662 match(Op1, m_BitReverse(m_Value(B))))) 3663 return new ICmpInst(Pred, A, B); 3664 3665 return nullptr; 3666 } 3667 3668 /// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so 3669 /// far. 3670 Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) { 3671 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0)); 3672 Value *LHSCIOp = LHSCI->getOperand(0); 3673 Type *SrcTy = LHSCIOp->getType(); 3674 Type *DestTy = LHSCI->getType(); 3675 Value *RHSCIOp; 3676 3677 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 3678 // integer type is the same size as the pointer type. 3679 const auto& CompatibleSizes = [&](Type* SrcTy, Type* DestTy) -> bool { 3680 if (isa<VectorType>(SrcTy)) { 3681 SrcTy = cast<VectorType>(SrcTy)->getElementType(); 3682 DestTy = cast<VectorType>(DestTy)->getElementType(); 3683 } 3684 return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth(); 3685 }; 3686 if (LHSCI->getOpcode() == Instruction::PtrToInt && 3687 CompatibleSizes(SrcTy, DestTy)) { 3688 Value *RHSOp = nullptr; 3689 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) { 3690 Value *RHSCIOp = RHSC->getOperand(0); 3691 if (RHSCIOp->getType()->getPointerAddressSpace() == 3692 LHSCIOp->getType()->getPointerAddressSpace()) { 3693 RHSOp = RHSC->getOperand(0); 3694 // If the pointer types don't match, insert a bitcast. 3695 if (LHSCIOp->getType() != RHSOp->getType()) 3696 RHSOp = Builder.CreateBitCast(RHSOp, LHSCIOp->getType()); 3697 } 3698 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) { 3699 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); 3700 } 3701 3702 if (RHSOp) 3703 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp); 3704 } 3705 3706 // The code below only handles extension cast instructions, so far. 3707 // Enforce this. 3708 if (LHSCI->getOpcode() != Instruction::ZExt && 3709 LHSCI->getOpcode() != Instruction::SExt) 3710 return nullptr; 3711 3712 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; 3713 bool isSignedCmp = ICmp.isSigned(); 3714 3715 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) { 3716 // Not an extension from the same type? 3717 RHSCIOp = CI->getOperand(0); 3718 if (RHSCIOp->getType() != LHSCIOp->getType()) 3719 return nullptr; 3720 3721 // If the signedness of the two casts doesn't agree (i.e. one is a sext 3722 // and the other is a zext), then we can't handle this. 3723 if (CI->getOpcode() != LHSCI->getOpcode()) 3724 return nullptr; 3725 3726 // Deal with equality cases early. 3727 if (ICmp.isEquality()) 3728 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); 3729 3730 // A signed comparison of sign extended values simplifies into a 3731 // signed comparison. 3732 if (isSignedCmp && isSignedExt) 3733 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); 3734 3735 // The other three cases all fold into an unsigned comparison. 3736 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp); 3737 } 3738 3739 // If we aren't dealing with a constant on the RHS, exit early. 3740 auto *C = dyn_cast<Constant>(ICmp.getOperand(1)); 3741 if (!C) 3742 return nullptr; 3743 3744 // Compute the constant that would happen if we truncated to SrcTy then 3745 // re-extended to DestTy. 3746 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy); 3747 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy); 3748 3749 // If the re-extended constant didn't change... 3750 if (Res2 == C) { 3751 // Deal with equality cases early. 3752 if (ICmp.isEquality()) 3753 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); 3754 3755 // A signed comparison of sign extended values simplifies into a 3756 // signed comparison. 3757 if (isSignedExt && isSignedCmp) 3758 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); 3759 3760 // The other three cases all fold into an unsigned comparison. 3761 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1); 3762 } 3763 3764 // The re-extended constant changed, partly changed (in the case of a vector), 3765 // or could not be determined to be equal (in the case of a constant 3766 // expression), so the constant cannot be represented in the shorter type. 3767 // Consequently, we cannot emit a simple comparison. 3768 // All the cases that fold to true or false will have already been handled 3769 // by SimplifyICmpInst, so only deal with the tricky case. 3770 3771 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C)) 3772 return nullptr; 3773 3774 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases 3775 // should have been folded away previously and not enter in here. 3776 3777 // We're performing an unsigned comp with a sign extended value. 3778 // This is true if the input is >= 0. [aka >s -1] 3779 Constant *NegOne = Constant::getAllOnesValue(SrcTy); 3780 Value *Result = Builder.CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName()); 3781 3782 // Finally, return the value computed. 3783 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT) 3784 return replaceInstUsesWith(ICmp, Result); 3785 3786 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); 3787 return BinaryOperator::CreateNot(Result); 3788 } 3789 3790 bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, 3791 Value *RHS, Instruction &OrigI, 3792 Value *&Result, Constant *&Overflow) { 3793 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS)) 3794 std::swap(LHS, RHS); 3795 3796 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) { 3797 Result = OpResult; 3798 Overflow = OverflowVal; 3799 if (ReuseName) 3800 Result->takeName(&OrigI); 3801 return true; 3802 }; 3803 3804 // If the overflow check was an add followed by a compare, the insertion point 3805 // may be pointing to the compare. We want to insert the new instructions 3806 // before the add in case there are uses of the add between the add and the 3807 // compare. 3808 Builder.SetInsertPoint(&OrigI); 3809 3810 switch (OCF) { 3811 case OCF_INVALID: 3812 llvm_unreachable("bad overflow check kind!"); 3813 3814 case OCF_UNSIGNED_ADD: { 3815 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI); 3816 if (OR == OverflowResult::NeverOverflows) 3817 return SetResult(Builder.CreateNUWAdd(LHS, RHS), Builder.getFalse(), 3818 true); 3819 3820 if (OR == OverflowResult::AlwaysOverflows) 3821 return SetResult(Builder.CreateAdd(LHS, RHS), Builder.getTrue(), true); 3822 3823 // Fall through uadd into sadd 3824 LLVM_FALLTHROUGH; 3825 } 3826 case OCF_SIGNED_ADD: { 3827 // X + 0 -> {X, false} 3828 if (match(RHS, m_Zero())) 3829 return SetResult(LHS, Builder.getFalse(), false); 3830 3831 // We can strength reduce this signed add into a regular add if we can prove 3832 // that it will never overflow. 3833 if (OCF == OCF_SIGNED_ADD) 3834 if (willNotOverflowSignedAdd(LHS, RHS, OrigI)) 3835 return SetResult(Builder.CreateNSWAdd(LHS, RHS), Builder.getFalse(), 3836 true); 3837 break; 3838 } 3839 3840 case OCF_UNSIGNED_SUB: 3841 case OCF_SIGNED_SUB: { 3842 // X - 0 -> {X, false} 3843 if (match(RHS, m_Zero())) 3844 return SetResult(LHS, Builder.getFalse(), false); 3845 3846 if (OCF == OCF_SIGNED_SUB) { 3847 if (willNotOverflowSignedSub(LHS, RHS, OrigI)) 3848 return SetResult(Builder.CreateNSWSub(LHS, RHS), Builder.getFalse(), 3849 true); 3850 } else { 3851 if (willNotOverflowUnsignedSub(LHS, RHS, OrigI)) 3852 return SetResult(Builder.CreateNUWSub(LHS, RHS), Builder.getFalse(), 3853 true); 3854 } 3855 break; 3856 } 3857 3858 case OCF_UNSIGNED_MUL: { 3859 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI); 3860 if (OR == OverflowResult::NeverOverflows) 3861 return SetResult(Builder.CreateNUWMul(LHS, RHS), Builder.getFalse(), 3862 true); 3863 if (OR == OverflowResult::AlwaysOverflows) 3864 return SetResult(Builder.CreateMul(LHS, RHS), Builder.getTrue(), true); 3865 LLVM_FALLTHROUGH; 3866 } 3867 case OCF_SIGNED_MUL: 3868 // X * undef -> undef 3869 if (isa<UndefValue>(RHS)) 3870 return SetResult(RHS, UndefValue::get(Builder.getInt1Ty()), false); 3871 3872 // X * 0 -> {0, false} 3873 if (match(RHS, m_Zero())) 3874 return SetResult(RHS, Builder.getFalse(), false); 3875 3876 // X * 1 -> {X, false} 3877 if (match(RHS, m_One())) 3878 return SetResult(LHS, Builder.getFalse(), false); 3879 3880 if (OCF == OCF_SIGNED_MUL) 3881 if (willNotOverflowSignedMul(LHS, RHS, OrigI)) 3882 return SetResult(Builder.CreateNSWMul(LHS, RHS), Builder.getFalse(), 3883 true); 3884 break; 3885 } 3886 3887 return false; 3888 } 3889 3890 /// Recognize and process idiom involving test for multiplication 3891 /// overflow. 3892 /// 3893 /// The caller has matched a pattern of the form: 3894 /// I = cmp u (mul(zext A, zext B), V 3895 /// The function checks if this is a test for overflow and if so replaces 3896 /// multiplication with call to 'mul.with.overflow' intrinsic. 3897 /// 3898 /// \param I Compare instruction. 3899 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of 3900 /// the compare instruction. Must be of integer type. 3901 /// \param OtherVal The other argument of compare instruction. 3902 /// \returns Instruction which must replace the compare instruction, NULL if no 3903 /// replacement required. 3904 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal, 3905 Value *OtherVal, InstCombiner &IC) { 3906 // Don't bother doing this transformation for pointers, don't do it for 3907 // vectors. 3908 if (!isa<IntegerType>(MulVal->getType())) 3909 return nullptr; 3910 3911 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal); 3912 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal); 3913 auto *MulInstr = dyn_cast<Instruction>(MulVal); 3914 if (!MulInstr) 3915 return nullptr; 3916 assert(MulInstr->getOpcode() == Instruction::Mul); 3917 3918 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)), 3919 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1)); 3920 assert(LHS->getOpcode() == Instruction::ZExt); 3921 assert(RHS->getOpcode() == Instruction::ZExt); 3922 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0); 3923 3924 // Calculate type and width of the result produced by mul.with.overflow. 3925 Type *TyA = A->getType(), *TyB = B->getType(); 3926 unsigned WidthA = TyA->getPrimitiveSizeInBits(), 3927 WidthB = TyB->getPrimitiveSizeInBits(); 3928 unsigned MulWidth; 3929 Type *MulType; 3930 if (WidthB > WidthA) { 3931 MulWidth = WidthB; 3932 MulType = TyB; 3933 } else { 3934 MulWidth = WidthA; 3935 MulType = TyA; 3936 } 3937 3938 // In order to replace the original mul with a narrower mul.with.overflow, 3939 // all uses must ignore upper bits of the product. The number of used low 3940 // bits must be not greater than the width of mul.with.overflow. 3941 if (MulVal->hasNUsesOrMore(2)) 3942 for (User *U : MulVal->users()) { 3943 if (U == &I) 3944 continue; 3945 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 3946 // Check if truncation ignores bits above MulWidth. 3947 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits(); 3948 if (TruncWidth > MulWidth) 3949 return nullptr; 3950 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 3951 // Check if AND ignores bits above MulWidth. 3952 if (BO->getOpcode() != Instruction::And) 3953 return nullptr; 3954 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 3955 const APInt &CVal = CI->getValue(); 3956 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth) 3957 return nullptr; 3958 } else { 3959 // In this case we could have the operand of the binary operation 3960 // being defined in another block, and performing the replacement 3961 // could break the dominance relation. 3962 return nullptr; 3963 } 3964 } else { 3965 // Other uses prohibit this transformation. 3966 return nullptr; 3967 } 3968 } 3969 3970 // Recognize patterns 3971 switch (I.getPredicate()) { 3972 case ICmpInst::ICMP_EQ: 3973 case ICmpInst::ICMP_NE: 3974 // Recognize pattern: 3975 // mulval = mul(zext A, zext B) 3976 // cmp eq/neq mulval, zext trunc mulval 3977 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal)) 3978 if (Zext->hasOneUse()) { 3979 Value *ZextArg = Zext->getOperand(0); 3980 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg)) 3981 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth) 3982 break; //Recognized 3983 } 3984 3985 // Recognize pattern: 3986 // mulval = mul(zext A, zext B) 3987 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits. 3988 ConstantInt *CI; 3989 Value *ValToMask; 3990 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) { 3991 if (ValToMask != MulVal) 3992 return nullptr; 3993 const APInt &CVal = CI->getValue() + 1; 3994 if (CVal.isPowerOf2()) { 3995 unsigned MaskWidth = CVal.logBase2(); 3996 if (MaskWidth == MulWidth) 3997 break; // Recognized 3998 } 3999 } 4000 return nullptr; 4001 4002 case ICmpInst::ICMP_UGT: 4003 // Recognize pattern: 4004 // mulval = mul(zext A, zext B) 4005 // cmp ugt mulval, max 4006 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4007 APInt MaxVal = APInt::getMaxValue(MulWidth); 4008 MaxVal = MaxVal.zext(CI->getBitWidth()); 4009 if (MaxVal.eq(CI->getValue())) 4010 break; // Recognized 4011 } 4012 return nullptr; 4013 4014 case ICmpInst::ICMP_UGE: 4015 // Recognize pattern: 4016 // mulval = mul(zext A, zext B) 4017 // cmp uge mulval, max+1 4018 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4019 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 4020 if (MaxVal.eq(CI->getValue())) 4021 break; // Recognized 4022 } 4023 return nullptr; 4024 4025 case ICmpInst::ICMP_ULE: 4026 // Recognize pattern: 4027 // mulval = mul(zext A, zext B) 4028 // cmp ule mulval, max 4029 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4030 APInt MaxVal = APInt::getMaxValue(MulWidth); 4031 MaxVal = MaxVal.zext(CI->getBitWidth()); 4032 if (MaxVal.eq(CI->getValue())) 4033 break; // Recognized 4034 } 4035 return nullptr; 4036 4037 case ICmpInst::ICMP_ULT: 4038 // Recognize pattern: 4039 // mulval = mul(zext A, zext B) 4040 // cmp ule mulval, max + 1 4041 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4042 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 4043 if (MaxVal.eq(CI->getValue())) 4044 break; // Recognized 4045 } 4046 return nullptr; 4047 4048 default: 4049 return nullptr; 4050 } 4051 4052 InstCombiner::BuilderTy &Builder = IC.Builder; 4053 Builder.SetInsertPoint(MulInstr); 4054 4055 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B) 4056 Value *MulA = A, *MulB = B; 4057 if (WidthA < MulWidth) 4058 MulA = Builder.CreateZExt(A, MulType); 4059 if (WidthB < MulWidth) 4060 MulB = Builder.CreateZExt(B, MulType); 4061 Value *F = Intrinsic::getDeclaration(I.getModule(), 4062 Intrinsic::umul_with_overflow, MulType); 4063 CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul"); 4064 IC.Worklist.Add(MulInstr); 4065 4066 // If there are uses of mul result other than the comparison, we know that 4067 // they are truncation or binary AND. Change them to use result of 4068 // mul.with.overflow and adjust properly mask/size. 4069 if (MulVal->hasNUsesOrMore(2)) { 4070 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value"); 4071 for (auto UI = MulVal->user_begin(), UE = MulVal->user_end(); UI != UE;) { 4072 User *U = *UI++; 4073 if (U == &I || U == OtherVal) 4074 continue; 4075 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 4076 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth) 4077 IC.replaceInstUsesWith(*TI, Mul); 4078 else 4079 TI->setOperand(0, Mul); 4080 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 4081 assert(BO->getOpcode() == Instruction::And); 4082 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask) 4083 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1)); 4084 APInt ShortMask = CI->getValue().trunc(MulWidth); 4085 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask); 4086 Instruction *Zext = 4087 cast<Instruction>(Builder.CreateZExt(ShortAnd, BO->getType())); 4088 IC.Worklist.Add(Zext); 4089 IC.replaceInstUsesWith(*BO, Zext); 4090 } else { 4091 llvm_unreachable("Unexpected Binary operation"); 4092 } 4093 IC.Worklist.Add(cast<Instruction>(U)); 4094 } 4095 } 4096 if (isa<Instruction>(OtherVal)) 4097 IC.Worklist.Add(cast<Instruction>(OtherVal)); 4098 4099 // The original icmp gets replaced with the overflow value, maybe inverted 4100 // depending on predicate. 4101 bool Inverse = false; 4102 switch (I.getPredicate()) { 4103 case ICmpInst::ICMP_NE: 4104 break; 4105 case ICmpInst::ICMP_EQ: 4106 Inverse = true; 4107 break; 4108 case ICmpInst::ICMP_UGT: 4109 case ICmpInst::ICMP_UGE: 4110 if (I.getOperand(0) == MulVal) 4111 break; 4112 Inverse = true; 4113 break; 4114 case ICmpInst::ICMP_ULT: 4115 case ICmpInst::ICMP_ULE: 4116 if (I.getOperand(1) == MulVal) 4117 break; 4118 Inverse = true; 4119 break; 4120 default: 4121 llvm_unreachable("Unexpected predicate"); 4122 } 4123 if (Inverse) { 4124 Value *Res = Builder.CreateExtractValue(Call, 1); 4125 return BinaryOperator::CreateNot(Res); 4126 } 4127 4128 return ExtractValueInst::Create(Call, 1); 4129 } 4130 4131 /// When performing a comparison against a constant, it is possible that not all 4132 /// the bits in the LHS are demanded. This helper method computes the mask that 4133 /// IS demanded. 4134 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) { 4135 const APInt *RHS; 4136 if (!match(I.getOperand(1), m_APInt(RHS))) 4137 return APInt::getAllOnesValue(BitWidth); 4138 4139 // If this is a normal comparison, it demands all bits. If it is a sign bit 4140 // comparison, it only demands the sign bit. 4141 bool UnusedBit; 4142 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit)) 4143 return APInt::getSignMask(BitWidth); 4144 4145 switch (I.getPredicate()) { 4146 // For a UGT comparison, we don't care about any bits that 4147 // correspond to the trailing ones of the comparand. The value of these 4148 // bits doesn't impact the outcome of the comparison, because any value 4149 // greater than the RHS must differ in a bit higher than these due to carry. 4150 case ICmpInst::ICMP_UGT: 4151 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes()); 4152 4153 // Similarly, for a ULT comparison, we don't care about the trailing zeros. 4154 // Any value less than the RHS must differ in a higher bit because of carries. 4155 case ICmpInst::ICMP_ULT: 4156 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros()); 4157 4158 default: 4159 return APInt::getAllOnesValue(BitWidth); 4160 } 4161 } 4162 4163 /// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst 4164 /// should be swapped. 4165 /// The decision is based on how many times these two operands are reused 4166 /// as subtract operands and their positions in those instructions. 4167 /// The rationale is that several architectures use the same instruction for 4168 /// both subtract and cmp. Thus, it is better if the order of those operands 4169 /// match. 4170 /// \return true if Op0 and Op1 should be swapped. 4171 static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) { 4172 // Filter out pointer values as those cannot appear directly in subtract. 4173 // FIXME: we may want to go through inttoptrs or bitcasts. 4174 if (Op0->getType()->isPointerTy()) 4175 return false; 4176 // If a subtract already has the same operands as a compare, swapping would be 4177 // bad. If a subtract has the same operands as a compare but in reverse order, 4178 // then swapping is good. 4179 int GoodToSwap = 0; 4180 for (const User *U : Op0->users()) { 4181 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0)))) 4182 GoodToSwap++; 4183 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1)))) 4184 GoodToSwap--; 4185 } 4186 return GoodToSwap > 0; 4187 } 4188 4189 /// Check that one use is in the same block as the definition and all 4190 /// other uses are in blocks dominated by a given block. 4191 /// 4192 /// \param DI Definition 4193 /// \param UI Use 4194 /// \param DB Block that must dominate all uses of \p DI outside 4195 /// the parent block 4196 /// \return true when \p UI is the only use of \p DI in the parent block 4197 /// and all other uses of \p DI are in blocks dominated by \p DB. 4198 /// 4199 bool InstCombiner::dominatesAllUses(const Instruction *DI, 4200 const Instruction *UI, 4201 const BasicBlock *DB) const { 4202 assert(DI && UI && "Instruction not defined\n"); 4203 // Ignore incomplete definitions. 4204 if (!DI->getParent()) 4205 return false; 4206 // DI and UI must be in the same block. 4207 if (DI->getParent() != UI->getParent()) 4208 return false; 4209 // Protect from self-referencing blocks. 4210 if (DI->getParent() == DB) 4211 return false; 4212 for (const User *U : DI->users()) { 4213 auto *Usr = cast<Instruction>(U); 4214 if (Usr != UI && !DT.dominates(DB, Usr->getParent())) 4215 return false; 4216 } 4217 return true; 4218 } 4219 4220 /// Return true when the instruction sequence within a block is select-cmp-br. 4221 static bool isChainSelectCmpBranch(const SelectInst *SI) { 4222 const BasicBlock *BB = SI->getParent(); 4223 if (!BB) 4224 return false; 4225 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator()); 4226 if (!BI || BI->getNumSuccessors() != 2) 4227 return false; 4228 auto *IC = dyn_cast<ICmpInst>(BI->getCondition()); 4229 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI)) 4230 return false; 4231 return true; 4232 } 4233 4234 /// True when a select result is replaced by one of its operands 4235 /// in select-icmp sequence. This will eventually result in the elimination 4236 /// of the select. 4237 /// 4238 /// \param SI Select instruction 4239 /// \param Icmp Compare instruction 4240 /// \param SIOpd Operand that replaces the select 4241 /// 4242 /// Notes: 4243 /// - The replacement is global and requires dominator information 4244 /// - The caller is responsible for the actual replacement 4245 /// 4246 /// Example: 4247 /// 4248 /// entry: 4249 /// %4 = select i1 %3, %C* %0, %C* null 4250 /// %5 = icmp eq %C* %4, null 4251 /// br i1 %5, label %9, label %7 4252 /// ... 4253 /// ; <label>:7 ; preds = %entry 4254 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0 4255 /// ... 4256 /// 4257 /// can be transformed to 4258 /// 4259 /// %5 = icmp eq %C* %0, null 4260 /// %6 = select i1 %3, i1 %5, i1 true 4261 /// br i1 %6, label %9, label %7 4262 /// ... 4263 /// ; <label>:7 ; preds = %entry 4264 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0! 4265 /// 4266 /// Similar when the first operand of the select is a constant or/and 4267 /// the compare is for not equal rather than equal. 4268 /// 4269 /// NOTE: The function is only called when the select and compare constants 4270 /// are equal, the optimization can work only for EQ predicates. This is not a 4271 /// major restriction since a NE compare should be 'normalized' to an equal 4272 /// compare, which usually happens in the combiner and test case 4273 /// select-cmp-br.ll checks for it. 4274 bool InstCombiner::replacedSelectWithOperand(SelectInst *SI, 4275 const ICmpInst *Icmp, 4276 const unsigned SIOpd) { 4277 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!"); 4278 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) { 4279 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1); 4280 // The check for the single predecessor is not the best that can be 4281 // done. But it protects efficiently against cases like when SI's 4282 // home block has two successors, Succ and Succ1, and Succ1 predecessor 4283 // of Succ. Then SI can't be replaced by SIOpd because the use that gets 4284 // replaced can be reached on either path. So the uniqueness check 4285 // guarantees that the path all uses of SI (outside SI's parent) are on 4286 // is disjoint from all other paths out of SI. But that information 4287 // is more expensive to compute, and the trade-off here is in favor 4288 // of compile-time. It should also be noticed that we check for a single 4289 // predecessor and not only uniqueness. This to handle the situation when 4290 // Succ and Succ1 points to the same basic block. 4291 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) { 4292 NumSel++; 4293 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent()); 4294 return true; 4295 } 4296 } 4297 return false; 4298 } 4299 4300 /// Try to fold the comparison based on range information we can get by checking 4301 /// whether bits are known to be zero or one in the inputs. 4302 Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) { 4303 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4304 Type *Ty = Op0->getType(); 4305 ICmpInst::Predicate Pred = I.getPredicate(); 4306 4307 // Get scalar or pointer size. 4308 unsigned BitWidth = Ty->isIntOrIntVectorTy() 4309 ? Ty->getScalarSizeInBits() 4310 : DL.getIndexTypeSizeInBits(Ty->getScalarType()); 4311 4312 if (!BitWidth) 4313 return nullptr; 4314 4315 KnownBits Op0Known(BitWidth); 4316 KnownBits Op1Known(BitWidth); 4317 4318 if (SimplifyDemandedBits(&I, 0, 4319 getDemandedBitsLHSMask(I, BitWidth), 4320 Op0Known, 0)) 4321 return &I; 4322 4323 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnesValue(BitWidth), 4324 Op1Known, 0)) 4325 return &I; 4326 4327 // Given the known and unknown bits, compute a range that the LHS could be 4328 // in. Compute the Min, Max and RHS values based on the known bits. For the 4329 // EQ and NE we use unsigned values. 4330 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); 4331 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); 4332 if (I.isSigned()) { 4333 computeSignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max); 4334 computeSignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max); 4335 } else { 4336 computeUnsignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max); 4337 computeUnsignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max); 4338 } 4339 4340 // If Min and Max are known to be the same, then SimplifyDemandedBits figured 4341 // out that the LHS or RHS is a constant. Constant fold this now, so that 4342 // code below can assume that Min != Max. 4343 if (!isa<Constant>(Op0) && Op0Min == Op0Max) 4344 return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1); 4345 if (!isa<Constant>(Op1) && Op1Min == Op1Max) 4346 return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min)); 4347 4348 // Based on the range information we know about the LHS, see if we can 4349 // simplify this comparison. For example, (x&4) < 8 is always true. 4350 switch (Pred) { 4351 default: 4352 llvm_unreachable("Unknown icmp opcode!"); 4353 case ICmpInst::ICMP_EQ: 4354 case ICmpInst::ICMP_NE: { 4355 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) { 4356 return Pred == CmpInst::ICMP_EQ 4357 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())) 4358 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4359 } 4360 4361 // If all bits are known zero except for one, then we know at most one bit 4362 // is set. If the comparison is against zero, then this is a check to see if 4363 // *that* bit is set. 4364 APInt Op0KnownZeroInverted = ~Op0Known.Zero; 4365 if (Op1Known.isZero()) { 4366 // If the LHS is an AND with the same constant, look through it. 4367 Value *LHS = nullptr; 4368 const APInt *LHSC; 4369 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) || 4370 *LHSC != Op0KnownZeroInverted) 4371 LHS = Op0; 4372 4373 Value *X; 4374 if (match(LHS, m_Shl(m_One(), m_Value(X)))) { 4375 APInt ValToCheck = Op0KnownZeroInverted; 4376 Type *XTy = X->getType(); 4377 if (ValToCheck.isPowerOf2()) { 4378 // ((1 << X) & 8) == 0 -> X != 3 4379 // ((1 << X) & 8) != 0 -> X == 3 4380 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); 4381 auto NewPred = ICmpInst::getInversePredicate(Pred); 4382 return new ICmpInst(NewPred, X, CmpC); 4383 } else if ((++ValToCheck).isPowerOf2()) { 4384 // ((1 << X) & 7) == 0 -> X >= 3 4385 // ((1 << X) & 7) != 0 -> X < 3 4386 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); 4387 auto NewPred = 4388 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT; 4389 return new ICmpInst(NewPred, X, CmpC); 4390 } 4391 } 4392 4393 // Check if the LHS is 8 >>u x and the result is a power of 2 like 1. 4394 const APInt *CI; 4395 if (Op0KnownZeroInverted.isOneValue() && 4396 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) { 4397 // ((8 >>u X) & 1) == 0 -> X != 3 4398 // ((8 >>u X) & 1) != 0 -> X == 3 4399 unsigned CmpVal = CI->countTrailingZeros(); 4400 auto NewPred = ICmpInst::getInversePredicate(Pred); 4401 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal)); 4402 } 4403 } 4404 break; 4405 } 4406 case ICmpInst::ICMP_ULT: { 4407 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) 4408 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4409 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) 4410 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4411 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) 4412 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4413 4414 const APInt *CmpC; 4415 if (match(Op1, m_APInt(CmpC))) { 4416 // A <u C -> A == C-1 if min(A)+1 == C 4417 if (*CmpC == Op0Min + 1) 4418 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4419 ConstantInt::get(Op1->getType(), *CmpC - 1)); 4420 // X <u C --> X == 0, if the number of zero bits in the bottom of X 4421 // exceeds the log2 of C. 4422 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2()) 4423 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4424 Constant::getNullValue(Op1->getType())); 4425 } 4426 break; 4427 } 4428 case ICmpInst::ICMP_UGT: { 4429 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) 4430 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4431 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) 4432 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4433 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) 4434 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4435 4436 const APInt *CmpC; 4437 if (match(Op1, m_APInt(CmpC))) { 4438 // A >u C -> A == C+1 if max(a)-1 == C 4439 if (*CmpC == Op0Max - 1) 4440 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4441 ConstantInt::get(Op1->getType(), *CmpC + 1)); 4442 // X >u C --> X != 0, if the number of zero bits in the bottom of X 4443 // exceeds the log2 of C. 4444 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits()) 4445 return new ICmpInst(ICmpInst::ICMP_NE, Op0, 4446 Constant::getNullValue(Op1->getType())); 4447 } 4448 break; 4449 } 4450 case ICmpInst::ICMP_SLT: { 4451 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) 4452 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4453 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) 4454 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4455 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) 4456 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4457 const APInt *CmpC; 4458 if (match(Op1, m_APInt(CmpC))) { 4459 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C 4460 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4461 ConstantInt::get(Op1->getType(), *CmpC - 1)); 4462 } 4463 break; 4464 } 4465 case ICmpInst::ICMP_SGT: { 4466 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) 4467 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4468 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) 4469 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4470 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) 4471 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4472 const APInt *CmpC; 4473 if (match(Op1, m_APInt(CmpC))) { 4474 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C 4475 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4476 ConstantInt::get(Op1->getType(), *CmpC + 1)); 4477 } 4478 break; 4479 } 4480 case ICmpInst::ICMP_SGE: 4481 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); 4482 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) 4483 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4484 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) 4485 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4486 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B) 4487 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 4488 break; 4489 case ICmpInst::ICMP_SLE: 4490 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); 4491 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) 4492 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4493 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) 4494 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4495 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B) 4496 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 4497 break; 4498 case ICmpInst::ICMP_UGE: 4499 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); 4500 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) 4501 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4502 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) 4503 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4504 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B) 4505 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 4506 break; 4507 case ICmpInst::ICMP_ULE: 4508 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); 4509 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) 4510 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4511 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) 4512 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4513 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B) 4514 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 4515 break; 4516 } 4517 4518 // Turn a signed comparison into an unsigned one if both operands are known to 4519 // have the same sign. 4520 if (I.isSigned() && 4521 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) || 4522 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) 4523 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); 4524 4525 return nullptr; 4526 } 4527 4528 /// If we have an icmp le or icmp ge instruction with a constant operand, turn 4529 /// it into the appropriate icmp lt or icmp gt instruction. This transform 4530 /// allows them to be folded in visitICmpInst. 4531 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) { 4532 ICmpInst::Predicate Pred = I.getPredicate(); 4533 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE && 4534 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE) 4535 return nullptr; 4536 4537 Value *Op0 = I.getOperand(0); 4538 Value *Op1 = I.getOperand(1); 4539 auto *Op1C = dyn_cast<Constant>(Op1); 4540 if (!Op1C) 4541 return nullptr; 4542 4543 // Check if the constant operand can be safely incremented/decremented without 4544 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled 4545 // the edge cases for us, so we just assert on them. For vectors, we must 4546 // handle the edge cases. 4547 Type *Op1Type = Op1->getType(); 4548 bool IsSigned = I.isSigned(); 4549 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE); 4550 auto *CI = dyn_cast<ConstantInt>(Op1C); 4551 if (CI) { 4552 // A <= MAX -> TRUE ; A >= MIN -> TRUE 4553 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned)); 4554 } else if (Op1Type->isVectorTy()) { 4555 // TODO? If the edge cases for vectors were guaranteed to be handled as they 4556 // are for scalar, we could remove the min/max checks. However, to do that, 4557 // we would have to use insertelement/shufflevector to replace edge values. 4558 unsigned NumElts = Op1Type->getVectorNumElements(); 4559 for (unsigned i = 0; i != NumElts; ++i) { 4560 Constant *Elt = Op1C->getAggregateElement(i); 4561 if (!Elt) 4562 return nullptr; 4563 4564 if (isa<UndefValue>(Elt)) 4565 continue; 4566 4567 // Bail out if we can't determine if this constant is min/max or if we 4568 // know that this constant is min/max. 4569 auto *CI = dyn_cast<ConstantInt>(Elt); 4570 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned))) 4571 return nullptr; 4572 } 4573 } else { 4574 // ConstantExpr? 4575 return nullptr; 4576 } 4577 4578 // Increment or decrement the constant and set the new comparison predicate: 4579 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT 4580 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true); 4581 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT; 4582 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred; 4583 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne)); 4584 } 4585 4586 /// Integer compare with boolean values can always be turned into bitwise ops. 4587 static Instruction *canonicalizeICmpBool(ICmpInst &I, 4588 InstCombiner::BuilderTy &Builder) { 4589 Value *A = I.getOperand(0), *B = I.getOperand(1); 4590 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only"); 4591 4592 // A boolean compared to true/false can be simplified to Op0/true/false in 4593 // 14 out of the 20 (10 predicates * 2 constants) possible combinations. 4594 // Cases not handled by InstSimplify are always 'not' of Op0. 4595 if (match(B, m_Zero())) { 4596 switch (I.getPredicate()) { 4597 case CmpInst::ICMP_EQ: // A == 0 -> !A 4598 case CmpInst::ICMP_ULE: // A <=u 0 -> !A 4599 case CmpInst::ICMP_SGE: // A >=s 0 -> !A 4600 return BinaryOperator::CreateNot(A); 4601 default: 4602 llvm_unreachable("ICmp i1 X, C not simplified as expected."); 4603 } 4604 } else if (match(B, m_One())) { 4605 switch (I.getPredicate()) { 4606 case CmpInst::ICMP_NE: // A != 1 -> !A 4607 case CmpInst::ICMP_ULT: // A <u 1 -> !A 4608 case CmpInst::ICMP_SGT: // A >s -1 -> !A 4609 return BinaryOperator::CreateNot(A); 4610 default: 4611 llvm_unreachable("ICmp i1 X, C not simplified as expected."); 4612 } 4613 } 4614 4615 switch (I.getPredicate()) { 4616 default: 4617 llvm_unreachable("Invalid icmp instruction!"); 4618 case ICmpInst::ICMP_EQ: 4619 // icmp eq i1 A, B -> ~(A ^ B) 4620 return BinaryOperator::CreateNot(Builder.CreateXor(A, B)); 4621 4622 case ICmpInst::ICMP_NE: 4623 // icmp ne i1 A, B -> A ^ B 4624 return BinaryOperator::CreateXor(A, B); 4625 4626 case ICmpInst::ICMP_UGT: 4627 // icmp ugt -> icmp ult 4628 std::swap(A, B); 4629 LLVM_FALLTHROUGH; 4630 case ICmpInst::ICMP_ULT: 4631 // icmp ult i1 A, B -> ~A & B 4632 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B); 4633 4634 case ICmpInst::ICMP_SGT: 4635 // icmp sgt -> icmp slt 4636 std::swap(A, B); 4637 LLVM_FALLTHROUGH; 4638 case ICmpInst::ICMP_SLT: 4639 // icmp slt i1 A, B -> A & ~B 4640 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A); 4641 4642 case ICmpInst::ICMP_UGE: 4643 // icmp uge -> icmp ule 4644 std::swap(A, B); 4645 LLVM_FALLTHROUGH; 4646 case ICmpInst::ICMP_ULE: 4647 // icmp ule i1 A, B -> ~A | B 4648 return BinaryOperator::CreateOr(Builder.CreateNot(A), B); 4649 4650 case ICmpInst::ICMP_SGE: 4651 // icmp sge -> icmp sle 4652 std::swap(A, B); 4653 LLVM_FALLTHROUGH; 4654 case ICmpInst::ICMP_SLE: 4655 // icmp sle i1 A, B -> A | ~B 4656 return BinaryOperator::CreateOr(Builder.CreateNot(B), A); 4657 } 4658 } 4659 4660 // Transform pattern like: 4661 // (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X 4662 // (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X 4663 // Into: 4664 // (X l>> Y) != 0 4665 // (X l>> Y) == 0 4666 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp, 4667 InstCombiner::BuilderTy &Builder) { 4668 ICmpInst::Predicate Pred, NewPred; 4669 Value *X, *Y; 4670 if (match(&Cmp, 4671 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) { 4672 // We want X to be the icmp's second operand, so swap predicate if it isn't. 4673 if (Cmp.getOperand(0) == X) 4674 Pred = Cmp.getSwappedPredicate(); 4675 4676 switch (Pred) { 4677 case ICmpInst::ICMP_ULE: 4678 NewPred = ICmpInst::ICMP_NE; 4679 break; 4680 case ICmpInst::ICMP_UGT: 4681 NewPred = ICmpInst::ICMP_EQ; 4682 break; 4683 default: 4684 return nullptr; 4685 } 4686 } else if (match(&Cmp, m_c_ICmp(Pred, 4687 m_OneUse(m_CombineOr( 4688 m_Not(m_Shl(m_AllOnes(), m_Value(Y))), 4689 m_Add(m_Shl(m_One(), m_Value(Y)), 4690 m_AllOnes()))), 4691 m_Value(X)))) { 4692 // The variant with 'add' is not canonical, (the variant with 'not' is) 4693 // we only get it because it has extra uses, and can't be canonicalized, 4694 4695 // We want X to be the icmp's second operand, so swap predicate if it isn't. 4696 if (Cmp.getOperand(0) == X) 4697 Pred = Cmp.getSwappedPredicate(); 4698 4699 switch (Pred) { 4700 case ICmpInst::ICMP_ULT: 4701 NewPred = ICmpInst::ICMP_NE; 4702 break; 4703 case ICmpInst::ICMP_UGE: 4704 NewPred = ICmpInst::ICMP_EQ; 4705 break; 4706 default: 4707 return nullptr; 4708 } 4709 } else 4710 return nullptr; 4711 4712 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits"); 4713 Constant *Zero = Constant::getNullValue(NewX->getType()); 4714 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero); 4715 } 4716 4717 static Instruction *foldVectorCmp(CmpInst &Cmp, 4718 InstCombiner::BuilderTy &Builder) { 4719 // If both arguments of the cmp are shuffles that use the same mask and 4720 // shuffle within a single vector, move the shuffle after the cmp. 4721 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1); 4722 Value *V1, *V2; 4723 Constant *M; 4724 if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(M))) && 4725 match(RHS, m_ShuffleVector(m_Value(V2), m_Undef(), m_Specific(M))) && 4726 V1->getType() == V2->getType() && 4727 (LHS->hasOneUse() || RHS->hasOneUse())) { 4728 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M 4729 CmpInst::Predicate P = Cmp.getPredicate(); 4730 Value *NewCmp = isa<ICmpInst>(Cmp) ? Builder.CreateICmp(P, V1, V2) 4731 : Builder.CreateFCmp(P, V1, V2); 4732 return new ShuffleVectorInst(NewCmp, UndefValue::get(NewCmp->getType()), M); 4733 } 4734 return nullptr; 4735 } 4736 4737 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) { 4738 bool Changed = false; 4739 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4740 unsigned Op0Cplxity = getComplexity(Op0); 4741 unsigned Op1Cplxity = getComplexity(Op1); 4742 4743 /// Orders the operands of the compare so that they are listed from most 4744 /// complex to least complex. This puts constants before unary operators, 4745 /// before binary operators. 4746 if (Op0Cplxity < Op1Cplxity || 4747 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) { 4748 I.swapOperands(); 4749 std::swap(Op0, Op1); 4750 Changed = true; 4751 } 4752 4753 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, 4754 SQ.getWithInstruction(&I))) 4755 return replaceInstUsesWith(I, V); 4756 4757 // Comparing -val or val with non-zero is the same as just comparing val 4758 // ie, abs(val) != 0 -> val != 0 4759 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) { 4760 Value *Cond, *SelectTrue, *SelectFalse; 4761 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue), 4762 m_Value(SelectFalse)))) { 4763 if (Value *V = dyn_castNegVal(SelectTrue)) { 4764 if (V == SelectFalse) 4765 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 4766 } 4767 else if (Value *V = dyn_castNegVal(SelectFalse)) { 4768 if (V == SelectTrue) 4769 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 4770 } 4771 } 4772 } 4773 4774 if (Op0->getType()->isIntOrIntVectorTy(1)) 4775 if (Instruction *Res = canonicalizeICmpBool(I, Builder)) 4776 return Res; 4777 4778 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I)) 4779 return NewICmp; 4780 4781 if (Instruction *Res = foldICmpWithConstant(I)) 4782 return Res; 4783 4784 if (Instruction *Res = foldICmpWithDominatingICmp(I)) 4785 return Res; 4786 4787 if (Instruction *Res = foldICmpUsingKnownBits(I)) 4788 return Res; 4789 4790 // Test if the ICmpInst instruction is used exclusively by a select as 4791 // part of a minimum or maximum operation. If so, refrain from doing 4792 // any other folding. This helps out other analyses which understand 4793 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 4794 // and CodeGen. And in this case, at least one of the comparison 4795 // operands has at least one user besides the compare (the select), 4796 // which would often largely negate the benefit of folding anyway. 4797 // 4798 // Do the same for the other patterns recognized by matchSelectPattern. 4799 if (I.hasOneUse()) 4800 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) { 4801 Value *A, *B; 4802 SelectPatternResult SPR = matchSelectPattern(SI, A, B); 4803 if (SPR.Flavor != SPF_UNKNOWN) 4804 return nullptr; 4805 } 4806 4807 // Do this after checking for min/max to prevent infinite looping. 4808 if (Instruction *Res = foldICmpWithZero(I)) 4809 return Res; 4810 4811 // FIXME: We only do this after checking for min/max to prevent infinite 4812 // looping caused by a reverse canonicalization of these patterns for min/max. 4813 // FIXME: The organization of folds is a mess. These would naturally go into 4814 // canonicalizeCmpWithConstant(), but we can't move all of the above folds 4815 // down here after the min/max restriction. 4816 ICmpInst::Predicate Pred = I.getPredicate(); 4817 const APInt *C; 4818 if (match(Op1, m_APInt(C))) { 4819 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set 4820 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) { 4821 Constant *Zero = Constant::getNullValue(Op0->getType()); 4822 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero); 4823 } 4824 4825 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear 4826 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) { 4827 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType()); 4828 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes); 4829 } 4830 } 4831 4832 if (Instruction *Res = foldICmpInstWithConstant(I)) 4833 return Res; 4834 4835 if (Instruction *Res = foldICmpInstWithConstantNotInt(I)) 4836 return Res; 4837 4838 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. 4839 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0)) 4840 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I)) 4841 return NI; 4842 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) 4843 if (Instruction *NI = foldGEPICmp(GEP, Op0, 4844 ICmpInst::getSwappedPredicate(I.getPredicate()), I)) 4845 return NI; 4846 4847 // Try to optimize equality comparisons against alloca-based pointers. 4848 if (Op0->getType()->isPointerTy() && I.isEquality()) { 4849 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?"); 4850 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL))) 4851 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1)) 4852 return New; 4853 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL))) 4854 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0)) 4855 return New; 4856 } 4857 4858 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast. 4859 Value *X; 4860 if (match(Op0, m_BitCast(m_SIToFP(m_Value(X))))) { 4861 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0 4862 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0 4863 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0 4864 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0 4865 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT || 4866 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) && 4867 match(Op1, m_Zero())) 4868 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType())); 4869 4870 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1 4871 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One())) 4872 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1)); 4873 4874 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1 4875 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes())) 4876 return new ICmpInst(Pred, X, ConstantInt::getAllOnesValue(X->getType())); 4877 } 4878 4879 // Zero-equality checks are preserved through unsigned floating-point casts: 4880 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0 4881 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0 4882 if (match(Op0, m_BitCast(m_UIToFP(m_Value(X))))) 4883 if (I.isEquality() && match(Op1, m_Zero())) 4884 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType())); 4885 4886 // Test to see if the operands of the icmp are casted versions of other 4887 // values. If the ptr->ptr cast can be stripped off both arguments, we do so 4888 // now. 4889 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) { 4890 if (Op0->getType()->isPointerTy() && 4891 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 4892 // We keep moving the cast from the left operand over to the right 4893 // operand, where it can often be eliminated completely. 4894 Op0 = CI->getOperand(0); 4895 4896 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast 4897 // so eliminate it as well. 4898 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1)) 4899 Op1 = CI2->getOperand(0); 4900 4901 // If Op1 is a constant, we can fold the cast into the constant. 4902 if (Op0->getType() != Op1->getType()) { 4903 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 4904 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType()); 4905 } else { 4906 // Otherwise, cast the RHS right before the icmp 4907 Op1 = Builder.CreateBitCast(Op1, Op0->getType()); 4908 } 4909 } 4910 return new ICmpInst(I.getPredicate(), Op0, Op1); 4911 } 4912 } 4913 4914 if (isa<CastInst>(Op0)) { 4915 // Handle the special case of: icmp (cast bool to X), <cst> 4916 // This comes up when you have code like 4917 // int X = A < B; 4918 // if (X) ... 4919 // For generality, we handle any zero-extension of any operand comparison 4920 // with a constant or another cast from the same type. 4921 if (isa<Constant>(Op1) || isa<CastInst>(Op1)) 4922 if (Instruction *R = foldICmpWithCastAndCast(I)) 4923 return R; 4924 } 4925 4926 if (Instruction *Res = foldICmpBinOp(I)) 4927 return Res; 4928 4929 if (Instruction *Res = foldICmpWithMinMax(I)) 4930 return Res; 4931 4932 { 4933 Value *A, *B; 4934 // Transform (A & ~B) == 0 --> (A & B) != 0 4935 // and (A & ~B) != 0 --> (A & B) == 0 4936 // if A is a power of 2. 4937 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) && 4938 match(Op1, m_Zero()) && 4939 isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality()) 4940 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B), 4941 Op1); 4942 4943 // ~X < ~Y --> Y < X 4944 // ~X < C --> X > ~C 4945 if (match(Op0, m_Not(m_Value(A)))) { 4946 if (match(Op1, m_Not(m_Value(B)))) 4947 return new ICmpInst(I.getPredicate(), B, A); 4948 4949 const APInt *C; 4950 if (match(Op1, m_APInt(C))) 4951 return new ICmpInst(I.getSwappedPredicate(), A, 4952 ConstantInt::get(Op1->getType(), ~(*C))); 4953 } 4954 4955 Instruction *AddI = nullptr; 4956 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B), 4957 m_Instruction(AddI))) && 4958 isa<IntegerType>(A->getType())) { 4959 Value *Result; 4960 Constant *Overflow; 4961 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result, 4962 Overflow)) { 4963 replaceInstUsesWith(*AddI, Result); 4964 return replaceInstUsesWith(I, Overflow); 4965 } 4966 } 4967 4968 // (zext a) * (zext b) --> llvm.umul.with.overflow. 4969 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 4970 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this)) 4971 return R; 4972 } 4973 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 4974 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this)) 4975 return R; 4976 } 4977 } 4978 4979 if (Instruction *Res = foldICmpEquality(I)) 4980 return Res; 4981 4982 // The 'cmpxchg' instruction returns an aggregate containing the old value and 4983 // an i1 which indicates whether or not we successfully did the swap. 4984 // 4985 // Replace comparisons between the old value and the expected value with the 4986 // indicator that 'cmpxchg' returns. 4987 // 4988 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to 4989 // spuriously fail. In those cases, the old value may equal the expected 4990 // value but it is possible for the swap to not occur. 4991 if (I.getPredicate() == ICmpInst::ICMP_EQ) 4992 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0)) 4993 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand())) 4994 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 && 4995 !ACXI->isWeak()) 4996 return ExtractValueInst::Create(ACXI, 1); 4997 4998 { 4999 Value *X; 5000 const APInt *C; 5001 // icmp X+Cst, X 5002 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X) 5003 return foldICmpAddOpConst(X, *C, I.getPredicate()); 5004 5005 // icmp X, X+Cst 5006 if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X) 5007 return foldICmpAddOpConst(X, *C, I.getSwappedPredicate()); 5008 } 5009 5010 if (Instruction *Res = foldICmpWithHighBitMask(I, Builder)) 5011 return Res; 5012 5013 if (I.getType()->isVectorTy()) 5014 if (Instruction *Res = foldVectorCmp(I, Builder)) 5015 return Res; 5016 5017 return Changed ? &I : nullptr; 5018 } 5019 5020 /// Fold fcmp ([us]itofp x, cst) if possible. 5021 Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI, 5022 Constant *RHSC) { 5023 if (!isa<ConstantFP>(RHSC)) return nullptr; 5024 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); 5025 5026 // Get the width of the mantissa. We don't want to hack on conversions that 5027 // might lose information from the integer, e.g. "i64 -> float" 5028 int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); 5029 if (MantissaWidth == -1) return nullptr; // Unknown. 5030 5031 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); 5032 5033 bool LHSUnsigned = isa<UIToFPInst>(LHSI); 5034 5035 if (I.isEquality()) { 5036 FCmpInst::Predicate P = I.getPredicate(); 5037 bool IsExact = false; 5038 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned); 5039 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact); 5040 5041 // If the floating point constant isn't an integer value, we know if we will 5042 // ever compare equal / not equal to it. 5043 if (!IsExact) { 5044 // TODO: Can never be -0.0 and other non-representable values 5045 APFloat RHSRoundInt(RHS); 5046 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven); 5047 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) { 5048 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ) 5049 return replaceInstUsesWith(I, Builder.getFalse()); 5050 5051 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE); 5052 return replaceInstUsesWith(I, Builder.getTrue()); 5053 } 5054 } 5055 5056 // TODO: If the constant is exactly representable, is it always OK to do 5057 // equality compares as integer? 5058 } 5059 5060 // Check to see that the input is converted from an integer type that is small 5061 // enough that preserves all bits. TODO: check here for "known" sign bits. 5062 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. 5063 unsigned InputSize = IntTy->getScalarSizeInBits(); 5064 5065 // Following test does NOT adjust InputSize downwards for signed inputs, 5066 // because the most negative value still requires all the mantissa bits 5067 // to distinguish it from one less than that value. 5068 if ((int)InputSize > MantissaWidth) { 5069 // Conversion would lose accuracy. Check if loss can impact comparison. 5070 int Exp = ilogb(RHS); 5071 if (Exp == APFloat::IEK_Inf) { 5072 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics())); 5073 if (MaxExponent < (int)InputSize - !LHSUnsigned) 5074 // Conversion could create infinity. 5075 return nullptr; 5076 } else { 5077 // Note that if RHS is zero or NaN, then Exp is negative 5078 // and first condition is trivially false. 5079 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned) 5080 // Conversion could affect comparison. 5081 return nullptr; 5082 } 5083 } 5084 5085 // Otherwise, we can potentially simplify the comparison. We know that it 5086 // will always come through as an integer value and we know the constant is 5087 // not a NAN (it would have been previously simplified). 5088 assert(!RHS.isNaN() && "NaN comparison not already folded!"); 5089 5090 ICmpInst::Predicate Pred; 5091 switch (I.getPredicate()) { 5092 default: llvm_unreachable("Unexpected predicate!"); 5093 case FCmpInst::FCMP_UEQ: 5094 case FCmpInst::FCMP_OEQ: 5095 Pred = ICmpInst::ICMP_EQ; 5096 break; 5097 case FCmpInst::FCMP_UGT: 5098 case FCmpInst::FCMP_OGT: 5099 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; 5100 break; 5101 case FCmpInst::FCMP_UGE: 5102 case FCmpInst::FCMP_OGE: 5103 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; 5104 break; 5105 case FCmpInst::FCMP_ULT: 5106 case FCmpInst::FCMP_OLT: 5107 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; 5108 break; 5109 case FCmpInst::FCMP_ULE: 5110 case FCmpInst::FCMP_OLE: 5111 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; 5112 break; 5113 case FCmpInst::FCMP_UNE: 5114 case FCmpInst::FCMP_ONE: 5115 Pred = ICmpInst::ICMP_NE; 5116 break; 5117 case FCmpInst::FCMP_ORD: 5118 return replaceInstUsesWith(I, Builder.getTrue()); 5119 case FCmpInst::FCMP_UNO: 5120 return replaceInstUsesWith(I, Builder.getFalse()); 5121 } 5122 5123 // Now we know that the APFloat is a normal number, zero or inf. 5124 5125 // See if the FP constant is too large for the integer. For example, 5126 // comparing an i8 to 300.0. 5127 unsigned IntWidth = IntTy->getScalarSizeInBits(); 5128 5129 if (!LHSUnsigned) { 5130 // If the RHS value is > SignedMax, fold the comparison. This handles +INF 5131 // and large values. 5132 APFloat SMax(RHS.getSemantics()); 5133 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, 5134 APFloat::rmNearestTiesToEven); 5135 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0 5136 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || 5137 Pred == ICmpInst::ICMP_SLE) 5138 return replaceInstUsesWith(I, Builder.getTrue()); 5139 return replaceInstUsesWith(I, Builder.getFalse()); 5140 } 5141 } else { 5142 // If the RHS value is > UnsignedMax, fold the comparison. This handles 5143 // +INF and large values. 5144 APFloat UMax(RHS.getSemantics()); 5145 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, 5146 APFloat::rmNearestTiesToEven); 5147 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0 5148 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || 5149 Pred == ICmpInst::ICMP_ULE) 5150 return replaceInstUsesWith(I, Builder.getTrue()); 5151 return replaceInstUsesWith(I, Builder.getFalse()); 5152 } 5153 } 5154 5155 if (!LHSUnsigned) { 5156 // See if the RHS value is < SignedMin. 5157 APFloat SMin(RHS.getSemantics()); 5158 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, 5159 APFloat::rmNearestTiesToEven); 5160 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0 5161 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || 5162 Pred == ICmpInst::ICMP_SGE) 5163 return replaceInstUsesWith(I, Builder.getTrue()); 5164 return replaceInstUsesWith(I, Builder.getFalse()); 5165 } 5166 } else { 5167 // See if the RHS value is < UnsignedMin. 5168 APFloat SMin(RHS.getSemantics()); 5169 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true, 5170 APFloat::rmNearestTiesToEven); 5171 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0 5172 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT || 5173 Pred == ICmpInst::ICMP_UGE) 5174 return replaceInstUsesWith(I, Builder.getTrue()); 5175 return replaceInstUsesWith(I, Builder.getFalse()); 5176 } 5177 } 5178 5179 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or 5180 // [0, UMAX], but it may still be fractional. See if it is fractional by 5181 // casting the FP value to the integer value and back, checking for equality. 5182 // Don't do this for zero, because -0.0 is not fractional. 5183 Constant *RHSInt = LHSUnsigned 5184 ? ConstantExpr::getFPToUI(RHSC, IntTy) 5185 : ConstantExpr::getFPToSI(RHSC, IntTy); 5186 if (!RHS.isZero()) { 5187 bool Equal = LHSUnsigned 5188 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC 5189 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; 5190 if (!Equal) { 5191 // If we had a comparison against a fractional value, we have to adjust 5192 // the compare predicate and sometimes the value. RHSC is rounded towards 5193 // zero at this point. 5194 switch (Pred) { 5195 default: llvm_unreachable("Unexpected integer comparison!"); 5196 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true 5197 return replaceInstUsesWith(I, Builder.getTrue()); 5198 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false 5199 return replaceInstUsesWith(I, Builder.getFalse()); 5200 case ICmpInst::ICMP_ULE: 5201 // (float)int <= 4.4 --> int <= 4 5202 // (float)int <= -4.4 --> false 5203 if (RHS.isNegative()) 5204 return replaceInstUsesWith(I, Builder.getFalse()); 5205 break; 5206 case ICmpInst::ICMP_SLE: 5207 // (float)int <= 4.4 --> int <= 4 5208 // (float)int <= -4.4 --> int < -4 5209 if (RHS.isNegative()) 5210 Pred = ICmpInst::ICMP_SLT; 5211 break; 5212 case ICmpInst::ICMP_ULT: 5213 // (float)int < -4.4 --> false 5214 // (float)int < 4.4 --> int <= 4 5215 if (RHS.isNegative()) 5216 return replaceInstUsesWith(I, Builder.getFalse()); 5217 Pred = ICmpInst::ICMP_ULE; 5218 break; 5219 case ICmpInst::ICMP_SLT: 5220 // (float)int < -4.4 --> int < -4 5221 // (float)int < 4.4 --> int <= 4 5222 if (!RHS.isNegative()) 5223 Pred = ICmpInst::ICMP_SLE; 5224 break; 5225 case ICmpInst::ICMP_UGT: 5226 // (float)int > 4.4 --> int > 4 5227 // (float)int > -4.4 --> true 5228 if (RHS.isNegative()) 5229 return replaceInstUsesWith(I, Builder.getTrue()); 5230 break; 5231 case ICmpInst::ICMP_SGT: 5232 // (float)int > 4.4 --> int > 4 5233 // (float)int > -4.4 --> int >= -4 5234 if (RHS.isNegative()) 5235 Pred = ICmpInst::ICMP_SGE; 5236 break; 5237 case ICmpInst::ICMP_UGE: 5238 // (float)int >= -4.4 --> true 5239 // (float)int >= 4.4 --> int > 4 5240 if (RHS.isNegative()) 5241 return replaceInstUsesWith(I, Builder.getTrue()); 5242 Pred = ICmpInst::ICMP_UGT; 5243 break; 5244 case ICmpInst::ICMP_SGE: 5245 // (float)int >= -4.4 --> int >= -4 5246 // (float)int >= 4.4 --> int > 4 5247 if (!RHS.isNegative()) 5248 Pred = ICmpInst::ICMP_SGT; 5249 break; 5250 } 5251 } 5252 } 5253 5254 // Lower this FP comparison into an appropriate integer version of the 5255 // comparison. 5256 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); 5257 } 5258 5259 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary. 5260 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, 5261 Constant *RHSC) { 5262 // When C is not 0.0 and infinities are not allowed: 5263 // (C / X) < 0.0 is a sign-bit test of X 5264 // (C / X) < 0.0 --> X < 0.0 (if C is positive) 5265 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate) 5266 // 5267 // Proof: 5268 // Multiply (C / X) < 0.0 by X * X / C. 5269 // - X is non zero, if it is the flag 'ninf' is violated. 5270 // - C defines the sign of X * X * C. Thus it also defines whether to swap 5271 // the predicate. C is also non zero by definition. 5272 // 5273 // Thus X * X / C is non zero and the transformation is valid. [qed] 5274 5275 FCmpInst::Predicate Pred = I.getPredicate(); 5276 5277 // Check that predicates are valid. 5278 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) && 5279 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE)) 5280 return nullptr; 5281 5282 // Check that RHS operand is zero. 5283 if (!match(RHSC, m_AnyZeroFP())) 5284 return nullptr; 5285 5286 // Check fastmath flags ('ninf'). 5287 if (!LHSI->hasNoInfs() || !I.hasNoInfs()) 5288 return nullptr; 5289 5290 // Check the properties of the dividend. It must not be zero to avoid a 5291 // division by zero (see Proof). 5292 const APFloat *C; 5293 if (!match(LHSI->getOperand(0), m_APFloat(C))) 5294 return nullptr; 5295 5296 if (C->isZero()) 5297 return nullptr; 5298 5299 // Get swapped predicate if necessary. 5300 if (C->isNegative()) 5301 Pred = I.getSwappedPredicate(); 5302 5303 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I); 5304 } 5305 5306 /// Optimize fabs(X) compared with zero. 5307 static Instruction *foldFabsWithFcmpZero(FCmpInst &I) { 5308 Value *X; 5309 if (!match(I.getOperand(0), m_Intrinsic<Intrinsic::fabs>(m_Value(X))) || 5310 !match(I.getOperand(1), m_PosZeroFP())) 5311 return nullptr; 5312 5313 auto replacePredAndOp0 = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) { 5314 I->setPredicate(P); 5315 I->setOperand(0, X); 5316 return I; 5317 }; 5318 5319 switch (I.getPredicate()) { 5320 case FCmpInst::FCMP_UGE: 5321 case FCmpInst::FCMP_OLT: 5322 // fabs(X) >= 0.0 --> true 5323 // fabs(X) < 0.0 --> false 5324 llvm_unreachable("fcmp should have simplified"); 5325 5326 case FCmpInst::FCMP_OGT: 5327 // fabs(X) > 0.0 --> X != 0.0 5328 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X); 5329 5330 case FCmpInst::FCMP_UGT: 5331 // fabs(X) u> 0.0 --> X u!= 0.0 5332 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X); 5333 5334 case FCmpInst::FCMP_OLE: 5335 // fabs(X) <= 0.0 --> X == 0.0 5336 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X); 5337 5338 case FCmpInst::FCMP_ULE: 5339 // fabs(X) u<= 0.0 --> X u== 0.0 5340 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X); 5341 5342 case FCmpInst::FCMP_OGE: 5343 // fabs(X) >= 0.0 --> !isnan(X) 5344 assert(!I.hasNoNaNs() && "fcmp should have simplified"); 5345 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X); 5346 5347 case FCmpInst::FCMP_ULT: 5348 // fabs(X) u< 0.0 --> isnan(X) 5349 assert(!I.hasNoNaNs() && "fcmp should have simplified"); 5350 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X); 5351 5352 case FCmpInst::FCMP_OEQ: 5353 case FCmpInst::FCMP_UEQ: 5354 case FCmpInst::FCMP_ONE: 5355 case FCmpInst::FCMP_UNE: 5356 case FCmpInst::FCMP_ORD: 5357 case FCmpInst::FCMP_UNO: 5358 // Look through the fabs() because it doesn't change anything but the sign. 5359 // fabs(X) == 0.0 --> X == 0.0, 5360 // fabs(X) != 0.0 --> X != 0.0 5361 // isnan(fabs(X)) --> isnan(X) 5362 // !isnan(fabs(X) --> !isnan(X) 5363 return replacePredAndOp0(&I, I.getPredicate(), X); 5364 5365 default: 5366 return nullptr; 5367 } 5368 } 5369 5370 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) { 5371 bool Changed = false; 5372 5373 /// Orders the operands of the compare so that they are listed from most 5374 /// complex to least complex. This puts constants before unary operators, 5375 /// before binary operators. 5376 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 5377 I.swapOperands(); 5378 Changed = true; 5379 } 5380 5381 const CmpInst::Predicate Pred = I.getPredicate(); 5382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 5383 if (Value *V = SimplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(), 5384 SQ.getWithInstruction(&I))) 5385 return replaceInstUsesWith(I, V); 5386 5387 // Simplify 'fcmp pred X, X' 5388 if (Op0 == Op1) { 5389 switch (Pred) { 5390 default: break; 5391 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) 5392 case FCmpInst::FCMP_ULT: // True if unordered or less than 5393 case FCmpInst::FCMP_UGT: // True if unordered or greater than 5394 case FCmpInst::FCMP_UNE: // True if unordered or not equal 5395 // Canonicalize these to be 'fcmp uno %X, 0.0'. 5396 I.setPredicate(FCmpInst::FCMP_UNO); 5397 I.setOperand(1, Constant::getNullValue(Op0->getType())); 5398 return &I; 5399 5400 case FCmpInst::FCMP_ORD: // True if ordered (no nans) 5401 case FCmpInst::FCMP_OEQ: // True if ordered and equal 5402 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal 5403 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal 5404 // Canonicalize these to be 'fcmp ord %X, 0.0'. 5405 I.setPredicate(FCmpInst::FCMP_ORD); 5406 I.setOperand(1, Constant::getNullValue(Op0->getType())); 5407 return &I; 5408 } 5409 } 5410 5411 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand, 5412 // then canonicalize the operand to 0.0. 5413 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) { 5414 if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, &TLI)) { 5415 I.setOperand(0, ConstantFP::getNullValue(Op0->getType())); 5416 return &I; 5417 } 5418 if (!match(Op1, m_PosZeroFP()) && isKnownNeverNaN(Op1, &TLI)) { 5419 I.setOperand(1, ConstantFP::getNullValue(Op0->getType())); 5420 return &I; 5421 } 5422 } 5423 5424 // Test if the FCmpInst instruction is used exclusively by a select as 5425 // part of a minimum or maximum operation. If so, refrain from doing 5426 // any other folding. This helps out other analyses which understand 5427 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 5428 // and CodeGen. And in this case, at least one of the comparison 5429 // operands has at least one user besides the compare (the select), 5430 // which would often largely negate the benefit of folding anyway. 5431 if (I.hasOneUse()) 5432 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) { 5433 Value *A, *B; 5434 SelectPatternResult SPR = matchSelectPattern(SI, A, B); 5435 if (SPR.Flavor != SPF_UNKNOWN) 5436 return nullptr; 5437 } 5438 5439 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0: 5440 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0 5441 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP())) { 5442 I.setOperand(1, ConstantFP::getNullValue(Op1->getType())); 5443 return &I; 5444 } 5445 5446 // Handle fcmp with instruction LHS and constant RHS. 5447 Instruction *LHSI; 5448 Constant *RHSC; 5449 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) { 5450 switch (LHSI->getOpcode()) { 5451 case Instruction::PHI: 5452 // Only fold fcmp into the PHI if the phi and fcmp are in the same 5453 // block. If in the same block, we're encouraging jump threading. If 5454 // not, we are just pessimizing the code by making an i1 phi. 5455 if (LHSI->getParent() == I.getParent()) 5456 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI))) 5457 return NV; 5458 break; 5459 case Instruction::SIToFP: 5460 case Instruction::UIToFP: 5461 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC)) 5462 return NV; 5463 break; 5464 case Instruction::FDiv: 5465 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC)) 5466 return NV; 5467 break; 5468 case Instruction::Load: 5469 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) 5470 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 5471 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 5472 !cast<LoadInst>(LHSI)->isVolatile()) 5473 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) 5474 return Res; 5475 break; 5476 } 5477 } 5478 5479 if (Instruction *R = foldFabsWithFcmpZero(I)) 5480 return R; 5481 5482 Value *X, *Y; 5483 if (match(Op0, m_FNeg(m_Value(X)))) { 5484 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y 5485 if (match(Op1, m_FNeg(m_Value(Y)))) 5486 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I); 5487 5488 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C 5489 Constant *C; 5490 if (match(Op1, m_Constant(C))) { 5491 Constant *NegC = ConstantExpr::getFNeg(C); 5492 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I); 5493 } 5494 } 5495 5496 if (match(Op0, m_FPExt(m_Value(X)))) { 5497 // fcmp (fpext X), (fpext Y) -> fcmp X, Y 5498 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType()) 5499 return new FCmpInst(Pred, X, Y, "", &I); 5500 5501 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless 5502 const APFloat *C; 5503 if (match(Op1, m_APFloat(C))) { 5504 const fltSemantics &FPSem = 5505 X->getType()->getScalarType()->getFltSemantics(); 5506 bool Lossy; 5507 APFloat TruncC = *C; 5508 TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy); 5509 5510 // Avoid lossy conversions and denormals. 5511 // Zero is a special case that's OK to convert. 5512 APFloat Fabs = TruncC; 5513 Fabs.clearSign(); 5514 if (!Lossy && 5515 ((Fabs.compare(APFloat::getSmallestNormalized(FPSem)) != 5516 APFloat::cmpLessThan) || Fabs.isZero())) { 5517 Constant *NewC = ConstantFP::get(X->getType(), TruncC); 5518 return new FCmpInst(Pred, X, NewC, "", &I); 5519 } 5520 } 5521 } 5522 5523 if (I.getType()->isVectorTy()) 5524 if (Instruction *Res = foldVectorCmp(I, Builder)) 5525 return Res; 5526 5527 return Changed ? &I : nullptr; 5528 } 5529