1 //===- InstCombineCompares.cpp --------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visitICmp and visitFCmp functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/APSInt.h" 15 #include "llvm/ADT/SetVector.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/CmpInstAnalysis.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/IR/ConstantRange.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/GetElementPtrTypeIterator.h" 23 #include "llvm/IR/IntrinsicInst.h" 24 #include "llvm/IR/PatternMatch.h" 25 #include "llvm/Support/KnownBits.h" 26 #include "llvm/Transforms/InstCombine/InstCombiner.h" 27 28 using namespace llvm; 29 using namespace PatternMatch; 30 31 #define DEBUG_TYPE "instcombine" 32 33 // How many times is a select replaced by one of its operands? 34 STATISTIC(NumSel, "Number of select opts"); 35 36 37 /// Compute Result = In1+In2, returning true if the result overflowed for this 38 /// type. 39 static bool addWithOverflow(APInt &Result, const APInt &In1, 40 const APInt &In2, bool IsSigned = false) { 41 bool Overflow; 42 if (IsSigned) 43 Result = In1.sadd_ov(In2, Overflow); 44 else 45 Result = In1.uadd_ov(In2, Overflow); 46 47 return Overflow; 48 } 49 50 /// Compute Result = In1-In2, returning true if the result overflowed for this 51 /// type. 52 static bool subWithOverflow(APInt &Result, const APInt &In1, 53 const APInt &In2, bool IsSigned = false) { 54 bool Overflow; 55 if (IsSigned) 56 Result = In1.ssub_ov(In2, Overflow); 57 else 58 Result = In1.usub_ov(In2, Overflow); 59 60 return Overflow; 61 } 62 63 /// Given an icmp instruction, return true if any use of this comparison is a 64 /// branch on sign bit comparison. 65 static bool hasBranchUse(ICmpInst &I) { 66 for (auto *U : I.users()) 67 if (isa<BranchInst>(U)) 68 return true; 69 return false; 70 } 71 72 /// Returns true if the exploded icmp can be expressed as a signed comparison 73 /// to zero and updates the predicate accordingly. 74 /// The signedness of the comparison is preserved. 75 /// TODO: Refactor with decomposeBitTestICmp()? 76 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) { 77 if (!ICmpInst::isSigned(Pred)) 78 return false; 79 80 if (C.isZero()) 81 return ICmpInst::isRelational(Pred); 82 83 if (C.isOne()) { 84 if (Pred == ICmpInst::ICMP_SLT) { 85 Pred = ICmpInst::ICMP_SLE; 86 return true; 87 } 88 } else if (C.isAllOnes()) { 89 if (Pred == ICmpInst::ICMP_SGT) { 90 Pred = ICmpInst::ICMP_SGE; 91 return true; 92 } 93 } 94 95 return false; 96 } 97 98 /// This is called when we see this pattern: 99 /// cmp pred (load (gep GV, ...)), cmpcst 100 /// where GV is a global variable with a constant initializer. Try to simplify 101 /// this into some simple computation that does not need the load. For example 102 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". 103 /// 104 /// If AndCst is non-null, then the loaded value is masked with that constant 105 /// before doing the comparison. This handles cases like "A[i]&4 == 0". 106 Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal( 107 LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI, 108 ConstantInt *AndCst) { 109 if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() || 110 GV->getValueType() != GEP->getSourceElementType() || 111 !GV->isConstant() || !GV->hasDefinitiveInitializer()) 112 return nullptr; 113 114 Constant *Init = GV->getInitializer(); 115 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init)) 116 return nullptr; 117 118 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements(); 119 // Don't blow up on huge arrays. 120 if (ArrayElementCount > MaxArraySizeForCombine) 121 return nullptr; 122 123 // There are many forms of this optimization we can handle, for now, just do 124 // the simple index into a single-dimensional array. 125 // 126 // Require: GEP GV, 0, i {{, constant indices}} 127 if (GEP->getNumOperands() < 3 || 128 !isa<ConstantInt>(GEP->getOperand(1)) || 129 !cast<ConstantInt>(GEP->getOperand(1))->isZero() || 130 isa<Constant>(GEP->getOperand(2))) 131 return nullptr; 132 133 // Check that indices after the variable are constants and in-range for the 134 // type they index. Collect the indices. This is typically for arrays of 135 // structs. 136 SmallVector<unsigned, 4> LaterIndices; 137 138 Type *EltTy = Init->getType()->getArrayElementType(); 139 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { 140 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 141 if (!Idx) return nullptr; // Variable index. 142 143 uint64_t IdxVal = Idx->getZExtValue(); 144 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index. 145 146 if (StructType *STy = dyn_cast<StructType>(EltTy)) 147 EltTy = STy->getElementType(IdxVal); 148 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { 149 if (IdxVal >= ATy->getNumElements()) return nullptr; 150 EltTy = ATy->getElementType(); 151 } else { 152 return nullptr; // Unknown type. 153 } 154 155 LaterIndices.push_back(IdxVal); 156 } 157 158 enum { Overdefined = -3, Undefined = -2 }; 159 160 // Variables for our state machines. 161 162 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form 163 // "i == 47 | i == 87", where 47 is the first index the condition is true for, 164 // and 87 is the second (and last) index. FirstTrueElement is -2 when 165 // undefined, otherwise set to the first true element. SecondTrueElement is 166 // -2 when undefined, -3 when overdefined and >= 0 when that index is true. 167 int FirstTrueElement = Undefined, SecondTrueElement = Undefined; 168 169 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the 170 // form "i != 47 & i != 87". Same state transitions as for true elements. 171 int FirstFalseElement = Undefined, SecondFalseElement = Undefined; 172 173 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these 174 /// define a state machine that triggers for ranges of values that the index 175 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. 176 /// This is -2 when undefined, -3 when overdefined, and otherwise the last 177 /// index in the range (inclusive). We use -2 for undefined here because we 178 /// use relative comparisons and don't want 0-1 to match -1. 179 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; 180 181 // MagicBitvector - This is a magic bitvector where we set a bit if the 182 // comparison is true for element 'i'. If there are 64 elements or less in 183 // the array, this will fully represent all the comparison results. 184 uint64_t MagicBitvector = 0; 185 186 // Scan the array and see if one of our patterns matches. 187 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); 188 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) { 189 Constant *Elt = Init->getAggregateElement(i); 190 if (!Elt) return nullptr; 191 192 // If this is indexing an array of structures, get the structure element. 193 if (!LaterIndices.empty()) { 194 Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices); 195 if (!Elt) 196 return nullptr; 197 } 198 199 // If the element is masked, handle it. 200 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); 201 202 // Find out if the comparison would be true or false for the i'th element. 203 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, 204 CompareRHS, DL, &TLI); 205 // If the result is undef for this element, ignore it. 206 if (isa<UndefValue>(C)) { 207 // Extend range state machines to cover this element in case there is an 208 // undef in the middle of the range. 209 if (TrueRangeEnd == (int)i-1) 210 TrueRangeEnd = i; 211 if (FalseRangeEnd == (int)i-1) 212 FalseRangeEnd = i; 213 continue; 214 } 215 216 // If we can't compute the result for any of the elements, we have to give 217 // up evaluating the entire conditional. 218 if (!isa<ConstantInt>(C)) return nullptr; 219 220 // Otherwise, we know if the comparison is true or false for this element, 221 // update our state machines. 222 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); 223 224 // State machine for single/double/range index comparison. 225 if (IsTrueForElt) { 226 // Update the TrueElement state machine. 227 if (FirstTrueElement == Undefined) 228 FirstTrueElement = TrueRangeEnd = i; // First true element. 229 else { 230 // Update double-compare state machine. 231 if (SecondTrueElement == Undefined) 232 SecondTrueElement = i; 233 else 234 SecondTrueElement = Overdefined; 235 236 // Update range state machine. 237 if (TrueRangeEnd == (int)i-1) 238 TrueRangeEnd = i; 239 else 240 TrueRangeEnd = Overdefined; 241 } 242 } else { 243 // Update the FalseElement state machine. 244 if (FirstFalseElement == Undefined) 245 FirstFalseElement = FalseRangeEnd = i; // First false element. 246 else { 247 // Update double-compare state machine. 248 if (SecondFalseElement == Undefined) 249 SecondFalseElement = i; 250 else 251 SecondFalseElement = Overdefined; 252 253 // Update range state machine. 254 if (FalseRangeEnd == (int)i-1) 255 FalseRangeEnd = i; 256 else 257 FalseRangeEnd = Overdefined; 258 } 259 } 260 261 // If this element is in range, update our magic bitvector. 262 if (i < 64 && IsTrueForElt) 263 MagicBitvector |= 1ULL << i; 264 265 // If all of our states become overdefined, bail out early. Since the 266 // predicate is expensive, only check it every 8 elements. This is only 267 // really useful for really huge arrays. 268 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && 269 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && 270 FalseRangeEnd == Overdefined) 271 return nullptr; 272 } 273 274 // Now that we've scanned the entire array, emit our new comparison(s). We 275 // order the state machines in complexity of the generated code. 276 Value *Idx = GEP->getOperand(2); 277 278 // If the index is larger than the pointer size of the target, truncate the 279 // index down like the GEP would do implicitly. We don't have to do this for 280 // an inbounds GEP because the index can't be out of range. 281 if (!GEP->isInBounds()) { 282 Type *IntPtrTy = DL.getIntPtrType(GEP->getType()); 283 unsigned PtrSize = IntPtrTy->getIntegerBitWidth(); 284 if (Idx->getType()->getPrimitiveSizeInBits().getFixedSize() > PtrSize) 285 Idx = Builder.CreateTrunc(Idx, IntPtrTy); 286 } 287 288 // If inbounds keyword is not present, Idx * ElementSize can overflow. 289 // Let's assume that ElementSize is 2 and the wanted value is at offset 0. 290 // Then, there are two possible values for Idx to match offset 0: 291 // 0x00..00, 0x80..00. 292 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the 293 // comparison is false if Idx was 0x80..00. 294 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx. 295 unsigned ElementSize = 296 DL.getTypeAllocSize(Init->getType()->getArrayElementType()); 297 auto MaskIdx = [&](Value* Idx){ 298 if (!GEP->isInBounds() && countTrailingZeros(ElementSize) != 0) { 299 Value *Mask = ConstantInt::get(Idx->getType(), -1); 300 Mask = Builder.CreateLShr(Mask, countTrailingZeros(ElementSize)); 301 Idx = Builder.CreateAnd(Idx, Mask); 302 } 303 return Idx; 304 }; 305 306 // If the comparison is only true for one or two elements, emit direct 307 // comparisons. 308 if (SecondTrueElement != Overdefined) { 309 Idx = MaskIdx(Idx); 310 // None true -> false. 311 if (FirstTrueElement == Undefined) 312 return replaceInstUsesWith(ICI, Builder.getFalse()); 313 314 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); 315 316 // True for one element -> 'i == 47'. 317 if (SecondTrueElement == Undefined) 318 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); 319 320 // True for two elements -> 'i == 47 | i == 72'. 321 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx); 322 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); 323 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx); 324 return BinaryOperator::CreateOr(C1, C2); 325 } 326 327 // If the comparison is only false for one or two elements, emit direct 328 // comparisons. 329 if (SecondFalseElement != Overdefined) { 330 Idx = MaskIdx(Idx); 331 // None false -> true. 332 if (FirstFalseElement == Undefined) 333 return replaceInstUsesWith(ICI, Builder.getTrue()); 334 335 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); 336 337 // False for one element -> 'i != 47'. 338 if (SecondFalseElement == Undefined) 339 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); 340 341 // False for two elements -> 'i != 47 & i != 72'. 342 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx); 343 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); 344 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx); 345 return BinaryOperator::CreateAnd(C1, C2); 346 } 347 348 // If the comparison can be replaced with a range comparison for the elements 349 // where it is true, emit the range check. 350 if (TrueRangeEnd != Overdefined) { 351 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); 352 Idx = MaskIdx(Idx); 353 354 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). 355 if (FirstTrueElement) { 356 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); 357 Idx = Builder.CreateAdd(Idx, Offs); 358 } 359 360 Value *End = ConstantInt::get(Idx->getType(), 361 TrueRangeEnd-FirstTrueElement+1); 362 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); 363 } 364 365 // False range check. 366 if (FalseRangeEnd != Overdefined) { 367 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); 368 Idx = MaskIdx(Idx); 369 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). 370 if (FirstFalseElement) { 371 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); 372 Idx = Builder.CreateAdd(Idx, Offs); 373 } 374 375 Value *End = ConstantInt::get(Idx->getType(), 376 FalseRangeEnd-FirstFalseElement); 377 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); 378 } 379 380 // If a magic bitvector captures the entire comparison state 381 // of this load, replace it with computation that does: 382 // ((magic_cst >> i) & 1) != 0 383 { 384 Type *Ty = nullptr; 385 386 // Look for an appropriate type: 387 // - The type of Idx if the magic fits 388 // - The smallest fitting legal type 389 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth()) 390 Ty = Idx->getType(); 391 else 392 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount); 393 394 if (Ty) { 395 Idx = MaskIdx(Idx); 396 Value *V = Builder.CreateIntCast(Idx, Ty, false); 397 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); 398 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V); 399 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); 400 } 401 } 402 403 return nullptr; 404 } 405 406 /// Return a value that can be used to compare the *offset* implied by a GEP to 407 /// zero. For example, if we have &A[i], we want to return 'i' for 408 /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales 409 /// are involved. The above expression would also be legal to codegen as 410 /// "icmp ne (i*4), 0" (assuming A is a pointer to i32). 411 /// This latter form is less amenable to optimization though, and we are allowed 412 /// to generate the first by knowing that pointer arithmetic doesn't overflow. 413 /// 414 /// If we can't emit an optimized form for this expression, this returns null. 415 /// 416 static Value *evaluateGEPOffsetExpression(User *GEP, InstCombinerImpl &IC, 417 const DataLayout &DL) { 418 gep_type_iterator GTI = gep_type_begin(GEP); 419 420 // Check to see if this gep only has a single variable index. If so, and if 421 // any constant indices are a multiple of its scale, then we can compute this 422 // in terms of the scale of the variable index. For example, if the GEP 423 // implies an offset of "12 + i*4", then we can codegen this as "3 + i", 424 // because the expression will cross zero at the same point. 425 unsigned i, e = GEP->getNumOperands(); 426 int64_t Offset = 0; 427 for (i = 1; i != e; ++i, ++GTI) { 428 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 429 // Compute the aggregate offset of constant indices. 430 if (CI->isZero()) continue; 431 432 // Handle a struct index, which adds its field offset to the pointer. 433 if (StructType *STy = GTI.getStructTypeOrNull()) { 434 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 435 } else { 436 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); 437 Offset += Size*CI->getSExtValue(); 438 } 439 } else { 440 // Found our variable index. 441 break; 442 } 443 } 444 445 // If there are no variable indices, we must have a constant offset, just 446 // evaluate it the general way. 447 if (i == e) return nullptr; 448 449 Value *VariableIdx = GEP->getOperand(i); 450 // Determine the scale factor of the variable element. For example, this is 451 // 4 if the variable index is into an array of i32. 452 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType()); 453 454 // Verify that there are no other variable indices. If so, emit the hard way. 455 for (++i, ++GTI; i != e; ++i, ++GTI) { 456 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); 457 if (!CI) return nullptr; 458 459 // Compute the aggregate offset of constant indices. 460 if (CI->isZero()) continue; 461 462 // Handle a struct index, which adds its field offset to the pointer. 463 if (StructType *STy = GTI.getStructTypeOrNull()) { 464 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 465 } else { 466 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); 467 Offset += Size*CI->getSExtValue(); 468 } 469 } 470 471 // Okay, we know we have a single variable index, which must be a 472 // pointer/array/vector index. If there is no offset, life is simple, return 473 // the index. 474 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType()); 475 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth(); 476 if (Offset == 0) { 477 // Cast to intptrty in case a truncation occurs. If an extension is needed, 478 // we don't need to bother extending: the extension won't affect where the 479 // computation crosses zero. 480 if (VariableIdx->getType()->getPrimitiveSizeInBits().getFixedSize() > 481 IntPtrWidth) { 482 VariableIdx = IC.Builder.CreateTrunc(VariableIdx, IntPtrTy); 483 } 484 return VariableIdx; 485 } 486 487 // Otherwise, there is an index. The computation we will do will be modulo 488 // the pointer size. 489 Offset = SignExtend64(Offset, IntPtrWidth); 490 VariableScale = SignExtend64(VariableScale, IntPtrWidth); 491 492 // To do this transformation, any constant index must be a multiple of the 493 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", 494 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a 495 // multiple of the variable scale. 496 int64_t NewOffs = Offset / (int64_t)VariableScale; 497 if (Offset != NewOffs*(int64_t)VariableScale) 498 return nullptr; 499 500 // Okay, we can do this evaluation. Start by converting the index to intptr. 501 if (VariableIdx->getType() != IntPtrTy) 502 VariableIdx = IC.Builder.CreateIntCast(VariableIdx, IntPtrTy, 503 true /*Signed*/); 504 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); 505 return IC.Builder.CreateAdd(VariableIdx, OffsetVal, "offset"); 506 } 507 508 /// Returns true if we can rewrite Start as a GEP with pointer Base 509 /// and some integer offset. The nodes that need to be re-written 510 /// for this transformation will be added to Explored. 511 static bool canRewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base, 512 const DataLayout &DL, 513 SetVector<Value *> &Explored) { 514 SmallVector<Value *, 16> WorkList(1, Start); 515 Explored.insert(Base); 516 517 // The following traversal gives us an order which can be used 518 // when doing the final transformation. Since in the final 519 // transformation we create the PHI replacement instructions first, 520 // we don't have to get them in any particular order. 521 // 522 // However, for other instructions we will have to traverse the 523 // operands of an instruction first, which means that we have to 524 // do a post-order traversal. 525 while (!WorkList.empty()) { 526 SetVector<PHINode *> PHIs; 527 528 while (!WorkList.empty()) { 529 if (Explored.size() >= 100) 530 return false; 531 532 Value *V = WorkList.back(); 533 534 if (Explored.contains(V)) { 535 WorkList.pop_back(); 536 continue; 537 } 538 539 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) && 540 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V)) 541 // We've found some value that we can't explore which is different from 542 // the base. Therefore we can't do this transformation. 543 return false; 544 545 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) { 546 auto *CI = cast<CastInst>(V); 547 if (!CI->isNoopCast(DL)) 548 return false; 549 550 if (!Explored.contains(CI->getOperand(0))) 551 WorkList.push_back(CI->getOperand(0)); 552 } 553 554 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 555 // We're limiting the GEP to having one index. This will preserve 556 // the original pointer type. We could handle more cases in the 557 // future. 558 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() || 559 GEP->getSourceElementType() != ElemTy) 560 return false; 561 562 if (!Explored.contains(GEP->getOperand(0))) 563 WorkList.push_back(GEP->getOperand(0)); 564 } 565 566 if (WorkList.back() == V) { 567 WorkList.pop_back(); 568 // We've finished visiting this node, mark it as such. 569 Explored.insert(V); 570 } 571 572 if (auto *PN = dyn_cast<PHINode>(V)) { 573 // We cannot transform PHIs on unsplittable basic blocks. 574 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator())) 575 return false; 576 Explored.insert(PN); 577 PHIs.insert(PN); 578 } 579 } 580 581 // Explore the PHI nodes further. 582 for (auto *PN : PHIs) 583 for (Value *Op : PN->incoming_values()) 584 if (!Explored.contains(Op)) 585 WorkList.push_back(Op); 586 } 587 588 // Make sure that we can do this. Since we can't insert GEPs in a basic 589 // block before a PHI node, we can't easily do this transformation if 590 // we have PHI node users of transformed instructions. 591 for (Value *Val : Explored) { 592 for (Value *Use : Val->uses()) { 593 594 auto *PHI = dyn_cast<PHINode>(Use); 595 auto *Inst = dyn_cast<Instruction>(Val); 596 597 if (Inst == Base || Inst == PHI || !Inst || !PHI || 598 !Explored.contains(PHI)) 599 continue; 600 601 if (PHI->getParent() == Inst->getParent()) 602 return false; 603 } 604 } 605 return true; 606 } 607 608 // Sets the appropriate insert point on Builder where we can add 609 // a replacement Instruction for V (if that is possible). 610 static void setInsertionPoint(IRBuilder<> &Builder, Value *V, 611 bool Before = true) { 612 if (auto *PHI = dyn_cast<PHINode>(V)) { 613 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt()); 614 return; 615 } 616 if (auto *I = dyn_cast<Instruction>(V)) { 617 if (!Before) 618 I = &*std::next(I->getIterator()); 619 Builder.SetInsertPoint(I); 620 return; 621 } 622 if (auto *A = dyn_cast<Argument>(V)) { 623 // Set the insertion point in the entry block. 624 BasicBlock &Entry = A->getParent()->getEntryBlock(); 625 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt()); 626 return; 627 } 628 // Otherwise, this is a constant and we don't need to set a new 629 // insertion point. 630 assert(isa<Constant>(V) && "Setting insertion point for unknown value!"); 631 } 632 633 /// Returns a re-written value of Start as an indexed GEP using Base as a 634 /// pointer. 635 static Value *rewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base, 636 const DataLayout &DL, 637 SetVector<Value *> &Explored) { 638 // Perform all the substitutions. This is a bit tricky because we can 639 // have cycles in our use-def chains. 640 // 1. Create the PHI nodes without any incoming values. 641 // 2. Create all the other values. 642 // 3. Add the edges for the PHI nodes. 643 // 4. Emit GEPs to get the original pointers. 644 // 5. Remove the original instructions. 645 Type *IndexType = IntegerType::get( 646 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType())); 647 648 DenseMap<Value *, Value *> NewInsts; 649 NewInsts[Base] = ConstantInt::getNullValue(IndexType); 650 651 // Create the new PHI nodes, without adding any incoming values. 652 for (Value *Val : Explored) { 653 if (Val == Base) 654 continue; 655 // Create empty phi nodes. This avoids cyclic dependencies when creating 656 // the remaining instructions. 657 if (auto *PHI = dyn_cast<PHINode>(Val)) 658 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(), 659 PHI->getName() + ".idx", PHI); 660 } 661 IRBuilder<> Builder(Base->getContext()); 662 663 // Create all the other instructions. 664 for (Value *Val : Explored) { 665 666 if (NewInsts.find(Val) != NewInsts.end()) 667 continue; 668 669 if (auto *CI = dyn_cast<CastInst>(Val)) { 670 // Don't get rid of the intermediate variable here; the store can grow 671 // the map which will invalidate the reference to the input value. 672 Value *V = NewInsts[CI->getOperand(0)]; 673 NewInsts[CI] = V; 674 continue; 675 } 676 if (auto *GEP = dyn_cast<GEPOperator>(Val)) { 677 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)] 678 : GEP->getOperand(1); 679 setInsertionPoint(Builder, GEP); 680 // Indices might need to be sign extended. GEPs will magically do 681 // this, but we need to do it ourselves here. 682 if (Index->getType()->getScalarSizeInBits() != 683 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) { 684 Index = Builder.CreateSExtOrTrunc( 685 Index, NewInsts[GEP->getOperand(0)]->getType(), 686 GEP->getOperand(0)->getName() + ".sext"); 687 } 688 689 auto *Op = NewInsts[GEP->getOperand(0)]; 690 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero()) 691 NewInsts[GEP] = Index; 692 else 693 NewInsts[GEP] = Builder.CreateNSWAdd( 694 Op, Index, GEP->getOperand(0)->getName() + ".add"); 695 continue; 696 } 697 if (isa<PHINode>(Val)) 698 continue; 699 700 llvm_unreachable("Unexpected instruction type"); 701 } 702 703 // Add the incoming values to the PHI nodes. 704 for (Value *Val : Explored) { 705 if (Val == Base) 706 continue; 707 // All the instructions have been created, we can now add edges to the 708 // phi nodes. 709 if (auto *PHI = dyn_cast<PHINode>(Val)) { 710 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]); 711 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) { 712 Value *NewIncoming = PHI->getIncomingValue(I); 713 714 if (NewInsts.find(NewIncoming) != NewInsts.end()) 715 NewIncoming = NewInsts[NewIncoming]; 716 717 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I)); 718 } 719 } 720 } 721 722 PointerType *PtrTy = 723 ElemTy->getPointerTo(Start->getType()->getPointerAddressSpace()); 724 for (Value *Val : Explored) { 725 if (Val == Base) 726 continue; 727 728 // Depending on the type, for external users we have to emit 729 // a GEP or a GEP + ptrtoint. 730 setInsertionPoint(Builder, Val, false); 731 732 // Cast base to the expected type. 733 Value *NewVal = Builder.CreateBitOrPointerCast( 734 Base, PtrTy, Start->getName() + "to.ptr"); 735 NewVal = Builder.CreateInBoundsGEP( 736 ElemTy, NewVal, makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr"); 737 NewVal = Builder.CreateBitOrPointerCast( 738 NewVal, Val->getType(), Val->getName() + ".conv"); 739 Val->replaceAllUsesWith(NewVal); 740 } 741 742 return NewInsts[Start]; 743 } 744 745 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express 746 /// the input Value as a constant indexed GEP. Returns a pair containing 747 /// the GEPs Pointer and Index. 748 static std::pair<Value *, Value *> 749 getAsConstantIndexedAddress(Type *ElemTy, Value *V, const DataLayout &DL) { 750 Type *IndexType = IntegerType::get(V->getContext(), 751 DL.getIndexTypeSizeInBits(V->getType())); 752 753 Constant *Index = ConstantInt::getNullValue(IndexType); 754 while (true) { 755 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 756 // We accept only inbouds GEPs here to exclude the possibility of 757 // overflow. 758 if (!GEP->isInBounds()) 759 break; 760 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 && 761 GEP->getSourceElementType() == ElemTy) { 762 V = GEP->getOperand(0); 763 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1)); 764 Index = ConstantExpr::getAdd( 765 Index, ConstantExpr::getSExtOrTrunc(GEPIndex, IndexType)); 766 continue; 767 } 768 break; 769 } 770 if (auto *CI = dyn_cast<IntToPtrInst>(V)) { 771 if (!CI->isNoopCast(DL)) 772 break; 773 V = CI->getOperand(0); 774 continue; 775 } 776 if (auto *CI = dyn_cast<PtrToIntInst>(V)) { 777 if (!CI->isNoopCast(DL)) 778 break; 779 V = CI->getOperand(0); 780 continue; 781 } 782 break; 783 } 784 return {V, Index}; 785 } 786 787 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant. 788 /// We can look through PHIs, GEPs and casts in order to determine a common base 789 /// between GEPLHS and RHS. 790 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, 791 ICmpInst::Predicate Cond, 792 const DataLayout &DL) { 793 // FIXME: Support vector of pointers. 794 if (GEPLHS->getType()->isVectorTy()) 795 return nullptr; 796 797 if (!GEPLHS->hasAllConstantIndices()) 798 return nullptr; 799 800 Type *ElemTy = GEPLHS->getSourceElementType(); 801 Value *PtrBase, *Index; 802 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(ElemTy, GEPLHS, DL); 803 804 // The set of nodes that will take part in this transformation. 805 SetVector<Value *> Nodes; 806 807 if (!canRewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes)) 808 return nullptr; 809 810 // We know we can re-write this as 811 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) 812 // Since we've only looked through inbouds GEPs we know that we 813 // can't have overflow on either side. We can therefore re-write 814 // this as: 815 // OFFSET1 cmp OFFSET2 816 Value *NewRHS = rewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes); 817 818 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written 819 // GEP having PtrBase as the pointer base, and has returned in NewRHS the 820 // offset. Since Index is the offset of LHS to the base pointer, we will now 821 // compare the offsets instead of comparing the pointers. 822 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS); 823 } 824 825 /// Fold comparisons between a GEP instruction and something else. At this point 826 /// we know that the GEP is on the LHS of the comparison. 827 Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, 828 ICmpInst::Predicate Cond, 829 Instruction &I) { 830 // Don't transform signed compares of GEPs into index compares. Even if the 831 // GEP is inbounds, the final add of the base pointer can have signed overflow 832 // and would change the result of the icmp. 833 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be 834 // the maximum signed value for the pointer type. 835 if (ICmpInst::isSigned(Cond)) 836 return nullptr; 837 838 // Look through bitcasts and addrspacecasts. We do not however want to remove 839 // 0 GEPs. 840 if (!isa<GetElementPtrInst>(RHS)) 841 RHS = RHS->stripPointerCasts(); 842 843 Value *PtrBase = GEPLHS->getOperand(0); 844 // FIXME: Support vector pointer GEPs. 845 if (PtrBase == RHS && GEPLHS->isInBounds() && 846 !GEPLHS->getType()->isVectorTy()) { 847 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). 848 // This transformation (ignoring the base and scales) is valid because we 849 // know pointers can't overflow since the gep is inbounds. See if we can 850 // output an optimized form. 851 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL); 852 853 // If not, synthesize the offset the hard way. 854 if (!Offset) 855 Offset = EmitGEPOffset(GEPLHS); 856 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, 857 Constant::getNullValue(Offset->getType())); 858 } 859 860 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) && 861 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() && 862 !NullPointerIsDefined(I.getFunction(), 863 RHS->getType()->getPointerAddressSpace())) { 864 // For most address spaces, an allocation can't be placed at null, but null 865 // itself is treated as a 0 size allocation in the in bounds rules. Thus, 866 // the only valid inbounds address derived from null, is null itself. 867 // Thus, we have four cases to consider: 868 // 1) Base == nullptr, Offset == 0 -> inbounds, null 869 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds 870 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations) 871 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison) 872 // 873 // (Note if we're indexing a type of size 0, that simply collapses into one 874 // of the buckets above.) 875 // 876 // In general, we're allowed to make values less poison (i.e. remove 877 // sources of full UB), so in this case, we just select between the two 878 // non-poison cases (1 and 4 above). 879 // 880 // For vectors, we apply the same reasoning on a per-lane basis. 881 auto *Base = GEPLHS->getPointerOperand(); 882 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) { 883 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount(); 884 Base = Builder.CreateVectorSplat(EC, Base); 885 } 886 return new ICmpInst(Cond, Base, 887 ConstantExpr::getPointerBitCastOrAddrSpaceCast( 888 cast<Constant>(RHS), Base->getType())); 889 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { 890 // If the base pointers are different, but the indices are the same, just 891 // compare the base pointer. 892 if (PtrBase != GEPRHS->getOperand(0)) { 893 bool IndicesTheSame = 894 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() && 895 GEPLHS->getPointerOperand()->getType() == 896 GEPRHS->getPointerOperand()->getType() && 897 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType(); 898 if (IndicesTheSame) 899 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 900 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 901 IndicesTheSame = false; 902 break; 903 } 904 905 // If all indices are the same, just compare the base pointers. 906 Type *BaseType = GEPLHS->getOperand(0)->getType(); 907 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType()) 908 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0)); 909 910 // If we're comparing GEPs with two base pointers that only differ in type 911 // and both GEPs have only constant indices or just one use, then fold 912 // the compare with the adjusted indices. 913 // FIXME: Support vector of pointers. 914 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() && 915 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) && 916 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) && 917 PtrBase->stripPointerCasts() == 918 GEPRHS->getOperand(0)->stripPointerCasts() && 919 !GEPLHS->getType()->isVectorTy()) { 920 Value *LOffset = EmitGEPOffset(GEPLHS); 921 Value *ROffset = EmitGEPOffset(GEPRHS); 922 923 // If we looked through an addrspacecast between different sized address 924 // spaces, the LHS and RHS pointers are different sized 925 // integers. Truncate to the smaller one. 926 Type *LHSIndexTy = LOffset->getType(); 927 Type *RHSIndexTy = ROffset->getType(); 928 if (LHSIndexTy != RHSIndexTy) { 929 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedSize() < 930 RHSIndexTy->getPrimitiveSizeInBits().getFixedSize()) { 931 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy); 932 } else 933 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy); 934 } 935 936 Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond), 937 LOffset, ROffset); 938 return replaceInstUsesWith(I, Cmp); 939 } 940 941 // Otherwise, the base pointers are different and the indices are 942 // different. Try convert this to an indexed compare by looking through 943 // PHIs/casts. 944 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 945 } 946 947 // If one of the GEPs has all zero indices, recurse. 948 // FIXME: Handle vector of pointers. 949 if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices()) 950 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0), 951 ICmpInst::getSwappedPredicate(Cond), I); 952 953 // If the other GEP has all zero indices, recurse. 954 // FIXME: Handle vector of pointers. 955 if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices()) 956 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); 957 958 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds(); 959 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() && 960 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) { 961 // If the GEPs only differ by one index, compare it. 962 unsigned NumDifferences = 0; // Keep track of # differences. 963 unsigned DiffOperand = 0; // The operand that differs. 964 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 965 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 966 Type *LHSType = GEPLHS->getOperand(i)->getType(); 967 Type *RHSType = GEPRHS->getOperand(i)->getType(); 968 // FIXME: Better support for vector of pointers. 969 if (LHSType->getPrimitiveSizeInBits() != 970 RHSType->getPrimitiveSizeInBits() || 971 (GEPLHS->getType()->isVectorTy() && 972 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) { 973 // Irreconcilable differences. 974 NumDifferences = 2; 975 break; 976 } 977 978 if (NumDifferences++) break; 979 DiffOperand = i; 980 } 981 982 if (NumDifferences == 0) // SAME GEP? 983 return replaceInstUsesWith(I, // No comparison is needed here. 984 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond))); 985 986 else if (NumDifferences == 1 && GEPsInBounds) { 987 Value *LHSV = GEPLHS->getOperand(DiffOperand); 988 Value *RHSV = GEPRHS->getOperand(DiffOperand); 989 // Make sure we do a signed comparison here. 990 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); 991 } 992 } 993 994 // Only lower this if the icmp is the only user of the GEP or if we expect 995 // the result to fold to a constant! 996 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && 997 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { 998 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) 999 Value *L = EmitGEPOffset(GEPLHS); 1000 Value *R = EmitGEPOffset(GEPRHS); 1001 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); 1002 } 1003 } 1004 1005 // Try convert this to an indexed compare by looking through PHIs/casts as a 1006 // last resort. 1007 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 1008 } 1009 1010 Instruction *InstCombinerImpl::foldAllocaCmp(ICmpInst &ICI, 1011 const AllocaInst *Alloca) { 1012 assert(ICI.isEquality() && "Cannot fold non-equality comparison."); 1013 1014 // It would be tempting to fold away comparisons between allocas and any 1015 // pointer not based on that alloca (e.g. an argument). However, even 1016 // though such pointers cannot alias, they can still compare equal. 1017 // 1018 // But LLVM doesn't specify where allocas get their memory, so if the alloca 1019 // doesn't escape we can argue that it's impossible to guess its value, and we 1020 // can therefore act as if any such guesses are wrong. 1021 // 1022 // The code below checks that the alloca doesn't escape, and that it's only 1023 // used in a comparison once (the current instruction). The 1024 // single-comparison-use condition ensures that we're trivially folding all 1025 // comparisons against the alloca consistently, and avoids the risk of 1026 // erroneously folding a comparison of the pointer with itself. 1027 1028 unsigned MaxIter = 32; // Break cycles and bound to constant-time. 1029 1030 SmallVector<const Use *, 32> Worklist; 1031 for (const Use &U : Alloca->uses()) { 1032 if (Worklist.size() >= MaxIter) 1033 return nullptr; 1034 Worklist.push_back(&U); 1035 } 1036 1037 unsigned NumCmps = 0; 1038 while (!Worklist.empty()) { 1039 assert(Worklist.size() <= MaxIter); 1040 const Use *U = Worklist.pop_back_val(); 1041 const Value *V = U->getUser(); 1042 --MaxIter; 1043 1044 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) || 1045 isa<SelectInst>(V)) { 1046 // Track the uses. 1047 } else if (isa<LoadInst>(V)) { 1048 // Loading from the pointer doesn't escape it. 1049 continue; 1050 } else if (const auto *SI = dyn_cast<StoreInst>(V)) { 1051 // Storing *to* the pointer is fine, but storing the pointer escapes it. 1052 if (SI->getValueOperand() == U->get()) 1053 return nullptr; 1054 continue; 1055 } else if (isa<ICmpInst>(V)) { 1056 if (NumCmps++) 1057 return nullptr; // Found more than one cmp. 1058 continue; 1059 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) { 1060 switch (Intrin->getIntrinsicID()) { 1061 // These intrinsics don't escape or compare the pointer. Memset is safe 1062 // because we don't allow ptrtoint. Memcpy and memmove are safe because 1063 // we don't allow stores, so src cannot point to V. 1064 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: 1065 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: 1066 continue; 1067 default: 1068 return nullptr; 1069 } 1070 } else { 1071 return nullptr; 1072 } 1073 for (const Use &U : V->uses()) { 1074 if (Worklist.size() >= MaxIter) 1075 return nullptr; 1076 Worklist.push_back(&U); 1077 } 1078 } 1079 1080 auto *Res = ConstantInt::get(ICI.getType(), 1081 !CmpInst::isTrueWhenEqual(ICI.getPredicate())); 1082 return replaceInstUsesWith(ICI, Res); 1083 } 1084 1085 /// Fold "icmp pred (X+C), X". 1086 Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C, 1087 ICmpInst::Predicate Pred) { 1088 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, 1089 // so the values can never be equal. Similarly for all other "or equals" 1090 // operators. 1091 assert(!!C && "C should not be zero!"); 1092 1093 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 1094 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 1095 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 1096 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 1097 Constant *R = ConstantInt::get(X->getType(), 1098 APInt::getMaxValue(C.getBitWidth()) - C); 1099 return new ICmpInst(ICmpInst::ICMP_UGT, X, R); 1100 } 1101 1102 // (X+1) >u X --> X <u (0-1) --> X != 255 1103 // (X+2) >u X --> X <u (0-2) --> X <u 254 1104 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 1105 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) 1106 return new ICmpInst(ICmpInst::ICMP_ULT, X, 1107 ConstantInt::get(X->getType(), -C)); 1108 1109 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth()); 1110 1111 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 1112 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 1113 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 1114 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 1115 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 1116 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 1117 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 1118 return new ICmpInst(ICmpInst::ICMP_SGT, X, 1119 ConstantInt::get(X->getType(), SMax - C)); 1120 1121 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 1122 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 1123 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 1124 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 1125 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 1126 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 1127 1128 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); 1129 return new ICmpInst(ICmpInst::ICMP_SLT, X, 1130 ConstantInt::get(X->getType(), SMax - (C - 1))); 1131 } 1132 1133 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> 1134 /// (icmp eq/ne A, Log2(AP2/AP1)) -> 1135 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)). 1136 Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A, 1137 const APInt &AP1, 1138 const APInt &AP2) { 1139 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1140 1141 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1142 if (I.getPredicate() == I.ICMP_NE) 1143 Pred = CmpInst::getInversePredicate(Pred); 1144 return new ICmpInst(Pred, LHS, RHS); 1145 }; 1146 1147 // Don't bother doing any work for cases which InstSimplify handles. 1148 if (AP2.isZero()) 1149 return nullptr; 1150 1151 bool IsAShr = isa<AShrOperator>(I.getOperand(0)); 1152 if (IsAShr) { 1153 if (AP2.isAllOnes()) 1154 return nullptr; 1155 if (AP2.isNegative() != AP1.isNegative()) 1156 return nullptr; 1157 if (AP2.sgt(AP1)) 1158 return nullptr; 1159 } 1160 1161 if (!AP1) 1162 // 'A' must be large enough to shift out the highest set bit. 1163 return getICmp(I.ICMP_UGT, A, 1164 ConstantInt::get(A->getType(), AP2.logBase2())); 1165 1166 if (AP1 == AP2) 1167 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1168 1169 int Shift; 1170 if (IsAShr && AP1.isNegative()) 1171 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes(); 1172 else 1173 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros(); 1174 1175 if (Shift > 0) { 1176 if (IsAShr && AP1 == AP2.ashr(Shift)) { 1177 // There are multiple solutions if we are comparing against -1 and the LHS 1178 // of the ashr is not a power of two. 1179 if (AP1.isAllOnes() && !AP2.isPowerOf2()) 1180 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift)); 1181 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1182 } else if (AP1 == AP2.lshr(Shift)) { 1183 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1184 } 1185 } 1186 1187 // Shifting const2 will never be equal to const1. 1188 // FIXME: This should always be handled by InstSimplify? 1189 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1190 return replaceInstUsesWith(I, TorF); 1191 } 1192 1193 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" -> 1194 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)). 1195 Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A, 1196 const APInt &AP1, 1197 const APInt &AP2) { 1198 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1199 1200 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1201 if (I.getPredicate() == I.ICMP_NE) 1202 Pred = CmpInst::getInversePredicate(Pred); 1203 return new ICmpInst(Pred, LHS, RHS); 1204 }; 1205 1206 // Don't bother doing any work for cases which InstSimplify handles. 1207 if (AP2.isZero()) 1208 return nullptr; 1209 1210 unsigned AP2TrailingZeros = AP2.countTrailingZeros(); 1211 1212 if (!AP1 && AP2TrailingZeros != 0) 1213 return getICmp( 1214 I.ICMP_UGE, A, 1215 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros)); 1216 1217 if (AP1 == AP2) 1218 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1219 1220 // Get the distance between the lowest bits that are set. 1221 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros; 1222 1223 if (Shift > 0 && AP2.shl(Shift) == AP1) 1224 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1225 1226 // Shifting const2 will never be equal to const1. 1227 // FIXME: This should always be handled by InstSimplify? 1228 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1229 return replaceInstUsesWith(I, TorF); 1230 } 1231 1232 /// The caller has matched a pattern of the form: 1233 /// I = icmp ugt (add (add A, B), CI2), CI1 1234 /// If this is of the form: 1235 /// sum = a + b 1236 /// if (sum+128 >u 255) 1237 /// Then replace it with llvm.sadd.with.overflow.i8. 1238 /// 1239 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, 1240 ConstantInt *CI2, ConstantInt *CI1, 1241 InstCombinerImpl &IC) { 1242 // The transformation we're trying to do here is to transform this into an 1243 // llvm.sadd.with.overflow. To do this, we have to replace the original add 1244 // with a narrower add, and discard the add-with-constant that is part of the 1245 // range check (if we can't eliminate it, this isn't profitable). 1246 1247 // In order to eliminate the add-with-constant, the compare can be its only 1248 // use. 1249 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0)); 1250 if (!AddWithCst->hasOneUse()) 1251 return nullptr; 1252 1253 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. 1254 if (!CI2->getValue().isPowerOf2()) 1255 return nullptr; 1256 unsigned NewWidth = CI2->getValue().countTrailingZeros(); 1257 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) 1258 return nullptr; 1259 1260 // The width of the new add formed is 1 more than the bias. 1261 ++NewWidth; 1262 1263 // Check to see that CI1 is an all-ones value with NewWidth bits. 1264 if (CI1->getBitWidth() == NewWidth || 1265 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) 1266 return nullptr; 1267 1268 // This is only really a signed overflow check if the inputs have been 1269 // sign-extended; check for that condition. For example, if CI2 is 2^31 and 1270 // the operands of the add are 64 bits wide, we need at least 33 sign bits. 1271 if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth || 1272 IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth) 1273 return nullptr; 1274 1275 // In order to replace the original add with a narrower 1276 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant 1277 // and truncates that discard the high bits of the add. Verify that this is 1278 // the case. 1279 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0)); 1280 for (User *U : OrigAdd->users()) { 1281 if (U == AddWithCst) 1282 continue; 1283 1284 // Only accept truncates for now. We would really like a nice recursive 1285 // predicate like SimplifyDemandedBits, but which goes downwards the use-def 1286 // chain to see which bits of a value are actually demanded. If the 1287 // original add had another add which was then immediately truncated, we 1288 // could still do the transformation. 1289 TruncInst *TI = dyn_cast<TruncInst>(U); 1290 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth) 1291 return nullptr; 1292 } 1293 1294 // If the pattern matches, truncate the inputs to the narrower type and 1295 // use the sadd_with_overflow intrinsic to efficiently compute both the 1296 // result and the overflow bit. 1297 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); 1298 Function *F = Intrinsic::getDeclaration( 1299 I.getModule(), Intrinsic::sadd_with_overflow, NewType); 1300 1301 InstCombiner::BuilderTy &Builder = IC.Builder; 1302 1303 // Put the new code above the original add, in case there are any uses of the 1304 // add between the add and the compare. 1305 Builder.SetInsertPoint(OrigAdd); 1306 1307 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc"); 1308 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc"); 1309 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd"); 1310 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result"); 1311 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType()); 1312 1313 // The inner add was the result of the narrow add, zero extended to the 1314 // wider type. Replace it with the result computed by the intrinsic. 1315 IC.replaceInstUsesWith(*OrigAdd, ZExt); 1316 IC.eraseInstFromFunction(*OrigAdd); 1317 1318 // The original icmp gets replaced with the overflow value. 1319 return ExtractValueInst::Create(Call, 1, "sadd.overflow"); 1320 } 1321 1322 /// If we have: 1323 /// icmp eq/ne (urem/srem %x, %y), 0 1324 /// iff %y is a power-of-two, we can replace this with a bit test: 1325 /// icmp eq/ne (and %x, (add %y, -1)), 0 1326 Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) { 1327 // This fold is only valid for equality predicates. 1328 if (!I.isEquality()) 1329 return nullptr; 1330 ICmpInst::Predicate Pred; 1331 Value *X, *Y, *Zero; 1332 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))), 1333 m_CombineAnd(m_Zero(), m_Value(Zero))))) 1334 return nullptr; 1335 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I)) 1336 return nullptr; 1337 // This may increase instruction count, we don't enforce that Y is a constant. 1338 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType())); 1339 Value *Masked = Builder.CreateAnd(X, Mask); 1340 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero); 1341 } 1342 1343 /// Fold equality-comparison between zero and any (maybe truncated) right-shift 1344 /// by one-less-than-bitwidth into a sign test on the original value. 1345 Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) { 1346 Instruction *Val; 1347 ICmpInst::Predicate Pred; 1348 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero()))) 1349 return nullptr; 1350 1351 Value *X; 1352 Type *XTy; 1353 1354 Constant *C; 1355 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) { 1356 XTy = X->getType(); 1357 unsigned XBitWidth = XTy->getScalarSizeInBits(); 1358 if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ, 1359 APInt(XBitWidth, XBitWidth - 1)))) 1360 return nullptr; 1361 } else if (isa<BinaryOperator>(Val) && 1362 (X = reassociateShiftAmtsOfTwoSameDirectionShifts( 1363 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val), 1364 /*AnalyzeForSignBitExtraction=*/true))) { 1365 XTy = X->getType(); 1366 } else 1367 return nullptr; 1368 1369 return ICmpInst::Create(Instruction::ICmp, 1370 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE 1371 : ICmpInst::ICMP_SLT, 1372 X, ConstantInt::getNullValue(XTy)); 1373 } 1374 1375 // Handle icmp pred X, 0 1376 Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) { 1377 CmpInst::Predicate Pred = Cmp.getPredicate(); 1378 if (!match(Cmp.getOperand(1), m_Zero())) 1379 return nullptr; 1380 1381 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0) 1382 if (Pred == ICmpInst::ICMP_SGT) { 1383 Value *A, *B; 1384 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) { 1385 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT)) 1386 return new ICmpInst(Pred, B, Cmp.getOperand(1)); 1387 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT)) 1388 return new ICmpInst(Pred, A, Cmp.getOperand(1)); 1389 } 1390 } 1391 1392 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp)) 1393 return New; 1394 1395 // Given: 1396 // icmp eq/ne (urem %x, %y), 0 1397 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 1398 // icmp eq/ne %x, 0 1399 Value *X, *Y; 1400 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) && 1401 ICmpInst::isEquality(Pred)) { 1402 KnownBits XKnown = computeKnownBits(X, 0, &Cmp); 1403 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp); 1404 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 1405 return new ICmpInst(Pred, X, Cmp.getOperand(1)); 1406 } 1407 1408 return nullptr; 1409 } 1410 1411 /// Fold icmp Pred X, C. 1412 /// TODO: This code structure does not make sense. The saturating add fold 1413 /// should be moved to some other helper and extended as noted below (it is also 1414 /// possible that code has been made unnecessary - do we canonicalize IR to 1415 /// overflow/saturating intrinsics or not?). 1416 Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) { 1417 // Match the following pattern, which is a common idiom when writing 1418 // overflow-safe integer arithmetic functions. The source performs an addition 1419 // in wider type and explicitly checks for overflow using comparisons against 1420 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic. 1421 // 1422 // TODO: This could probably be generalized to handle other overflow-safe 1423 // operations if we worked out the formulas to compute the appropriate magic 1424 // constants. 1425 // 1426 // sum = a + b 1427 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8 1428 CmpInst::Predicate Pred = Cmp.getPredicate(); 1429 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1); 1430 Value *A, *B; 1431 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI 1432 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) && 1433 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2)))) 1434 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this)) 1435 return Res; 1436 1437 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...). 1438 Constant *C = dyn_cast<Constant>(Op1); 1439 if (!C || C->canTrap()) 1440 return nullptr; 1441 1442 if (auto *Phi = dyn_cast<PHINode>(Op0)) 1443 if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) { 1444 Type *Ty = Cmp.getType(); 1445 Builder.SetInsertPoint(Phi); 1446 PHINode *NewPhi = 1447 Builder.CreatePHI(Ty, Phi->getNumOperands()); 1448 for (BasicBlock *Predecessor : predecessors(Phi->getParent())) { 1449 auto *Input = 1450 cast<Constant>(Phi->getIncomingValueForBlock(Predecessor)); 1451 auto *BoolInput = ConstantExpr::getCompare(Pred, Input, C); 1452 NewPhi->addIncoming(BoolInput, Predecessor); 1453 } 1454 NewPhi->takeName(&Cmp); 1455 return replaceInstUsesWith(Cmp, NewPhi); 1456 } 1457 1458 return nullptr; 1459 } 1460 1461 /// Canonicalize icmp instructions based on dominating conditions. 1462 Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) { 1463 // This is a cheap/incomplete check for dominance - just match a single 1464 // predecessor with a conditional branch. 1465 BasicBlock *CmpBB = Cmp.getParent(); 1466 BasicBlock *DomBB = CmpBB->getSinglePredecessor(); 1467 if (!DomBB) 1468 return nullptr; 1469 1470 Value *DomCond; 1471 BasicBlock *TrueBB, *FalseBB; 1472 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB))) 1473 return nullptr; 1474 1475 assert((TrueBB == CmpBB || FalseBB == CmpBB) && 1476 "Predecessor block does not point to successor?"); 1477 1478 // The branch should get simplified. Don't bother simplifying this condition. 1479 if (TrueBB == FalseBB) 1480 return nullptr; 1481 1482 // Try to simplify this compare to T/F based on the dominating condition. 1483 Optional<bool> Imp = isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB); 1484 if (Imp) 1485 return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp)); 1486 1487 CmpInst::Predicate Pred = Cmp.getPredicate(); 1488 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1); 1489 ICmpInst::Predicate DomPred; 1490 const APInt *C, *DomC; 1491 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) && 1492 match(Y, m_APInt(C))) { 1493 // We have 2 compares of a variable with constants. Calculate the constant 1494 // ranges of those compares to see if we can transform the 2nd compare: 1495 // DomBB: 1496 // DomCond = icmp DomPred X, DomC 1497 // br DomCond, CmpBB, FalseBB 1498 // CmpBB: 1499 // Cmp = icmp Pred X, C 1500 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *C); 1501 ConstantRange DominatingCR = 1502 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC) 1503 : ConstantRange::makeExactICmpRegion( 1504 CmpInst::getInversePredicate(DomPred), *DomC); 1505 ConstantRange Intersection = DominatingCR.intersectWith(CR); 1506 ConstantRange Difference = DominatingCR.difference(CR); 1507 if (Intersection.isEmptySet()) 1508 return replaceInstUsesWith(Cmp, Builder.getFalse()); 1509 if (Difference.isEmptySet()) 1510 return replaceInstUsesWith(Cmp, Builder.getTrue()); 1511 1512 // Canonicalizing a sign bit comparison that gets used in a branch, 1513 // pessimizes codegen by generating branch on zero instruction instead 1514 // of a test and branch. So we avoid canonicalizing in such situations 1515 // because test and branch instruction has better branch displacement 1516 // than compare and branch instruction. 1517 bool UnusedBit; 1518 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit); 1519 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp))) 1520 return nullptr; 1521 1522 // Avoid an infinite loop with min/max canonicalization. 1523 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics. 1524 if (Cmp.hasOneUse() && 1525 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value()))) 1526 return nullptr; 1527 1528 if (const APInt *EqC = Intersection.getSingleElement()) 1529 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC)); 1530 if (const APInt *NeC = Difference.getSingleElement()) 1531 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC)); 1532 } 1533 1534 return nullptr; 1535 } 1536 1537 /// Fold icmp (trunc X, Y), C. 1538 Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp, 1539 TruncInst *Trunc, 1540 const APInt &C) { 1541 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1542 Value *X = Trunc->getOperand(0); 1543 if (C.isOne() && C.getBitWidth() > 1) { 1544 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1 1545 Value *V = nullptr; 1546 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V)))) 1547 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1548 ConstantInt::get(V->getType(), 1)); 1549 } 1550 1551 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(), 1552 SrcBits = X->getType()->getScalarSizeInBits(); 1553 if (Cmp.isEquality() && Trunc->hasOneUse()) { 1554 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all 1555 // of the high bits truncated out of x are known. 1556 KnownBits Known = computeKnownBits(X, 0, &Cmp); 1557 1558 // If all the high bits are known, we can do this xform. 1559 if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) { 1560 // Pull in the high bits from known-ones set. 1561 APInt NewRHS = C.zext(SrcBits); 1562 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits); 1563 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS)); 1564 } 1565 } 1566 1567 // Look through truncated right-shift of the sign-bit for a sign-bit check: 1568 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0 1569 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1 1570 Value *ShOp; 1571 const APInt *ShAmtC; 1572 bool TrueIfSigned; 1573 if (isSignBitCheck(Pred, C, TrueIfSigned) && 1574 match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) && 1575 DstBits == SrcBits - ShAmtC->getZExtValue()) { 1576 return TrueIfSigned 1577 ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp, 1578 ConstantInt::getNullValue(X->getType())) 1579 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp, 1580 ConstantInt::getAllOnesValue(X->getType())); 1581 } 1582 1583 return nullptr; 1584 } 1585 1586 /// Fold icmp (xor X, Y), C. 1587 Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp, 1588 BinaryOperator *Xor, 1589 const APInt &C) { 1590 Value *X = Xor->getOperand(0); 1591 Value *Y = Xor->getOperand(1); 1592 const APInt *XorC; 1593 if (!match(Y, m_APInt(XorC))) 1594 return nullptr; 1595 1596 // If this is a comparison that tests the signbit (X < 0) or (x > -1), 1597 // fold the xor. 1598 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1599 bool TrueIfSigned = false; 1600 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) { 1601 1602 // If the sign bit of the XorCst is not set, there is no change to 1603 // the operation, just stop using the Xor. 1604 if (!XorC->isNegative()) 1605 return replaceOperand(Cmp, 0, X); 1606 1607 // Emit the opposite comparison. 1608 if (TrueIfSigned) 1609 return new ICmpInst(ICmpInst::ICMP_SGT, X, 1610 ConstantInt::getAllOnesValue(X->getType())); 1611 else 1612 return new ICmpInst(ICmpInst::ICMP_SLT, X, 1613 ConstantInt::getNullValue(X->getType())); 1614 } 1615 1616 if (Xor->hasOneUse()) { 1617 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask)) 1618 if (!Cmp.isEquality() && XorC->isSignMask()) { 1619 Pred = Cmp.getFlippedSignednessPredicate(); 1620 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC)); 1621 } 1622 1623 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask)) 1624 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) { 1625 Pred = Cmp.getFlippedSignednessPredicate(); 1626 Pred = Cmp.getSwappedPredicate(Pred); 1627 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC)); 1628 } 1629 } 1630 1631 // Mask constant magic can eliminate an 'xor' with unsigned compares. 1632 if (Pred == ICmpInst::ICMP_UGT) { 1633 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2) 1634 if (*XorC == ~C && (C + 1).isPowerOf2()) 1635 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 1636 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2) 1637 if (*XorC == C && (C + 1).isPowerOf2()) 1638 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); 1639 } 1640 if (Pred == ICmpInst::ICMP_ULT) { 1641 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2) 1642 if (*XorC == -C && C.isPowerOf2()) 1643 return new ICmpInst(ICmpInst::ICMP_UGT, X, 1644 ConstantInt::get(X->getType(), ~C)); 1645 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2) 1646 if (*XorC == C && (-C).isPowerOf2()) 1647 return new ICmpInst(ICmpInst::ICMP_UGT, X, 1648 ConstantInt::get(X->getType(), ~C)); 1649 } 1650 return nullptr; 1651 } 1652 1653 /// Fold icmp (and (sh X, Y), C2), C1. 1654 Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp, 1655 BinaryOperator *And, 1656 const APInt &C1, 1657 const APInt &C2) { 1658 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0)); 1659 if (!Shift || !Shift->isShift()) 1660 return nullptr; 1661 1662 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could 1663 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in 1664 // code produced by the clang front-end, for bitfield access. 1665 // This seemingly simple opportunity to fold away a shift turns out to be 1666 // rather complicated. See PR17827 for details. 1667 unsigned ShiftOpcode = Shift->getOpcode(); 1668 bool IsShl = ShiftOpcode == Instruction::Shl; 1669 const APInt *C3; 1670 if (match(Shift->getOperand(1), m_APInt(C3))) { 1671 APInt NewAndCst, NewCmpCst; 1672 bool AnyCmpCstBitsShiftedOut; 1673 if (ShiftOpcode == Instruction::Shl) { 1674 // For a left shift, we can fold if the comparison is not signed. We can 1675 // also fold a signed comparison if the mask value and comparison value 1676 // are not negative. These constraints may not be obvious, but we can 1677 // prove that they are correct using an SMT solver. 1678 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative())) 1679 return nullptr; 1680 1681 NewCmpCst = C1.lshr(*C3); 1682 NewAndCst = C2.lshr(*C3); 1683 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1; 1684 } else if (ShiftOpcode == Instruction::LShr) { 1685 // For a logical right shift, we can fold if the comparison is not signed. 1686 // We can also fold a signed comparison if the shifted mask value and the 1687 // shifted comparison value are not negative. These constraints may not be 1688 // obvious, but we can prove that they are correct using an SMT solver. 1689 NewCmpCst = C1.shl(*C3); 1690 NewAndCst = C2.shl(*C3); 1691 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1; 1692 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative())) 1693 return nullptr; 1694 } else { 1695 // For an arithmetic shift, check that both constants don't use (in a 1696 // signed sense) the top bits being shifted out. 1697 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode"); 1698 NewCmpCst = C1.shl(*C3); 1699 NewAndCst = C2.shl(*C3); 1700 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1; 1701 if (NewAndCst.ashr(*C3) != C2) 1702 return nullptr; 1703 } 1704 1705 if (AnyCmpCstBitsShiftedOut) { 1706 // If we shifted bits out, the fold is not going to work out. As a 1707 // special case, check to see if this means that the result is always 1708 // true or false now. 1709 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ) 1710 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType())); 1711 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) 1712 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType())); 1713 } else { 1714 Value *NewAnd = Builder.CreateAnd( 1715 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst)); 1716 return new ICmpInst(Cmp.getPredicate(), 1717 NewAnd, ConstantInt::get(And->getType(), NewCmpCst)); 1718 } 1719 } 1720 1721 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is 1722 // preferable because it allows the C2 << Y expression to be hoisted out of a 1723 // loop if Y is invariant and X is not. 1724 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() && 1725 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) { 1726 // Compute C2 << Y. 1727 Value *NewShift = 1728 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1)) 1729 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1)); 1730 1731 // Compute X & (C2 << Y). 1732 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift); 1733 return replaceOperand(Cmp, 0, NewAnd); 1734 } 1735 1736 return nullptr; 1737 } 1738 1739 /// Fold icmp (and X, C2), C1. 1740 Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp, 1741 BinaryOperator *And, 1742 const APInt &C1) { 1743 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE; 1744 1745 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1 1746 // TODO: We canonicalize to the longer form for scalars because we have 1747 // better analysis/folds for icmp, and codegen may be better with icmp. 1748 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() && 1749 match(And->getOperand(1), m_One())) 1750 return new TruncInst(And->getOperand(0), Cmp.getType()); 1751 1752 const APInt *C2; 1753 Value *X; 1754 if (!match(And, m_And(m_Value(X), m_APInt(C2)))) 1755 return nullptr; 1756 1757 // Don't perform the following transforms if the AND has multiple uses 1758 if (!And->hasOneUse()) 1759 return nullptr; 1760 1761 if (Cmp.isEquality() && C1.isZero()) { 1762 // Restrict this fold to single-use 'and' (PR10267). 1763 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0 1764 if (C2->isSignMask()) { 1765 Constant *Zero = Constant::getNullValue(X->getType()); 1766 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; 1767 return new ICmpInst(NewPred, X, Zero); 1768 } 1769 1770 // Restrict this fold only for single-use 'and' (PR10267). 1771 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two. 1772 if ((~(*C2) + 1).isPowerOf2()) { 1773 Constant *NegBOC = 1774 ConstantExpr::getNeg(cast<Constant>(And->getOperand(1))); 1775 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 1776 return new ICmpInst(NewPred, X, NegBOC); 1777 } 1778 } 1779 1780 // If the LHS is an 'and' of a truncate and we can widen the and/compare to 1781 // the input width without changing the value produced, eliminate the cast: 1782 // 1783 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1' 1784 // 1785 // We can do this transformation if the constants do not have their sign bits 1786 // set or if it is an equality comparison. Extending a relational comparison 1787 // when we're checking the sign bit would not work. 1788 Value *W; 1789 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) && 1790 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) { 1791 // TODO: Is this a good transform for vectors? Wider types may reduce 1792 // throughput. Should this transform be limited (even for scalars) by using 1793 // shouldChangeType()? 1794 if (!Cmp.getType()->isVectorTy()) { 1795 Type *WideType = W->getType(); 1796 unsigned WideScalarBits = WideType->getScalarSizeInBits(); 1797 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits)); 1798 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits)); 1799 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName()); 1800 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1); 1801 } 1802 } 1803 1804 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2)) 1805 return I; 1806 1807 // (icmp pred (and (or (lshr A, B), A), 1), 0) --> 1808 // (icmp pred (and A, (or (shl 1, B), 1), 0)) 1809 // 1810 // iff pred isn't signed 1811 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() && 1812 match(And->getOperand(1), m_One())) { 1813 Constant *One = cast<Constant>(And->getOperand(1)); 1814 Value *Or = And->getOperand(0); 1815 Value *A, *B, *LShr; 1816 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) && 1817 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) { 1818 unsigned UsesRemoved = 0; 1819 if (And->hasOneUse()) 1820 ++UsesRemoved; 1821 if (Or->hasOneUse()) 1822 ++UsesRemoved; 1823 if (LShr->hasOneUse()) 1824 ++UsesRemoved; 1825 1826 // Compute A & ((1 << B) | 1) 1827 Value *NewOr = nullptr; 1828 if (auto *C = dyn_cast<Constant>(B)) { 1829 if (UsesRemoved >= 1) 1830 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One); 1831 } else { 1832 if (UsesRemoved >= 3) 1833 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(), 1834 /*HasNUW=*/true), 1835 One, Or->getName()); 1836 } 1837 if (NewOr) { 1838 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName()); 1839 return replaceOperand(Cmp, 0, NewAnd); 1840 } 1841 } 1842 } 1843 1844 return nullptr; 1845 } 1846 1847 /// Fold icmp (and X, Y), C. 1848 Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp, 1849 BinaryOperator *And, 1850 const APInt &C) { 1851 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C)) 1852 return I; 1853 1854 const ICmpInst::Predicate Pred = Cmp.getPredicate(); 1855 bool TrueIfNeg; 1856 if (isSignBitCheck(Pred, C, TrueIfNeg)) { 1857 // ((X - 1) & ~X) < 0 --> X == 0 1858 // ((X - 1) & ~X) >= 0 --> X != 0 1859 Value *X; 1860 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) && 1861 match(And->getOperand(1), m_Not(m_Specific(X)))) { 1862 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE; 1863 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType())); 1864 } 1865 } 1866 1867 // TODO: These all require that Y is constant too, so refactor with the above. 1868 1869 // Try to optimize things like "A[i] & 42 == 0" to index computations. 1870 Value *X = And->getOperand(0); 1871 Value *Y = And->getOperand(1); 1872 if (auto *C2 = dyn_cast<ConstantInt>(Y)) 1873 if (auto *LI = dyn_cast<LoadInst>(X)) 1874 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) 1875 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1876 if (Instruction *Res = 1877 foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2)) 1878 return Res; 1879 1880 if (!Cmp.isEquality()) 1881 return nullptr; 1882 1883 // X & -C == -C -> X > u ~C 1884 // X & -C != -C -> X <= u ~C 1885 // iff C is a power of 2 1886 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) { 1887 auto NewPred = 1888 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE; 1889 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1)))); 1890 } 1891 1892 return nullptr; 1893 } 1894 1895 /// Fold icmp (or X, Y), C. 1896 Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp, 1897 BinaryOperator *Or, 1898 const APInt &C) { 1899 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1900 if (C.isOne()) { 1901 // icmp slt signum(V) 1 --> icmp slt V, 1 1902 Value *V = nullptr; 1903 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V)))) 1904 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1905 ConstantInt::get(V->getType(), 1)); 1906 } 1907 1908 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1); 1909 const APInt *MaskC; 1910 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) { 1911 if (*MaskC == C && (C + 1).isPowerOf2()) { 1912 // X | C == C --> X <=u C 1913 // X | C != C --> X >u C 1914 // iff C+1 is a power of 2 (C is a bitmask of the low bits) 1915 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT; 1916 return new ICmpInst(Pred, OrOp0, OrOp1); 1917 } 1918 1919 // More general: canonicalize 'equality with set bits mask' to 1920 // 'equality with clear bits mask'. 1921 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC 1922 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC 1923 if (Or->hasOneUse()) { 1924 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC)); 1925 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC)); 1926 return new ICmpInst(Pred, And, NewC); 1927 } 1928 } 1929 1930 // (X | (X-1)) s< 0 --> X s< 1 1931 // (X | (X-1)) s> -1 --> X s> 0 1932 Value *X; 1933 bool TrueIfSigned; 1934 if (isSignBitCheck(Pred, C, TrueIfSigned) && 1935 match(Or, m_c_Or(m_Add(m_Value(X), m_AllOnes()), m_Deferred(X)))) { 1936 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT; 1937 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0); 1938 return new ICmpInst(NewPred, X, NewC); 1939 } 1940 1941 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse()) 1942 return nullptr; 1943 1944 Value *P, *Q; 1945 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { 1946 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 1947 // -> and (icmp eq P, null), (icmp eq Q, null). 1948 Value *CmpP = 1949 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType())); 1950 Value *CmpQ = 1951 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType())); 1952 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1953 return BinaryOperator::Create(BOpc, CmpP, CmpQ); 1954 } 1955 1956 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to 1957 // a shorter form that has more potential to be folded even further. 1958 Value *X1, *X2, *X3, *X4; 1959 if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) && 1960 match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) { 1961 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4) 1962 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4) 1963 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2); 1964 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4); 1965 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1966 return BinaryOperator::Create(BOpc, Cmp12, Cmp34); 1967 } 1968 1969 return nullptr; 1970 } 1971 1972 /// Fold icmp (mul X, Y), C. 1973 Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp, 1974 BinaryOperator *Mul, 1975 const APInt &C) { 1976 const APInt *MulC; 1977 if (!match(Mul->getOperand(1), m_APInt(MulC))) 1978 return nullptr; 1979 1980 // If this is a test of the sign bit and the multiply is sign-preserving with 1981 // a constant operand, use the multiply LHS operand instead. 1982 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1983 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) { 1984 if (MulC->isNegative()) 1985 Pred = ICmpInst::getSwappedPredicate(Pred); 1986 return new ICmpInst(Pred, Mul->getOperand(0), 1987 Constant::getNullValue(Mul->getType())); 1988 } 1989 1990 // If the multiply does not wrap, try to divide the compare constant by the 1991 // multiplication factor. 1992 if (Cmp.isEquality() && !MulC->isZero()) { 1993 // (mul nsw X, MulC) == C --> X == C /s MulC 1994 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) { 1995 Constant *NewC = ConstantInt::get(Mul->getType(), C.sdiv(*MulC)); 1996 return new ICmpInst(Pred, Mul->getOperand(0), NewC); 1997 } 1998 // (mul nuw X, MulC) == C --> X == C /u MulC 1999 if (Mul->hasNoUnsignedWrap() && C.urem(*MulC).isZero()) { 2000 Constant *NewC = ConstantInt::get(Mul->getType(), C.udiv(*MulC)); 2001 return new ICmpInst(Pred, Mul->getOperand(0), NewC); 2002 } 2003 } 2004 2005 return nullptr; 2006 } 2007 2008 /// Fold icmp (shl 1, Y), C. 2009 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, 2010 const APInt &C) { 2011 Value *Y; 2012 if (!match(Shl, m_Shl(m_One(), m_Value(Y)))) 2013 return nullptr; 2014 2015 Type *ShiftType = Shl->getType(); 2016 unsigned TypeBits = C.getBitWidth(); 2017 bool CIsPowerOf2 = C.isPowerOf2(); 2018 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2019 if (Cmp.isUnsigned()) { 2020 // (1 << Y) pred C -> Y pred Log2(C) 2021 if (!CIsPowerOf2) { 2022 // (1 << Y) < 30 -> Y <= 4 2023 // (1 << Y) <= 30 -> Y <= 4 2024 // (1 << Y) >= 30 -> Y > 4 2025 // (1 << Y) > 30 -> Y > 4 2026 if (Pred == ICmpInst::ICMP_ULT) 2027 Pred = ICmpInst::ICMP_ULE; 2028 else if (Pred == ICmpInst::ICMP_UGE) 2029 Pred = ICmpInst::ICMP_UGT; 2030 } 2031 2032 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31 2033 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31 2034 unsigned CLog2 = C.logBase2(); 2035 if (CLog2 == TypeBits - 1) { 2036 if (Pred == ICmpInst::ICMP_UGE) 2037 Pred = ICmpInst::ICMP_EQ; 2038 else if (Pred == ICmpInst::ICMP_ULT) 2039 Pred = ICmpInst::ICMP_NE; 2040 } 2041 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2)); 2042 } else if (Cmp.isSigned()) { 2043 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1); 2044 if (C.isAllOnes()) { 2045 // (1 << Y) <= -1 -> Y == 31 2046 if (Pred == ICmpInst::ICMP_SLE) 2047 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 2048 2049 // (1 << Y) > -1 -> Y != 31 2050 if (Pred == ICmpInst::ICMP_SGT) 2051 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 2052 } else if (!C) { 2053 // (1 << Y) < 0 -> Y == 31 2054 // (1 << Y) <= 0 -> Y == 31 2055 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 2056 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 2057 2058 // (1 << Y) >= 0 -> Y != 31 2059 // (1 << Y) > 0 -> Y != 31 2060 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) 2061 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 2062 } 2063 } else if (Cmp.isEquality() && CIsPowerOf2) { 2064 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C.logBase2())); 2065 } 2066 2067 return nullptr; 2068 } 2069 2070 /// Fold icmp (shl X, Y), C. 2071 Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp, 2072 BinaryOperator *Shl, 2073 const APInt &C) { 2074 const APInt *ShiftVal; 2075 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal))) 2076 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal); 2077 2078 const APInt *ShiftAmt; 2079 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt))) 2080 return foldICmpShlOne(Cmp, Shl, C); 2081 2082 // Check that the shift amount is in range. If not, don't perform undefined 2083 // shifts. When the shift is visited, it will be simplified. 2084 unsigned TypeBits = C.getBitWidth(); 2085 if (ShiftAmt->uge(TypeBits)) 2086 return nullptr; 2087 2088 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2089 Value *X = Shl->getOperand(0); 2090 Type *ShType = Shl->getType(); 2091 2092 // NSW guarantees that we are only shifting out sign bits from the high bits, 2093 // so we can ASHR the compare constant without needing a mask and eliminate 2094 // the shift. 2095 if (Shl->hasNoSignedWrap()) { 2096 if (Pred == ICmpInst::ICMP_SGT) { 2097 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt) 2098 APInt ShiftedC = C.ashr(*ShiftAmt); 2099 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2100 } 2101 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) && 2102 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) { 2103 APInt ShiftedC = C.ashr(*ShiftAmt); 2104 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2105 } 2106 if (Pred == ICmpInst::ICMP_SLT) { 2107 // SLE is the same as above, but SLE is canonicalized to SLT, so convert: 2108 // (X << S) <=s C is equiv to X <=s (C >> S) for all C 2109 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX 2110 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN 2111 assert(!C.isMinSignedValue() && "Unexpected icmp slt"); 2112 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1; 2113 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2114 } 2115 // If this is a signed comparison to 0 and the shift is sign preserving, 2116 // use the shift LHS operand instead; isSignTest may change 'Pred', so only 2117 // do that if we're sure to not continue on in this function. 2118 if (isSignTest(Pred, C)) 2119 return new ICmpInst(Pred, X, Constant::getNullValue(ShType)); 2120 } 2121 2122 // NUW guarantees that we are only shifting out zero bits from the high bits, 2123 // so we can LSHR the compare constant without needing a mask and eliminate 2124 // the shift. 2125 if (Shl->hasNoUnsignedWrap()) { 2126 if (Pred == ICmpInst::ICMP_UGT) { 2127 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt) 2128 APInt ShiftedC = C.lshr(*ShiftAmt); 2129 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2130 } 2131 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) && 2132 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) { 2133 APInt ShiftedC = C.lshr(*ShiftAmt); 2134 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2135 } 2136 if (Pred == ICmpInst::ICMP_ULT) { 2137 // ULE is the same as above, but ULE is canonicalized to ULT, so convert: 2138 // (X << S) <=u C is equiv to X <=u (C >> S) for all C 2139 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u 2140 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0 2141 assert(C.ugt(0) && "ult 0 should have been eliminated"); 2142 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1; 2143 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2144 } 2145 } 2146 2147 if (Cmp.isEquality() && Shl->hasOneUse()) { 2148 // Strength-reduce the shift into an 'and'. 2149 Constant *Mask = ConstantInt::get( 2150 ShType, 2151 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue())); 2152 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask"); 2153 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt)); 2154 return new ICmpInst(Pred, And, LShrC); 2155 } 2156 2157 // Otherwise, if this is a comparison of the sign bit, simplify to and/test. 2158 bool TrueIfSigned = false; 2159 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) { 2160 // (X << 31) <s 0 --> (X & 1) != 0 2161 Constant *Mask = ConstantInt::get( 2162 ShType, 2163 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1)); 2164 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask"); 2165 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, 2166 And, Constant::getNullValue(ShType)); 2167 } 2168 2169 // Simplify 'shl' inequality test into 'and' equality test. 2170 if (Cmp.isUnsigned() && Shl->hasOneUse()) { 2171 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0 2172 if ((C + 1).isPowerOf2() && 2173 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) { 2174 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue())); 2175 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ 2176 : ICmpInst::ICMP_NE, 2177 And, Constant::getNullValue(ShType)); 2178 } 2179 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0 2180 if (C.isPowerOf2() && 2181 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) { 2182 Value *And = 2183 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue())); 2184 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ 2185 : ICmpInst::ICMP_NE, 2186 And, Constant::getNullValue(ShType)); 2187 } 2188 } 2189 2190 // Transform (icmp pred iM (shl iM %v, N), C) 2191 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N)) 2192 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N. 2193 // This enables us to get rid of the shift in favor of a trunc that may be 2194 // free on the target. It has the additional benefit of comparing to a 2195 // smaller constant that may be more target-friendly. 2196 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1); 2197 if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt && 2198 DL.isLegalInteger(TypeBits - Amt)) { 2199 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt); 2200 if (auto *ShVTy = dyn_cast<VectorType>(ShType)) 2201 TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount()); 2202 Constant *NewC = 2203 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt)); 2204 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC); 2205 } 2206 2207 return nullptr; 2208 } 2209 2210 /// Fold icmp ({al}shr X, Y), C. 2211 Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp, 2212 BinaryOperator *Shr, 2213 const APInt &C) { 2214 // An exact shr only shifts out zero bits, so: 2215 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0 2216 Value *X = Shr->getOperand(0); 2217 CmpInst::Predicate Pred = Cmp.getPredicate(); 2218 if (Cmp.isEquality() && Shr->isExact() && C.isZero()) 2219 return new ICmpInst(Pred, X, Cmp.getOperand(1)); 2220 2221 bool IsAShr = Shr->getOpcode() == Instruction::AShr; 2222 const APInt *ShiftValC; 2223 if (match(Shr->getOperand(0), m_APInt(ShiftValC))) { 2224 if (Cmp.isEquality()) 2225 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC); 2226 2227 // If the shifted constant is a power-of-2, test the shift amount directly: 2228 // (ShiftValC >> X) >u C --> X <u (LZ(C) - LZ(ShiftValC)) 2229 // TODO: Handle ult. 2230 if (!IsAShr && Pred == CmpInst::ICMP_UGT && ShiftValC->isPowerOf2()) { 2231 assert(ShiftValC->ugt(C) && "Expected simplify of compare"); 2232 unsigned CmpLZ = C.countLeadingZeros(); 2233 unsigned ShiftLZ = ShiftValC->countLeadingZeros(); 2234 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ); 2235 return new ICmpInst(ICmpInst::ICMP_ULT, Shr->User::getOperand(1), NewC); 2236 } 2237 } 2238 2239 const APInt *ShiftAmtC; 2240 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC))) 2241 return nullptr; 2242 2243 // Check that the shift amount is in range. If not, don't perform undefined 2244 // shifts. When the shift is visited it will be simplified. 2245 unsigned TypeBits = C.getBitWidth(); 2246 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits); 2247 if (ShAmtVal >= TypeBits || ShAmtVal == 0) 2248 return nullptr; 2249 2250 bool IsExact = Shr->isExact(); 2251 Type *ShrTy = Shr->getType(); 2252 // TODO: If we could guarantee that InstSimplify would handle all of the 2253 // constant-value-based preconditions in the folds below, then we could assert 2254 // those conditions rather than checking them. This is difficult because of 2255 // undef/poison (PR34838). 2256 if (IsAShr) { 2257 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) { 2258 // When ShAmtC can be shifted losslessly: 2259 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC) 2260 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC) 2261 APInt ShiftedC = C.shl(ShAmtVal); 2262 if (ShiftedC.ashr(ShAmtVal) == C) 2263 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2264 } 2265 if (Pred == CmpInst::ICMP_SGT) { 2266 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1 2267 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1; 2268 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() && 2269 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1)) 2270 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2271 } 2272 if (Pred == CmpInst::ICMP_UGT) { 2273 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1 2274 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd 2275 // clause accounts for that pattern. 2276 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1; 2277 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) || 2278 (C + 1).shl(ShAmtVal).isMinSignedValue()) 2279 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2280 } 2281 2282 // If the compare constant has significant bits above the lowest sign-bit, 2283 // then convert an unsigned cmp to a test of the sign-bit: 2284 // (ashr X, ShiftC) u> C --> X s< 0 2285 // (ashr X, ShiftC) u< C --> X s> -1 2286 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) { 2287 if (Pred == CmpInst::ICMP_UGT) { 2288 return new ICmpInst(CmpInst::ICMP_SLT, X, 2289 ConstantInt::getNullValue(ShrTy)); 2290 } 2291 if (Pred == CmpInst::ICMP_ULT) { 2292 return new ICmpInst(CmpInst::ICMP_SGT, X, 2293 ConstantInt::getAllOnesValue(ShrTy)); 2294 } 2295 } 2296 } else { 2297 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) { 2298 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC) 2299 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC) 2300 APInt ShiftedC = C.shl(ShAmtVal); 2301 if (ShiftedC.lshr(ShAmtVal) == C) 2302 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2303 } 2304 if (Pred == CmpInst::ICMP_UGT) { 2305 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1 2306 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1; 2307 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1)) 2308 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2309 } 2310 } 2311 2312 if (!Cmp.isEquality()) 2313 return nullptr; 2314 2315 // Handle equality comparisons of shift-by-constant. 2316 2317 // If the comparison constant changes with the shift, the comparison cannot 2318 // succeed (bits of the comparison constant cannot match the shifted value). 2319 // This should be known by InstSimplify and already be folded to true/false. 2320 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) || 2321 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) && 2322 "Expected icmp+shr simplify did not occur."); 2323 2324 // If the bits shifted out are known zero, compare the unshifted value: 2325 // (X & 4) >> 1 == 2 --> (X & 4) == 4. 2326 if (Shr->isExact()) 2327 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal)); 2328 2329 if (C.isZero()) { 2330 // == 0 is u< 1. 2331 if (Pred == CmpInst::ICMP_EQ) 2332 return new ICmpInst(CmpInst::ICMP_ULT, X, 2333 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal))); 2334 else 2335 return new ICmpInst(CmpInst::ICMP_UGT, X, 2336 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1)); 2337 } 2338 2339 if (Shr->hasOneUse()) { 2340 // Canonicalize the shift into an 'and': 2341 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt) 2342 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); 2343 Constant *Mask = ConstantInt::get(ShrTy, Val); 2344 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask"); 2345 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal)); 2346 } 2347 2348 return nullptr; 2349 } 2350 2351 Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp, 2352 BinaryOperator *SRem, 2353 const APInt &C) { 2354 // Match an 'is positive' or 'is negative' comparison of remainder by a 2355 // constant power-of-2 value: 2356 // (X % pow2C) sgt/slt 0 2357 const ICmpInst::Predicate Pred = Cmp.getPredicate(); 2358 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT && 2359 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 2360 return nullptr; 2361 2362 // TODO: The one-use check is standard because we do not typically want to 2363 // create longer instruction sequences, but this might be a special-case 2364 // because srem is not good for analysis or codegen. 2365 if (!SRem->hasOneUse()) 2366 return nullptr; 2367 2368 const APInt *DivisorC; 2369 if (!match(SRem->getOperand(1), m_Power2(DivisorC))) 2370 return nullptr; 2371 2372 // For cmp_sgt/cmp_slt only zero valued C is handled. 2373 // For cmp_eq/cmp_ne only positive valued C is handled. 2374 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) && 2375 !C.isZero()) || 2376 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) && 2377 !C.isStrictlyPositive())) 2378 return nullptr; 2379 2380 // Mask off the sign bit and the modulo bits (low-bits). 2381 Type *Ty = SRem->getType(); 2382 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits()); 2383 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1)); 2384 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC); 2385 2386 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) 2387 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C)); 2388 2389 // For 'is positive?' check that the sign-bit is clear and at least 1 masked 2390 // bit is set. Example: 2391 // (i8 X % 32) s> 0 --> (X & 159) s> 0 2392 if (Pred == ICmpInst::ICMP_SGT) 2393 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty)); 2394 2395 // For 'is negative?' check that the sign-bit is set and at least 1 masked 2396 // bit is set. Example: 2397 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768 2398 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask)); 2399 } 2400 2401 /// Fold icmp (udiv X, Y), C. 2402 Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp, 2403 BinaryOperator *UDiv, 2404 const APInt &C) { 2405 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2406 Value *X = UDiv->getOperand(0); 2407 Value *Y = UDiv->getOperand(1); 2408 Type *Ty = UDiv->getType(); 2409 2410 const APInt *C2; 2411 if (!match(X, m_APInt(C2))) 2412 return nullptr; 2413 2414 assert(*C2 != 0 && "udiv 0, X should have been simplified already."); 2415 2416 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1)) 2417 if (Pred == ICmpInst::ICMP_UGT) { 2418 assert(!C.isMaxValue() && 2419 "icmp ugt X, UINT_MAX should have been simplified already."); 2420 return new ICmpInst(ICmpInst::ICMP_ULE, Y, 2421 ConstantInt::get(Ty, C2->udiv(C + 1))); 2422 } 2423 2424 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C) 2425 if (Pred == ICmpInst::ICMP_ULT) { 2426 assert(C != 0 && "icmp ult X, 0 should have been simplified already."); 2427 return new ICmpInst(ICmpInst::ICMP_UGT, Y, 2428 ConstantInt::get(Ty, C2->udiv(C))); 2429 } 2430 2431 return nullptr; 2432 } 2433 2434 /// Fold icmp ({su}div X, Y), C. 2435 Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp, 2436 BinaryOperator *Div, 2437 const APInt &C) { 2438 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2439 Value *X = Div->getOperand(0); 2440 Value *Y = Div->getOperand(1); 2441 Type *Ty = Div->getType(); 2442 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv; 2443 2444 // If unsigned division and the compare constant is bigger than 2445 // UMAX/2 (negative), there's only one pair of values that satisfies an 2446 // equality check, so eliminate the division: 2447 // (X u/ Y) == C --> (X == C) && (Y == 1) 2448 // (X u/ Y) != C --> (X != C) || (Y != 1) 2449 // Similarly, if signed division and the compare constant is exactly SMIN: 2450 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1) 2451 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1) 2452 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() && 2453 (!DivIsSigned || C.isMinSignedValue())) { 2454 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C)); 2455 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1)); 2456 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 2457 return BinaryOperator::Create(Logic, XBig, YOne); 2458 } 2459 2460 // Fold: icmp pred ([us]div X, C2), C -> range test 2461 // Fold this div into the comparison, producing a range check. 2462 // Determine, based on the divide type, what the range is being 2463 // checked. If there is an overflow on the low or high side, remember 2464 // it, otherwise compute the range [low, hi) bounding the new value. 2465 // See: InsertRangeTest above for the kinds of replacements possible. 2466 const APInt *C2; 2467 if (!match(Y, m_APInt(C2))) 2468 return nullptr; 2469 2470 // FIXME: If the operand types don't match the type of the divide 2471 // then don't attempt this transform. The code below doesn't have the 2472 // logic to deal with a signed divide and an unsigned compare (and 2473 // vice versa). This is because (x /s C2) <s C produces different 2474 // results than (x /s C2) <u C or (x /u C2) <s C or even 2475 // (x /u C2) <u C. Simply casting the operands and result won't 2476 // work. :( The if statement below tests that condition and bails 2477 // if it finds it. 2478 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) 2479 return nullptr; 2480 2481 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with 2482 // INT_MIN will also fail if the divisor is 1. Although folds of all these 2483 // division-by-constant cases should be present, we can not assert that they 2484 // have happened before we reach this icmp instruction. 2485 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes())) 2486 return nullptr; 2487 2488 // Compute Prod = C * C2. We are essentially solving an equation of 2489 // form X / C2 = C. We solve for X by multiplying C2 and C. 2490 // By solving for X, we can turn this into a range check instead of computing 2491 // a divide. 2492 APInt Prod = C * *C2; 2493 2494 // Determine if the product overflows by seeing if the product is not equal to 2495 // the divide. Make sure we do the same kind of divide as in the LHS 2496 // instruction that we're folding. 2497 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C; 2498 2499 // If the division is known to be exact, then there is no remainder from the 2500 // divide, so the covered range size is unit, otherwise it is the divisor. 2501 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2; 2502 2503 // Figure out the interval that is being checked. For example, a comparison 2504 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 2505 // Compute this interval based on the constants involved and the signedness of 2506 // the compare/divide. This computes a half-open interval, keeping track of 2507 // whether either value in the interval overflows. After analysis each 2508 // overflow variable is set to 0 if it's corresponding bound variable is valid 2509 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. 2510 int LoOverflow = 0, HiOverflow = 0; 2511 APInt LoBound, HiBound; 2512 2513 if (!DivIsSigned) { // udiv 2514 // e.g. X/5 op 3 --> [15, 20) 2515 LoBound = Prod; 2516 HiOverflow = LoOverflow = ProdOV; 2517 if (!HiOverflow) { 2518 // If this is not an exact divide, then many values in the range collapse 2519 // to the same result value. 2520 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false); 2521 } 2522 } else if (C2->isStrictlyPositive()) { // Divisor is > 0. 2523 if (C.isZero()) { // (X / pos) op 0 2524 // Can't overflow. e.g. X/2 op 0 --> [-1, 2) 2525 LoBound = -(RangeSize - 1); 2526 HiBound = RangeSize; 2527 } else if (C.isStrictlyPositive()) { // (X / pos) op pos 2528 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) 2529 HiOverflow = LoOverflow = ProdOV; 2530 if (!HiOverflow) 2531 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true); 2532 } else { // (X / pos) op neg 2533 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) 2534 HiBound = Prod + 1; 2535 LoOverflow = HiOverflow = ProdOV ? -1 : 0; 2536 if (!LoOverflow) { 2537 APInt DivNeg = -RangeSize; 2538 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; 2539 } 2540 } 2541 } else if (C2->isNegative()) { // Divisor is < 0. 2542 if (Div->isExact()) 2543 RangeSize.negate(); 2544 if (C.isZero()) { // (X / neg) op 0 2545 // e.g. X/-5 op 0 --> [-4, 5) 2546 LoBound = RangeSize + 1; 2547 HiBound = -RangeSize; 2548 if (HiBound == *C2) { // -INTMIN = INTMIN 2549 HiOverflow = 1; // [INTMIN+1, overflow) 2550 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN 2551 } 2552 } else if (C.isStrictlyPositive()) { // (X / neg) op pos 2553 // e.g. X/-5 op 3 --> [-19, -14) 2554 HiBound = Prod + 1; 2555 HiOverflow = LoOverflow = ProdOV ? -1 : 0; 2556 if (!LoOverflow) 2557 LoOverflow = 2558 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0; 2559 } else { // (X / neg) op neg 2560 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) 2561 LoOverflow = HiOverflow = ProdOV; 2562 if (!HiOverflow) 2563 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true); 2564 } 2565 2566 // Dividing by a negative swaps the condition. LT <-> GT 2567 Pred = ICmpInst::getSwappedPredicate(Pred); 2568 } 2569 2570 switch (Pred) { 2571 default: 2572 llvm_unreachable("Unhandled icmp predicate!"); 2573 case ICmpInst::ICMP_EQ: 2574 if (LoOverflow && HiOverflow) 2575 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2576 if (HiOverflow) 2577 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, 2578 X, ConstantInt::get(Ty, LoBound)); 2579 if (LoOverflow) 2580 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 2581 X, ConstantInt::get(Ty, HiBound)); 2582 return replaceInstUsesWith( 2583 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true)); 2584 case ICmpInst::ICMP_NE: 2585 if (LoOverflow && HiOverflow) 2586 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2587 if (HiOverflow) 2588 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 2589 X, ConstantInt::get(Ty, LoBound)); 2590 if (LoOverflow) 2591 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, 2592 X, ConstantInt::get(Ty, HiBound)); 2593 return replaceInstUsesWith( 2594 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false)); 2595 case ICmpInst::ICMP_ULT: 2596 case ICmpInst::ICMP_SLT: 2597 if (LoOverflow == +1) // Low bound is greater than input range. 2598 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2599 if (LoOverflow == -1) // Low bound is less than input range. 2600 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2601 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound)); 2602 case ICmpInst::ICMP_UGT: 2603 case ICmpInst::ICMP_SGT: 2604 if (HiOverflow == +1) // High bound greater than input range. 2605 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2606 if (HiOverflow == -1) // High bound less than input range. 2607 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2608 if (Pred == ICmpInst::ICMP_UGT) 2609 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound)); 2610 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound)); 2611 } 2612 2613 return nullptr; 2614 } 2615 2616 /// Fold icmp (sub X, Y), C. 2617 Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp, 2618 BinaryOperator *Sub, 2619 const APInt &C) { 2620 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1); 2621 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2622 Type *Ty = Sub->getType(); 2623 2624 // (SubC - Y) == C) --> Y == (SubC - C) 2625 // (SubC - Y) != C) --> Y != (SubC - C) 2626 Constant *SubC; 2627 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) { 2628 return new ICmpInst(Pred, Y, 2629 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C))); 2630 } 2631 2632 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C) 2633 const APInt *C2; 2634 APInt SubResult; 2635 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate(); 2636 bool HasNSW = Sub->hasNoSignedWrap(); 2637 bool HasNUW = Sub->hasNoUnsignedWrap(); 2638 if (match(X, m_APInt(C2)) && 2639 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) && 2640 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned())) 2641 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult)); 2642 2643 // X - Y == 0 --> X == Y. 2644 // X - Y != 0 --> X != Y. 2645 // TODO: We allow this with multiple uses as long as the other uses are not 2646 // in phis. The phi use check is guarding against a codegen regression 2647 // for a loop test. If the backend could undo this (and possibly 2648 // subsequent transforms), we would not need this hack. 2649 if (Cmp.isEquality() && C.isZero() && 2650 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); })) 2651 return new ICmpInst(Pred, X, Y); 2652 2653 // The following transforms are only worth it if the only user of the subtract 2654 // is the icmp. 2655 // TODO: This is an artificial restriction for all of the transforms below 2656 // that only need a single replacement icmp. Can these use the phi test 2657 // like the transform above here? 2658 if (!Sub->hasOneUse()) 2659 return nullptr; 2660 2661 if (Sub->hasNoSignedWrap()) { 2662 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y) 2663 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes()) 2664 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 2665 2666 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y) 2667 if (Pred == ICmpInst::ICMP_SGT && C.isZero()) 2668 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 2669 2670 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y) 2671 if (Pred == ICmpInst::ICMP_SLT && C.isZero()) 2672 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 2673 2674 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y) 2675 if (Pred == ICmpInst::ICMP_SLT && C.isOne()) 2676 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 2677 } 2678 2679 if (!match(X, m_APInt(C2))) 2680 return nullptr; 2681 2682 // C2 - Y <u C -> (Y | (C - 1)) == C2 2683 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2 2684 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && 2685 (*C2 & (C - 1)) == (C - 1)) 2686 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X); 2687 2688 // C2 - Y >u C -> (Y | C) != C2 2689 // iff C2 & C == C and C + 1 is a power of 2 2690 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C) 2691 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X); 2692 2693 // We have handled special cases that reduce. 2694 // Canonicalize any remaining sub to add as: 2695 // (C2 - Y) > C --> (Y + ~C2) < ~C 2696 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub", 2697 HasNUW, HasNSW); 2698 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C)); 2699 } 2700 2701 /// Fold icmp (add X, Y), C. 2702 Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp, 2703 BinaryOperator *Add, 2704 const APInt &C) { 2705 Value *Y = Add->getOperand(1); 2706 const APInt *C2; 2707 if (Cmp.isEquality() || !match(Y, m_APInt(C2))) 2708 return nullptr; 2709 2710 // Fold icmp pred (add X, C2), C. 2711 Value *X = Add->getOperand(0); 2712 Type *Ty = Add->getType(); 2713 const CmpInst::Predicate Pred = Cmp.getPredicate(); 2714 2715 // If the add does not wrap, we can always adjust the compare by subtracting 2716 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE 2717 // are canonicalized to SGT/SLT/UGT/ULT. 2718 if ((Add->hasNoSignedWrap() && 2719 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) || 2720 (Add->hasNoUnsignedWrap() && 2721 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) { 2722 bool Overflow; 2723 APInt NewC = 2724 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow); 2725 // If there is overflow, the result must be true or false. 2726 // TODO: Can we assert there is no overflow because InstSimplify always 2727 // handles those cases? 2728 if (!Overflow) 2729 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2) 2730 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC)); 2731 } 2732 2733 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2); 2734 const APInt &Upper = CR.getUpper(); 2735 const APInt &Lower = CR.getLower(); 2736 if (Cmp.isSigned()) { 2737 if (Lower.isSignMask()) 2738 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper)); 2739 if (Upper.isSignMask()) 2740 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower)); 2741 } else { 2742 if (Lower.isMinValue()) 2743 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper)); 2744 if (Upper.isMinValue()) 2745 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower)); 2746 } 2747 2748 // This set of folds is intentionally placed after folds that use no-wrapping 2749 // flags because those folds are likely better for later analysis/codegen. 2750 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits()); 2751 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits()); 2752 2753 // Fold compare with offset to opposite sign compare if it eliminates offset: 2754 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX) 2755 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax) 2756 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2))); 2757 2758 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN) 2759 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin) 2760 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2))); 2761 2762 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1) 2763 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1) 2764 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C)); 2765 2766 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2) 2767 if (Pred == CmpInst::ICMP_SLT && C == *C2) 2768 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax)); 2769 2770 if (!Add->hasOneUse()) 2771 return nullptr; 2772 2773 // X+C <u C2 -> (X & -C2) == C 2774 // iff C & (C2-1) == 0 2775 // C2 is a power of 2 2776 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0) 2777 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C), 2778 ConstantExpr::getNeg(cast<Constant>(Y))); 2779 2780 // X+C >u C2 -> (X & ~C2) != C 2781 // iff C & C2 == 0 2782 // C2+1 is a power of 2 2783 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0) 2784 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C), 2785 ConstantExpr::getNeg(cast<Constant>(Y))); 2786 2787 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize 2788 // to the ult form. 2789 // X+C2 >u C -> X+(C2-C-1) <u ~C 2790 if (Pred == ICmpInst::ICMP_UGT) 2791 return new ICmpInst(ICmpInst::ICMP_ULT, 2792 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)), 2793 ConstantInt::get(Ty, ~C)); 2794 2795 return nullptr; 2796 } 2797 2798 bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, 2799 Value *&RHS, ConstantInt *&Less, 2800 ConstantInt *&Equal, 2801 ConstantInt *&Greater) { 2802 // TODO: Generalize this to work with other comparison idioms or ensure 2803 // they get canonicalized into this form. 2804 2805 // select i1 (a == b), 2806 // i32 Equal, 2807 // i32 (select i1 (a < b), i32 Less, i32 Greater) 2808 // where Equal, Less and Greater are placeholders for any three constants. 2809 ICmpInst::Predicate PredA; 2810 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) || 2811 !ICmpInst::isEquality(PredA)) 2812 return false; 2813 Value *EqualVal = SI->getTrueValue(); 2814 Value *UnequalVal = SI->getFalseValue(); 2815 // We still can get non-canonical predicate here, so canonicalize. 2816 if (PredA == ICmpInst::ICMP_NE) 2817 std::swap(EqualVal, UnequalVal); 2818 if (!match(EqualVal, m_ConstantInt(Equal))) 2819 return false; 2820 ICmpInst::Predicate PredB; 2821 Value *LHS2, *RHS2; 2822 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)), 2823 m_ConstantInt(Less), m_ConstantInt(Greater)))) 2824 return false; 2825 // We can get predicate mismatch here, so canonicalize if possible: 2826 // First, ensure that 'LHS' match. 2827 if (LHS2 != LHS) { 2828 // x sgt y <--> y slt x 2829 std::swap(LHS2, RHS2); 2830 PredB = ICmpInst::getSwappedPredicate(PredB); 2831 } 2832 if (LHS2 != LHS) 2833 return false; 2834 // We also need to canonicalize 'RHS'. 2835 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) { 2836 // x sgt C-1 <--> x sge C <--> not(x slt C) 2837 auto FlippedStrictness = 2838 InstCombiner::getFlippedStrictnessPredicateAndConstant( 2839 PredB, cast<Constant>(RHS2)); 2840 if (!FlippedStrictness) 2841 return false; 2842 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE && 2843 "basic correctness failure"); 2844 RHS2 = FlippedStrictness->second; 2845 // And kind-of perform the result swap. 2846 std::swap(Less, Greater); 2847 PredB = ICmpInst::ICMP_SLT; 2848 } 2849 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2; 2850 } 2851 2852 Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp, 2853 SelectInst *Select, 2854 ConstantInt *C) { 2855 2856 assert(C && "Cmp RHS should be a constant int!"); 2857 // If we're testing a constant value against the result of a three way 2858 // comparison, the result can be expressed directly in terms of the 2859 // original values being compared. Note: We could possibly be more 2860 // aggressive here and remove the hasOneUse test. The original select is 2861 // really likely to simplify or sink when we remove a test of the result. 2862 Value *OrigLHS, *OrigRHS; 2863 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan; 2864 if (Cmp.hasOneUse() && 2865 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal, 2866 C3GreaterThan)) { 2867 assert(C1LessThan && C2Equal && C3GreaterThan); 2868 2869 bool TrueWhenLessThan = 2870 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C) 2871 ->isAllOnesValue(); 2872 bool TrueWhenEqual = 2873 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C) 2874 ->isAllOnesValue(); 2875 bool TrueWhenGreaterThan = 2876 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C) 2877 ->isAllOnesValue(); 2878 2879 // This generates the new instruction that will replace the original Cmp 2880 // Instruction. Instead of enumerating the various combinations when 2881 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus 2882 // false, we rely on chaining of ORs and future passes of InstCombine to 2883 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b). 2884 2885 // When none of the three constants satisfy the predicate for the RHS (C), 2886 // the entire original Cmp can be simplified to a false. 2887 Value *Cond = Builder.getFalse(); 2888 if (TrueWhenLessThan) 2889 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, 2890 OrigLHS, OrigRHS)); 2891 if (TrueWhenEqual) 2892 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, 2893 OrigLHS, OrigRHS)); 2894 if (TrueWhenGreaterThan) 2895 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, 2896 OrigLHS, OrigRHS)); 2897 2898 return replaceInstUsesWith(Cmp, Cond); 2899 } 2900 return nullptr; 2901 } 2902 2903 Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) { 2904 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0)); 2905 if (!Bitcast) 2906 return nullptr; 2907 2908 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2909 Value *Op1 = Cmp.getOperand(1); 2910 Value *BCSrcOp = Bitcast->getOperand(0); 2911 Type *SrcType = Bitcast->getSrcTy(); 2912 Type *DstType = Bitcast->getType(); 2913 2914 // Make sure the bitcast doesn't change between scalar and vector and 2915 // doesn't change the number of vector elements. 2916 if (SrcType->isVectorTy() == DstType->isVectorTy() && 2917 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) { 2918 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast. 2919 Value *X; 2920 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) { 2921 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0 2922 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0 2923 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0 2924 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0 2925 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT || 2926 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) && 2927 match(Op1, m_Zero())) 2928 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType())); 2929 2930 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1 2931 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One())) 2932 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1)); 2933 2934 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1 2935 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes())) 2936 return new ICmpInst(Pred, X, 2937 ConstantInt::getAllOnesValue(X->getType())); 2938 } 2939 2940 // Zero-equality checks are preserved through unsigned floating-point casts: 2941 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0 2942 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0 2943 if (match(BCSrcOp, m_UIToFP(m_Value(X)))) 2944 if (Cmp.isEquality() && match(Op1, m_Zero())) 2945 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType())); 2946 2947 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate 2948 // the FP extend/truncate because that cast does not change the sign-bit. 2949 // This is true for all standard IEEE-754 types and the X86 80-bit type. 2950 // The sign-bit is always the most significant bit in those types. 2951 const APInt *C; 2952 bool TrueIfSigned; 2953 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() && 2954 InstCombiner::isSignBitCheck(Pred, *C, TrueIfSigned)) { 2955 if (match(BCSrcOp, m_FPExt(m_Value(X))) || 2956 match(BCSrcOp, m_FPTrunc(m_Value(X)))) { 2957 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0 2958 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1 2959 Type *XType = X->getType(); 2960 2961 // We can't currently handle Power style floating point operations here. 2962 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) { 2963 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits()); 2964 if (auto *XVTy = dyn_cast<VectorType>(XType)) 2965 NewType = VectorType::get(NewType, XVTy->getElementCount()); 2966 Value *NewBitcast = Builder.CreateBitCast(X, NewType); 2967 if (TrueIfSigned) 2968 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast, 2969 ConstantInt::getNullValue(NewType)); 2970 else 2971 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast, 2972 ConstantInt::getAllOnesValue(NewType)); 2973 } 2974 } 2975 } 2976 } 2977 2978 // Test to see if the operands of the icmp are casted versions of other 2979 // values. If the ptr->ptr cast can be stripped off both arguments, do so. 2980 if (DstType->isPointerTy() && (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 2981 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast 2982 // so eliminate it as well. 2983 if (auto *BC2 = dyn_cast<BitCastInst>(Op1)) 2984 Op1 = BC2->getOperand(0); 2985 2986 Op1 = Builder.CreateBitCast(Op1, SrcType); 2987 return new ICmpInst(Pred, BCSrcOp, Op1); 2988 } 2989 2990 const APInt *C; 2991 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() || 2992 !SrcType->isIntOrIntVectorTy()) 2993 return nullptr; 2994 2995 // If this is checking if all elements of a vector compare are set or not, 2996 // invert the casted vector equality compare and test if all compare 2997 // elements are clear or not. Compare against zero is generally easier for 2998 // analysis and codegen. 2999 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0 3000 // Example: are all elements equal? --> are zero elements not equal? 3001 // TODO: Try harder to reduce compare of 2 freely invertible operands? 3002 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse() && 3003 isFreeToInvert(BCSrcOp, BCSrcOp->hasOneUse())) { 3004 Value *Cast = Builder.CreateBitCast(Builder.CreateNot(BCSrcOp), DstType); 3005 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType)); 3006 } 3007 3008 // If this is checking if all elements of an extended vector are clear or not, 3009 // compare in a narrow type to eliminate the extend: 3010 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0 3011 Value *X; 3012 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() && 3013 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) { 3014 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) { 3015 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits()); 3016 Value *NewCast = Builder.CreateBitCast(X, NewType); 3017 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType)); 3018 } 3019 } 3020 3021 // Folding: icmp <pred> iN X, C 3022 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN 3023 // and C is a splat of a K-bit pattern 3024 // and SC is a constant vector = <C', C', C', ..., C'> 3025 // Into: 3026 // %E = extractelement <M x iK> %vec, i32 C' 3027 // icmp <pred> iK %E, trunc(C) 3028 Value *Vec; 3029 ArrayRef<int> Mask; 3030 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) { 3031 // Check whether every element of Mask is the same constant 3032 if (is_splat(Mask)) { 3033 auto *VecTy = cast<VectorType>(SrcType); 3034 auto *EltTy = cast<IntegerType>(VecTy->getElementType()); 3035 if (C->isSplat(EltTy->getBitWidth())) { 3036 // Fold the icmp based on the value of C 3037 // If C is M copies of an iK sized bit pattern, 3038 // then: 3039 // => %E = extractelement <N x iK> %vec, i32 Elem 3040 // icmp <pred> iK %SplatVal, <pattern> 3041 Value *Elem = Builder.getInt32(Mask[0]); 3042 Value *Extract = Builder.CreateExtractElement(Vec, Elem); 3043 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth())); 3044 return new ICmpInst(Pred, Extract, NewC); 3045 } 3046 } 3047 } 3048 return nullptr; 3049 } 3050 3051 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C 3052 /// where X is some kind of instruction. 3053 Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) { 3054 const APInt *C; 3055 3056 if (match(Cmp.getOperand(1), m_APInt(C))) { 3057 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0))) 3058 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C)) 3059 return I; 3060 3061 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0))) 3062 // For now, we only support constant integers while folding the 3063 // ICMP(SELECT)) pattern. We can extend this to support vector of integers 3064 // similar to the cases handled by binary ops above. 3065 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1))) 3066 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS)) 3067 return I; 3068 3069 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0))) 3070 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C)) 3071 return I; 3072 3073 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) 3074 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C)) 3075 return I; 3076 } 3077 3078 if (match(Cmp.getOperand(1), m_APIntAllowUndef(C))) 3079 return foldICmpInstWithConstantAllowUndef(Cmp, *C); 3080 3081 return nullptr; 3082 } 3083 3084 /// Fold an icmp equality instruction with binary operator LHS and constant RHS: 3085 /// icmp eq/ne BO, C. 3086 Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant( 3087 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) { 3088 // TODO: Some of these folds could work with arbitrary constants, but this 3089 // function is limited to scalar and vector splat constants. 3090 if (!Cmp.isEquality()) 3091 return nullptr; 3092 3093 ICmpInst::Predicate Pred = Cmp.getPredicate(); 3094 bool isICMP_NE = Pred == ICmpInst::ICMP_NE; 3095 Constant *RHS = cast<Constant>(Cmp.getOperand(1)); 3096 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); 3097 3098 switch (BO->getOpcode()) { 3099 case Instruction::SRem: 3100 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. 3101 if (C.isZero() && BO->hasOneUse()) { 3102 const APInt *BOC; 3103 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) { 3104 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName()); 3105 return new ICmpInst(Pred, NewRem, 3106 Constant::getNullValue(BO->getType())); 3107 } 3108 } 3109 break; 3110 case Instruction::Add: { 3111 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. 3112 if (Constant *BOC = dyn_cast<Constant>(BOp1)) { 3113 if (BO->hasOneUse()) 3114 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, BOC)); 3115 } else if (C.isZero()) { 3116 // Replace ((add A, B) != 0) with (A != -B) if A or B is 3117 // efficiently invertible, or if the add has just this one use. 3118 if (Value *NegVal = dyn_castNegVal(BOp1)) 3119 return new ICmpInst(Pred, BOp0, NegVal); 3120 if (Value *NegVal = dyn_castNegVal(BOp0)) 3121 return new ICmpInst(Pred, NegVal, BOp1); 3122 if (BO->hasOneUse()) { 3123 Value *Neg = Builder.CreateNeg(BOp1); 3124 Neg->takeName(BO); 3125 return new ICmpInst(Pred, BOp0, Neg); 3126 } 3127 } 3128 break; 3129 } 3130 case Instruction::Xor: 3131 if (BO->hasOneUse()) { 3132 if (Constant *BOC = dyn_cast<Constant>(BOp1)) { 3133 // For the xor case, we can xor two constants together, eliminating 3134 // the explicit xor. 3135 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC)); 3136 } else if (C.isZero()) { 3137 // Replace ((xor A, B) != 0) with (A != B) 3138 return new ICmpInst(Pred, BOp0, BOp1); 3139 } 3140 } 3141 break; 3142 case Instruction::Or: { 3143 const APInt *BOC; 3144 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) { 3145 // Comparing if all bits outside of a constant mask are set? 3146 // Replace (X | C) == -1 with (X & ~C) == ~C. 3147 // This removes the -1 constant. 3148 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1)); 3149 Value *And = Builder.CreateAnd(BOp0, NotBOC); 3150 return new ICmpInst(Pred, And, NotBOC); 3151 } 3152 break; 3153 } 3154 case Instruction::And: { 3155 const APInt *BOC; 3156 if (match(BOp1, m_APInt(BOC))) { 3157 // If we have ((X & C) == C), turn it into ((X & C) != 0). 3158 if (C == *BOC && C.isPowerOf2()) 3159 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, 3160 BO, Constant::getNullValue(RHS->getType())); 3161 } 3162 break; 3163 } 3164 case Instruction::UDiv: 3165 if (C.isZero()) { 3166 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A) 3167 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT; 3168 return new ICmpInst(NewPred, BOp1, BOp0); 3169 } 3170 break; 3171 default: 3172 break; 3173 } 3174 return nullptr; 3175 } 3176 3177 /// Fold an equality icmp with LLVM intrinsic and constant operand. 3178 Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant( 3179 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) { 3180 Type *Ty = II->getType(); 3181 unsigned BitWidth = C.getBitWidth(); 3182 const ICmpInst::Predicate Pred = Cmp.getPredicate(); 3183 3184 switch (II->getIntrinsicID()) { 3185 case Intrinsic::abs: 3186 // abs(A) == 0 -> A == 0 3187 // abs(A) == INT_MIN -> A == INT_MIN 3188 if (C.isZero() || C.isMinSignedValue()) 3189 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C)); 3190 break; 3191 3192 case Intrinsic::bswap: 3193 // bswap(A) == C -> A == bswap(C) 3194 return new ICmpInst(Pred, II->getArgOperand(0), 3195 ConstantInt::get(Ty, C.byteSwap())); 3196 3197 case Intrinsic::ctlz: 3198 case Intrinsic::cttz: { 3199 // ctz(A) == bitwidth(A) -> A == 0 and likewise for != 3200 if (C == BitWidth) 3201 return new ICmpInst(Pred, II->getArgOperand(0), 3202 ConstantInt::getNullValue(Ty)); 3203 3204 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set 3205 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits. 3206 // Limit to one use to ensure we don't increase instruction count. 3207 unsigned Num = C.getLimitedValue(BitWidth); 3208 if (Num != BitWidth && II->hasOneUse()) { 3209 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz; 3210 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1) 3211 : APInt::getHighBitsSet(BitWidth, Num + 1); 3212 APInt Mask2 = IsTrailing 3213 ? APInt::getOneBitSet(BitWidth, Num) 3214 : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1); 3215 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1), 3216 ConstantInt::get(Ty, Mask2)); 3217 } 3218 break; 3219 } 3220 3221 case Intrinsic::ctpop: { 3222 // popcount(A) == 0 -> A == 0 and likewise for != 3223 // popcount(A) == bitwidth(A) -> A == -1 and likewise for != 3224 bool IsZero = C.isZero(); 3225 if (IsZero || C == BitWidth) 3226 return new ICmpInst(Pred, II->getArgOperand(0), 3227 IsZero ? Constant::getNullValue(Ty) 3228 : Constant::getAllOnesValue(Ty)); 3229 3230 break; 3231 } 3232 3233 case Intrinsic::fshl: 3234 case Intrinsic::fshr: 3235 if (II->getArgOperand(0) == II->getArgOperand(1)) { 3236 const APInt *RotAmtC; 3237 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC) 3238 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC) 3239 if (match(II->getArgOperand(2), m_APInt(RotAmtC))) 3240 return new ICmpInst(Pred, II->getArgOperand(0), 3241 II->getIntrinsicID() == Intrinsic::fshl 3242 ? ConstantInt::get(Ty, C.rotr(*RotAmtC)) 3243 : ConstantInt::get(Ty, C.rotl(*RotAmtC))); 3244 } 3245 break; 3246 3247 case Intrinsic::uadd_sat: { 3248 // uadd.sat(a, b) == 0 -> (a | b) == 0 3249 if (C.isZero()) { 3250 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1)); 3251 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty)); 3252 } 3253 break; 3254 } 3255 3256 case Intrinsic::usub_sat: { 3257 // usub.sat(a, b) == 0 -> a <= b 3258 if (C.isZero()) { 3259 ICmpInst::Predicate NewPred = 3260 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT; 3261 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1)); 3262 } 3263 break; 3264 } 3265 default: 3266 break; 3267 } 3268 3269 return nullptr; 3270 } 3271 3272 /// Fold an icmp with LLVM intrinsics 3273 static Instruction *foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp) { 3274 assert(Cmp.isEquality()); 3275 3276 ICmpInst::Predicate Pred = Cmp.getPredicate(); 3277 Value *Op0 = Cmp.getOperand(0); 3278 Value *Op1 = Cmp.getOperand(1); 3279 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0); 3280 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1); 3281 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID()) 3282 return nullptr; 3283 3284 switch (IIOp0->getIntrinsicID()) { 3285 case Intrinsic::bswap: 3286 case Intrinsic::bitreverse: 3287 // If both operands are byte-swapped or bit-reversed, just compare the 3288 // original values. 3289 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0)); 3290 case Intrinsic::fshl: 3291 case Intrinsic::fshr: 3292 // If both operands are rotated by same amount, just compare the 3293 // original values. 3294 if (IIOp0->getOperand(0) != IIOp0->getOperand(1)) 3295 break; 3296 if (IIOp1->getOperand(0) != IIOp1->getOperand(1)) 3297 break; 3298 if (IIOp0->getOperand(2) != IIOp1->getOperand(2)) 3299 break; 3300 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0)); 3301 default: 3302 break; 3303 } 3304 3305 return nullptr; 3306 } 3307 3308 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C 3309 /// where X is some kind of instruction and C is AllowUndef. 3310 /// TODO: Move more folds which allow undef to this function. 3311 Instruction * 3312 InstCombinerImpl::foldICmpInstWithConstantAllowUndef(ICmpInst &Cmp, 3313 const APInt &C) { 3314 const ICmpInst::Predicate Pred = Cmp.getPredicate(); 3315 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) { 3316 switch (II->getIntrinsicID()) { 3317 default: 3318 break; 3319 case Intrinsic::fshl: 3320 case Intrinsic::fshr: 3321 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) { 3322 // (rot X, ?) == 0/-1 --> X == 0/-1 3323 if (C.isZero() || C.isAllOnes()) 3324 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1)); 3325 } 3326 break; 3327 } 3328 } 3329 3330 return nullptr; 3331 } 3332 3333 /// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C. 3334 Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp, 3335 BinaryOperator *BO, 3336 const APInt &C) { 3337 switch (BO->getOpcode()) { 3338 case Instruction::Xor: 3339 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C)) 3340 return I; 3341 break; 3342 case Instruction::And: 3343 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C)) 3344 return I; 3345 break; 3346 case Instruction::Or: 3347 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C)) 3348 return I; 3349 break; 3350 case Instruction::Mul: 3351 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C)) 3352 return I; 3353 break; 3354 case Instruction::Shl: 3355 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C)) 3356 return I; 3357 break; 3358 case Instruction::LShr: 3359 case Instruction::AShr: 3360 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C)) 3361 return I; 3362 break; 3363 case Instruction::SRem: 3364 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C)) 3365 return I; 3366 break; 3367 case Instruction::UDiv: 3368 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C)) 3369 return I; 3370 LLVM_FALLTHROUGH; 3371 case Instruction::SDiv: 3372 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C)) 3373 return I; 3374 break; 3375 case Instruction::Sub: 3376 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C)) 3377 return I; 3378 break; 3379 case Instruction::Add: 3380 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C)) 3381 return I; 3382 break; 3383 default: 3384 break; 3385 } 3386 3387 // TODO: These folds could be refactored to be part of the above calls. 3388 return foldICmpBinOpEqualityWithConstant(Cmp, BO, C); 3389 } 3390 3391 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C. 3392 Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp, 3393 IntrinsicInst *II, 3394 const APInt &C) { 3395 if (Cmp.isEquality()) 3396 return foldICmpEqIntrinsicWithConstant(Cmp, II, C); 3397 3398 Type *Ty = II->getType(); 3399 unsigned BitWidth = C.getBitWidth(); 3400 ICmpInst::Predicate Pred = Cmp.getPredicate(); 3401 switch (II->getIntrinsicID()) { 3402 case Intrinsic::ctpop: { 3403 // (ctpop X > BitWidth - 1) --> X == -1 3404 Value *X = II->getArgOperand(0); 3405 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT) 3406 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X, 3407 ConstantInt::getAllOnesValue(Ty)); 3408 // (ctpop X < BitWidth) --> X != -1 3409 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT) 3410 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X, 3411 ConstantInt::getAllOnesValue(Ty)); 3412 break; 3413 } 3414 case Intrinsic::ctlz: { 3415 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000 3416 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) { 3417 unsigned Num = C.getLimitedValue(); 3418 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1); 3419 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT, 3420 II->getArgOperand(0), ConstantInt::get(Ty, Limit)); 3421 } 3422 3423 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111 3424 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) { 3425 unsigned Num = C.getLimitedValue(); 3426 APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num); 3427 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT, 3428 II->getArgOperand(0), ConstantInt::get(Ty, Limit)); 3429 } 3430 break; 3431 } 3432 case Intrinsic::cttz: { 3433 // Limit to one use to ensure we don't increase instruction count. 3434 if (!II->hasOneUse()) 3435 return nullptr; 3436 3437 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0 3438 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) { 3439 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1); 3440 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, 3441 Builder.CreateAnd(II->getArgOperand(0), Mask), 3442 ConstantInt::getNullValue(Ty)); 3443 } 3444 3445 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0 3446 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) { 3447 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue()); 3448 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, 3449 Builder.CreateAnd(II->getArgOperand(0), Mask), 3450 ConstantInt::getNullValue(Ty)); 3451 } 3452 break; 3453 } 3454 default: 3455 break; 3456 } 3457 3458 return nullptr; 3459 } 3460 3461 /// Handle icmp with constant (but not simple integer constant) RHS. 3462 Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) { 3463 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3464 Constant *RHSC = dyn_cast<Constant>(Op1); 3465 Instruction *LHSI = dyn_cast<Instruction>(Op0); 3466 if (!RHSC || !LHSI) 3467 return nullptr; 3468 3469 switch (LHSI->getOpcode()) { 3470 case Instruction::GetElementPtr: 3471 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null 3472 if (RHSC->isNullValue() && 3473 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) 3474 return new ICmpInst( 3475 I.getPredicate(), LHSI->getOperand(0), 3476 Constant::getNullValue(LHSI->getOperand(0)->getType())); 3477 break; 3478 case Instruction::PHI: 3479 // Only fold icmp into the PHI if the phi and icmp are in the same 3480 // block. If in the same block, we're encouraging jump threading. If 3481 // not, we are just pessimizing the code by making an i1 phi. 3482 if (LHSI->getParent() == I.getParent()) 3483 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI))) 3484 return NV; 3485 break; 3486 case Instruction::IntToPtr: 3487 // icmp pred inttoptr(X), null -> icmp pred X, 0 3488 if (RHSC->isNullValue() && 3489 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType()) 3490 return new ICmpInst( 3491 I.getPredicate(), LHSI->getOperand(0), 3492 Constant::getNullValue(LHSI->getOperand(0)->getType())); 3493 break; 3494 3495 case Instruction::Load: 3496 // Try to optimize things like "A[i] > 4" to index computations. 3497 if (GetElementPtrInst *GEP = 3498 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) 3499 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 3500 if (Instruction *Res = 3501 foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I)) 3502 return Res; 3503 break; 3504 } 3505 3506 return nullptr; 3507 } 3508 3509 Instruction *InstCombinerImpl::foldSelectICmp(ICmpInst::Predicate Pred, 3510 SelectInst *SI, Value *RHS, 3511 const ICmpInst &I) { 3512 // Try to fold the comparison into the select arms, which will cause the 3513 // select to be converted into a logical and/or. 3514 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * { 3515 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ)) 3516 return Res; 3517 if (Optional<bool> Impl = isImpliedCondition(SI->getCondition(), Pred, Op, 3518 RHS, DL, SelectCondIsTrue)) 3519 return ConstantInt::get(I.getType(), *Impl); 3520 return nullptr; 3521 }; 3522 3523 ConstantInt *CI = nullptr; 3524 Value *Op1 = SimplifyOp(SI->getOperand(1), true); 3525 if (Op1) 3526 CI = dyn_cast<ConstantInt>(Op1); 3527 3528 Value *Op2 = SimplifyOp(SI->getOperand(2), false); 3529 if (Op2) 3530 CI = dyn_cast<ConstantInt>(Op2); 3531 3532 // We only want to perform this transformation if it will not lead to 3533 // additional code. This is true if either both sides of the select 3534 // fold to a constant (in which case the icmp is replaced with a select 3535 // which will usually simplify) or this is the only user of the 3536 // select (in which case we are trading a select+icmp for a simpler 3537 // select+icmp) or all uses of the select can be replaced based on 3538 // dominance information ("Global cases"). 3539 bool Transform = false; 3540 if (Op1 && Op2) 3541 Transform = true; 3542 else if (Op1 || Op2) { 3543 // Local case 3544 if (SI->hasOneUse()) 3545 Transform = true; 3546 // Global cases 3547 else if (CI && !CI->isZero()) 3548 // When Op1 is constant try replacing select with second operand. 3549 // Otherwise Op2 is constant and try replacing select with first 3550 // operand. 3551 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1); 3552 } 3553 if (Transform) { 3554 if (!Op1) 3555 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName()); 3556 if (!Op2) 3557 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName()); 3558 return SelectInst::Create(SI->getOperand(0), Op1, Op2); 3559 } 3560 3561 return nullptr; 3562 } 3563 3564 /// Some comparisons can be simplified. 3565 /// In this case, we are looking for comparisons that look like 3566 /// a check for a lossy truncation. 3567 /// Folds: 3568 /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask 3569 /// Where Mask is some pattern that produces all-ones in low bits: 3570 /// (-1 >> y) 3571 /// ((-1 << y) >> y) <- non-canonical, has extra uses 3572 /// ~(-1 << y) 3573 /// ((1 << y) + (-1)) <- non-canonical, has extra uses 3574 /// The Mask can be a constant, too. 3575 /// For some predicates, the operands are commutative. 3576 /// For others, x can only be on a specific side. 3577 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I, 3578 InstCombiner::BuilderTy &Builder) { 3579 ICmpInst::Predicate SrcPred; 3580 Value *X, *M, *Y; 3581 auto m_VariableMask = m_CombineOr( 3582 m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())), 3583 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())), 3584 m_CombineOr(m_LShr(m_AllOnes(), m_Value()), 3585 m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y)))); 3586 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask()); 3587 if (!match(&I, m_c_ICmp(SrcPred, 3588 m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)), 3589 m_Deferred(X)))) 3590 return nullptr; 3591 3592 ICmpInst::Predicate DstPred; 3593 switch (SrcPred) { 3594 case ICmpInst::Predicate::ICMP_EQ: 3595 // x & (-1 >> y) == x -> x u<= (-1 >> y) 3596 DstPred = ICmpInst::Predicate::ICMP_ULE; 3597 break; 3598 case ICmpInst::Predicate::ICMP_NE: 3599 // x & (-1 >> y) != x -> x u> (-1 >> y) 3600 DstPred = ICmpInst::Predicate::ICMP_UGT; 3601 break; 3602 case ICmpInst::Predicate::ICMP_ULT: 3603 // x & (-1 >> y) u< x -> x u> (-1 >> y) 3604 // x u> x & (-1 >> y) -> x u> (-1 >> y) 3605 DstPred = ICmpInst::Predicate::ICMP_UGT; 3606 break; 3607 case ICmpInst::Predicate::ICMP_UGE: 3608 // x & (-1 >> y) u>= x -> x u<= (-1 >> y) 3609 // x u<= x & (-1 >> y) -> x u<= (-1 >> y) 3610 DstPred = ICmpInst::Predicate::ICMP_ULE; 3611 break; 3612 case ICmpInst::Predicate::ICMP_SLT: 3613 // x & (-1 >> y) s< x -> x s> (-1 >> y) 3614 // x s> x & (-1 >> y) -> x s> (-1 >> y) 3615 if (!match(M, m_Constant())) // Can not do this fold with non-constant. 3616 return nullptr; 3617 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements. 3618 return nullptr; 3619 DstPred = ICmpInst::Predicate::ICMP_SGT; 3620 break; 3621 case ICmpInst::Predicate::ICMP_SGE: 3622 // x & (-1 >> y) s>= x -> x s<= (-1 >> y) 3623 // x s<= x & (-1 >> y) -> x s<= (-1 >> y) 3624 if (!match(M, m_Constant())) // Can not do this fold with non-constant. 3625 return nullptr; 3626 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements. 3627 return nullptr; 3628 DstPred = ICmpInst::Predicate::ICMP_SLE; 3629 break; 3630 case ICmpInst::Predicate::ICMP_SGT: 3631 case ICmpInst::Predicate::ICMP_SLE: 3632 return nullptr; 3633 case ICmpInst::Predicate::ICMP_UGT: 3634 case ICmpInst::Predicate::ICMP_ULE: 3635 llvm_unreachable("Instsimplify took care of commut. variant"); 3636 break; 3637 default: 3638 llvm_unreachable("All possible folds are handled."); 3639 } 3640 3641 // The mask value may be a vector constant that has undefined elements. But it 3642 // may not be safe to propagate those undefs into the new compare, so replace 3643 // those elements by copying an existing, defined, and safe scalar constant. 3644 Type *OpTy = M->getType(); 3645 auto *VecC = dyn_cast<Constant>(M); 3646 auto *OpVTy = dyn_cast<FixedVectorType>(OpTy); 3647 if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) { 3648 Constant *SafeReplacementConstant = nullptr; 3649 for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) { 3650 if (!isa<UndefValue>(VecC->getAggregateElement(i))) { 3651 SafeReplacementConstant = VecC->getAggregateElement(i); 3652 break; 3653 } 3654 } 3655 assert(SafeReplacementConstant && "Failed to find undef replacement"); 3656 M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant); 3657 } 3658 3659 return Builder.CreateICmp(DstPred, X, M); 3660 } 3661 3662 /// Some comparisons can be simplified. 3663 /// In this case, we are looking for comparisons that look like 3664 /// a check for a lossy signed truncation. 3665 /// Folds: (MaskedBits is a constant.) 3666 /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x 3667 /// Into: 3668 /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits) 3669 /// Where KeptBits = bitwidth(%x) - MaskedBits 3670 static Value * 3671 foldICmpWithTruncSignExtendedVal(ICmpInst &I, 3672 InstCombiner::BuilderTy &Builder) { 3673 ICmpInst::Predicate SrcPred; 3674 Value *X; 3675 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef. 3676 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use. 3677 if (!match(&I, m_c_ICmp(SrcPred, 3678 m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)), 3679 m_APInt(C1))), 3680 m_Deferred(X)))) 3681 return nullptr; 3682 3683 // Potential handling of non-splats: for each element: 3684 // * if both are undef, replace with constant 0. 3685 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0. 3686 // * if both are not undef, and are different, bailout. 3687 // * else, only one is undef, then pick the non-undef one. 3688 3689 // The shift amount must be equal. 3690 if (*C0 != *C1) 3691 return nullptr; 3692 const APInt &MaskedBits = *C0; 3693 assert(MaskedBits != 0 && "shift by zero should be folded away already."); 3694 3695 ICmpInst::Predicate DstPred; 3696 switch (SrcPred) { 3697 case ICmpInst::Predicate::ICMP_EQ: 3698 // ((%x << MaskedBits) a>> MaskedBits) == %x 3699 // => 3700 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits) 3701 DstPred = ICmpInst::Predicate::ICMP_ULT; 3702 break; 3703 case ICmpInst::Predicate::ICMP_NE: 3704 // ((%x << MaskedBits) a>> MaskedBits) != %x 3705 // => 3706 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits) 3707 DstPred = ICmpInst::Predicate::ICMP_UGE; 3708 break; 3709 // FIXME: are more folds possible? 3710 default: 3711 return nullptr; 3712 } 3713 3714 auto *XType = X->getType(); 3715 const unsigned XBitWidth = XType->getScalarSizeInBits(); 3716 const APInt BitWidth = APInt(XBitWidth, XBitWidth); 3717 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched"); 3718 3719 // KeptBits = bitwidth(%x) - MaskedBits 3720 const APInt KeptBits = BitWidth - MaskedBits; 3721 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable"); 3722 // ICmpCst = (1 << KeptBits) 3723 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits); 3724 assert(ICmpCst.isPowerOf2()); 3725 // AddCst = (1 << (KeptBits-1)) 3726 const APInt AddCst = ICmpCst.lshr(1); 3727 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2()); 3728 3729 // T0 = add %x, AddCst 3730 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst)); 3731 // T1 = T0 DstPred ICmpCst 3732 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst)); 3733 3734 return T1; 3735 } 3736 3737 // Given pattern: 3738 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0 3739 // we should move shifts to the same hand of 'and', i.e. rewrite as 3740 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x) 3741 // We are only interested in opposite logical shifts here. 3742 // One of the shifts can be truncated. 3743 // If we can, we want to end up creating 'lshr' shift. 3744 static Value * 3745 foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, 3746 InstCombiner::BuilderTy &Builder) { 3747 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) || 3748 !I.getOperand(0)->hasOneUse()) 3749 return nullptr; 3750 3751 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value()); 3752 3753 // Look for an 'and' of two logical shifts, one of which may be truncated. 3754 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case. 3755 Instruction *XShift, *MaybeTruncation, *YShift; 3756 if (!match( 3757 I.getOperand(0), 3758 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)), 3759 m_CombineAnd(m_TruncOrSelf(m_CombineAnd( 3760 m_AnyLogicalShift, m_Instruction(YShift))), 3761 m_Instruction(MaybeTruncation))))) 3762 return nullptr; 3763 3764 // We potentially looked past 'trunc', but only when matching YShift, 3765 // therefore YShift must have the widest type. 3766 Instruction *WidestShift = YShift; 3767 // Therefore XShift must have the shallowest type. 3768 // Or they both have identical types if there was no truncation. 3769 Instruction *NarrowestShift = XShift; 3770 3771 Type *WidestTy = WidestShift->getType(); 3772 Type *NarrowestTy = NarrowestShift->getType(); 3773 assert(NarrowestTy == I.getOperand(0)->getType() && 3774 "We did not look past any shifts while matching XShift though."); 3775 bool HadTrunc = WidestTy != I.getOperand(0)->getType(); 3776 3777 // If YShift is a 'lshr', swap the shifts around. 3778 if (match(YShift, m_LShr(m_Value(), m_Value()))) 3779 std::swap(XShift, YShift); 3780 3781 // The shifts must be in opposite directions. 3782 auto XShiftOpcode = XShift->getOpcode(); 3783 if (XShiftOpcode == YShift->getOpcode()) 3784 return nullptr; // Do not care about same-direction shifts here. 3785 3786 Value *X, *XShAmt, *Y, *YShAmt; 3787 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt)))); 3788 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt)))); 3789 3790 // If one of the values being shifted is a constant, then we will end with 3791 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not, 3792 // however, we will need to ensure that we won't increase instruction count. 3793 if (!isa<Constant>(X) && !isa<Constant>(Y)) { 3794 // At least one of the hands of the 'and' should be one-use shift. 3795 if (!match(I.getOperand(0), 3796 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value()))) 3797 return nullptr; 3798 if (HadTrunc) { 3799 // Due to the 'trunc', we will need to widen X. For that either the old 3800 // 'trunc' or the shift amt in the non-truncated shift should be one-use. 3801 if (!MaybeTruncation->hasOneUse() && 3802 !NarrowestShift->getOperand(1)->hasOneUse()) 3803 return nullptr; 3804 } 3805 } 3806 3807 // We have two shift amounts from two different shifts. The types of those 3808 // shift amounts may not match. If that's the case let's bailout now. 3809 if (XShAmt->getType() != YShAmt->getType()) 3810 return nullptr; 3811 3812 // As input, we have the following pattern: 3813 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0 3814 // We want to rewrite that as: 3815 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x) 3816 // While we know that originally (Q+K) would not overflow 3817 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of 3818 // shift amounts. so it may now overflow in smaller bitwidth. 3819 // To ensure that does not happen, we need to ensure that the total maximal 3820 // shift amount is still representable in that smaller bit width. 3821 unsigned MaximalPossibleTotalShiftAmount = 3822 (WidestTy->getScalarSizeInBits() - 1) + 3823 (NarrowestTy->getScalarSizeInBits() - 1); 3824 APInt MaximalRepresentableShiftAmount = 3825 APInt::getAllOnes(XShAmt->getType()->getScalarSizeInBits()); 3826 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount)) 3827 return nullptr; 3828 3829 // Can we fold (XShAmt+YShAmt) ? 3830 auto *NewShAmt = dyn_cast_or_null<Constant>( 3831 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false, 3832 /*isNUW=*/false, SQ.getWithInstruction(&I))); 3833 if (!NewShAmt) 3834 return nullptr; 3835 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy); 3836 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits(); 3837 3838 // Is the new shift amount smaller than the bit width? 3839 // FIXME: could also rely on ConstantRange. 3840 if (!match(NewShAmt, 3841 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT, 3842 APInt(WidestBitWidth, WidestBitWidth)))) 3843 return nullptr; 3844 3845 // An extra legality check is needed if we had trunc-of-lshr. 3846 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) { 3847 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ, 3848 WidestShift]() { 3849 // It isn't obvious whether it's worth it to analyze non-constants here. 3850 // Also, let's basically give up on non-splat cases, pessimizing vectors. 3851 // If *any* of these preconditions matches we can perform the fold. 3852 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy() 3853 ? NewShAmt->getSplatValue() 3854 : NewShAmt; 3855 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold. 3856 if (NewShAmtSplat && 3857 (NewShAmtSplat->isNullValue() || 3858 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1)) 3859 return true; 3860 // We consider *min* leading zeros so a single outlier 3861 // blocks the transform as opposed to allowing it. 3862 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) { 3863 KnownBits Known = computeKnownBits(C, SQ.DL); 3864 unsigned MinLeadZero = Known.countMinLeadingZeros(); 3865 // If the value being shifted has at most lowest bit set we can fold. 3866 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero; 3867 if (MaxActiveBits <= 1) 3868 return true; 3869 // Precondition: NewShAmt u<= countLeadingZeros(C) 3870 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero)) 3871 return true; 3872 } 3873 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) { 3874 KnownBits Known = computeKnownBits(C, SQ.DL); 3875 unsigned MinLeadZero = Known.countMinLeadingZeros(); 3876 // If the value being shifted has at most lowest bit set we can fold. 3877 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero; 3878 if (MaxActiveBits <= 1) 3879 return true; 3880 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C) 3881 if (NewShAmtSplat) { 3882 APInt AdjNewShAmt = 3883 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger(); 3884 if (AdjNewShAmt.ule(MinLeadZero)) 3885 return true; 3886 } 3887 } 3888 return false; // Can't tell if it's ok. 3889 }; 3890 if (!CanFold()) 3891 return nullptr; 3892 } 3893 3894 // All good, we can do this fold. 3895 X = Builder.CreateZExt(X, WidestTy); 3896 Y = Builder.CreateZExt(Y, WidestTy); 3897 // The shift is the same that was for X. 3898 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr 3899 ? Builder.CreateLShr(X, NewShAmt) 3900 : Builder.CreateShl(X, NewShAmt); 3901 Value *T1 = Builder.CreateAnd(T0, Y); 3902 return Builder.CreateICmp(I.getPredicate(), T1, 3903 Constant::getNullValue(WidestTy)); 3904 } 3905 3906 /// Fold 3907 /// (-1 u/ x) u< y 3908 /// ((x * y) ?/ x) != y 3909 /// to 3910 /// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit 3911 /// Note that the comparison is commutative, while inverted (u>=, ==) predicate 3912 /// will mean that we are looking for the opposite answer. 3913 Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) { 3914 ICmpInst::Predicate Pred; 3915 Value *X, *Y; 3916 Instruction *Mul; 3917 Instruction *Div; 3918 bool NeedNegation; 3919 // Look for: (-1 u/ x) u</u>= y 3920 if (!I.isEquality() && 3921 match(&I, m_c_ICmp(Pred, 3922 m_CombineAnd(m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))), 3923 m_Instruction(Div)), 3924 m_Value(Y)))) { 3925 Mul = nullptr; 3926 3927 // Are we checking that overflow does not happen, or does happen? 3928 switch (Pred) { 3929 case ICmpInst::Predicate::ICMP_ULT: 3930 NeedNegation = false; 3931 break; // OK 3932 case ICmpInst::Predicate::ICMP_UGE: 3933 NeedNegation = true; 3934 break; // OK 3935 default: 3936 return nullptr; // Wrong predicate. 3937 } 3938 } else // Look for: ((x * y) / x) !=/== y 3939 if (I.isEquality() && 3940 match(&I, 3941 m_c_ICmp(Pred, m_Value(Y), 3942 m_CombineAnd( 3943 m_OneUse(m_IDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y), 3944 m_Value(X)), 3945 m_Instruction(Mul)), 3946 m_Deferred(X))), 3947 m_Instruction(Div))))) { 3948 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ; 3949 } else 3950 return nullptr; 3951 3952 BuilderTy::InsertPointGuard Guard(Builder); 3953 // If the pattern included (x * y), we'll want to insert new instructions 3954 // right before that original multiplication so that we can replace it. 3955 bool MulHadOtherUses = Mul && !Mul->hasOneUse(); 3956 if (MulHadOtherUses) 3957 Builder.SetInsertPoint(Mul); 3958 3959 Function *F = Intrinsic::getDeclaration(I.getModule(), 3960 Div->getOpcode() == Instruction::UDiv 3961 ? Intrinsic::umul_with_overflow 3962 : Intrinsic::smul_with_overflow, 3963 X->getType()); 3964 CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul"); 3965 3966 // If the multiplication was used elsewhere, to ensure that we don't leave 3967 // "duplicate" instructions, replace uses of that original multiplication 3968 // with the multiplication result from the with.overflow intrinsic. 3969 if (MulHadOtherUses) 3970 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val")); 3971 3972 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov"); 3973 if (NeedNegation) // This technically increases instruction count. 3974 Res = Builder.CreateNot(Res, "mul.not.ov"); 3975 3976 // If we replaced the mul, erase it. Do this after all uses of Builder, 3977 // as the mul is used as insertion point. 3978 if (MulHadOtherUses) 3979 eraseInstFromFunction(*Mul); 3980 3981 return Res; 3982 } 3983 3984 static Instruction *foldICmpXNegX(ICmpInst &I) { 3985 CmpInst::Predicate Pred; 3986 Value *X; 3987 if (!match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) 3988 return nullptr; 3989 3990 if (ICmpInst::isSigned(Pred)) 3991 Pred = ICmpInst::getSwappedPredicate(Pred); 3992 else if (ICmpInst::isUnsigned(Pred)) 3993 Pred = ICmpInst::getSignedPredicate(Pred); 3994 // else for equality-comparisons just keep the predicate. 3995 3996 return ICmpInst::Create(Instruction::ICmp, Pred, X, 3997 Constant::getNullValue(X->getType()), I.getName()); 3998 } 3999 4000 /// Try to fold icmp (binop), X or icmp X, (binop). 4001 /// TODO: A large part of this logic is duplicated in InstSimplify's 4002 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code 4003 /// duplication. 4004 Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I, 4005 const SimplifyQuery &SQ) { 4006 const SimplifyQuery Q = SQ.getWithInstruction(&I); 4007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4008 4009 // Special logic for binary operators. 4010 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0); 4011 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1); 4012 if (!BO0 && !BO1) 4013 return nullptr; 4014 4015 if (Instruction *NewICmp = foldICmpXNegX(I)) 4016 return NewICmp; 4017 4018 const CmpInst::Predicate Pred = I.getPredicate(); 4019 Value *X; 4020 4021 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare. 4022 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X 4023 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) && 4024 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) 4025 return new ICmpInst(Pred, Builder.CreateNot(Op1), X); 4026 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0 4027 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) && 4028 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) 4029 return new ICmpInst(Pred, X, Builder.CreateNot(Op0)); 4030 4031 { 4032 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1 4033 Constant *C; 4034 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)), 4035 m_ImmConstant(C)))) && 4036 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) { 4037 Constant *C2 = ConstantExpr::getNot(C); 4038 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1); 4039 } 4040 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X 4041 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)), 4042 m_ImmConstant(C)))) && 4043 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) { 4044 Constant *C2 = ConstantExpr::getNot(C); 4045 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X)); 4046 } 4047 } 4048 4049 { 4050 // Similar to above: an unsigned overflow comparison may use offset + mask: 4051 // ((Op1 + C) & C) u< Op1 --> Op1 != 0 4052 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0 4053 // Op0 u> ((Op0 + C) & C) --> Op0 != 0 4054 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0 4055 BinaryOperator *BO; 4056 const APInt *C; 4057 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) && 4058 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) && 4059 match(BO, m_Add(m_Specific(Op1), m_SpecificIntAllowUndef(*C)))) { 4060 CmpInst::Predicate NewPred = 4061 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ; 4062 Constant *Zero = ConstantInt::getNullValue(Op1->getType()); 4063 return new ICmpInst(NewPred, Op1, Zero); 4064 } 4065 4066 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) && 4067 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) && 4068 match(BO, m_Add(m_Specific(Op0), m_SpecificIntAllowUndef(*C)))) { 4069 CmpInst::Predicate NewPred = 4070 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ; 4071 Constant *Zero = ConstantInt::getNullValue(Op1->getType()); 4072 return new ICmpInst(NewPred, Op0, Zero); 4073 } 4074 } 4075 4076 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false; 4077 if (BO0 && isa<OverflowingBinaryOperator>(BO0)) 4078 NoOp0WrapProblem = 4079 ICmpInst::isEquality(Pred) || 4080 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) || 4081 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap()); 4082 if (BO1 && isa<OverflowingBinaryOperator>(BO1)) 4083 NoOp1WrapProblem = 4084 ICmpInst::isEquality(Pred) || 4085 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) || 4086 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap()); 4087 4088 // Analyze the case when either Op0 or Op1 is an add instruction. 4089 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null). 4090 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 4091 if (BO0 && BO0->getOpcode() == Instruction::Add) { 4092 A = BO0->getOperand(0); 4093 B = BO0->getOperand(1); 4094 } 4095 if (BO1 && BO1->getOpcode() == Instruction::Add) { 4096 C = BO1->getOperand(0); 4097 D = BO1->getOperand(1); 4098 } 4099 4100 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow. 4101 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow. 4102 if ((A == Op1 || B == Op1) && NoOp0WrapProblem) 4103 return new ICmpInst(Pred, A == Op1 ? B : A, 4104 Constant::getNullValue(Op1->getType())); 4105 4106 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow. 4107 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow. 4108 if ((C == Op0 || D == Op0) && NoOp1WrapProblem) 4109 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()), 4110 C == Op0 ? D : C); 4111 4112 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow. 4113 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem && 4114 NoOp1WrapProblem) { 4115 // Determine Y and Z in the form icmp (X+Y), (X+Z). 4116 Value *Y, *Z; 4117 if (A == C) { 4118 // C + B == C + D -> B == D 4119 Y = B; 4120 Z = D; 4121 } else if (A == D) { 4122 // D + B == C + D -> B == C 4123 Y = B; 4124 Z = C; 4125 } else if (B == C) { 4126 // A + C == C + D -> A == D 4127 Y = A; 4128 Z = D; 4129 } else { 4130 assert(B == D); 4131 // A + D == C + D -> A == C 4132 Y = A; 4133 Z = C; 4134 } 4135 return new ICmpInst(Pred, Y, Z); 4136 } 4137 4138 // icmp slt (A + -1), Op1 -> icmp sle A, Op1 4139 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT && 4140 match(B, m_AllOnes())) 4141 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1); 4142 4143 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1 4144 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE && 4145 match(B, m_AllOnes())) 4146 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1); 4147 4148 // icmp sle (A + 1), Op1 -> icmp slt A, Op1 4149 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One())) 4150 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1); 4151 4152 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1 4153 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One())) 4154 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1); 4155 4156 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C 4157 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT && 4158 match(D, m_AllOnes())) 4159 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C); 4160 4161 // icmp sle Op0, (C + -1) -> icmp slt Op0, C 4162 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE && 4163 match(D, m_AllOnes())) 4164 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C); 4165 4166 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C 4167 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One())) 4168 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C); 4169 4170 // icmp slt Op0, (C + 1) -> icmp sle Op0, C 4171 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One())) 4172 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C); 4173 4174 // TODO: The subtraction-related identities shown below also hold, but 4175 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations 4176 // wouldn't happen even if they were implemented. 4177 // 4178 // icmp ult (A - 1), Op1 -> icmp ule A, Op1 4179 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1 4180 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C 4181 // icmp ule Op0, (C - 1) -> icmp ult Op0, C 4182 4183 // icmp ule (A + 1), Op0 -> icmp ult A, Op1 4184 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One())) 4185 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1); 4186 4187 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1 4188 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One())) 4189 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1); 4190 4191 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C 4192 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One())) 4193 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C); 4194 4195 // icmp ult Op0, (C + 1) -> icmp ule Op0, C 4196 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One())) 4197 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C); 4198 4199 // if C1 has greater magnitude than C2: 4200 // icmp (A + C1), (C + C2) -> icmp (A + C3), C 4201 // s.t. C3 = C1 - C2 4202 // 4203 // if C2 has greater magnitude than C1: 4204 // icmp (A + C1), (C + C2) -> icmp A, (C + C3) 4205 // s.t. C3 = C2 - C1 4206 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem && 4207 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) { 4208 const APInt *AP1, *AP2; 4209 // TODO: Support non-uniform vectors. 4210 // TODO: Allow undef passthrough if B AND D's element is undef. 4211 if (match(B, m_APIntAllowUndef(AP1)) && match(D, m_APIntAllowUndef(AP2)) && 4212 AP1->isNegative() == AP2->isNegative()) { 4213 APInt AP1Abs = AP1->abs(); 4214 APInt AP2Abs = AP2->abs(); 4215 if (AP1Abs.uge(AP2Abs)) { 4216 APInt Diff = *AP1 - *AP2; 4217 bool HasNUW = BO0->hasNoUnsignedWrap() && Diff.ule(*AP1); 4218 bool HasNSW = BO0->hasNoSignedWrap(); 4219 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff); 4220 Value *NewAdd = Builder.CreateAdd(A, C3, "", HasNUW, HasNSW); 4221 return new ICmpInst(Pred, NewAdd, C); 4222 } else { 4223 APInt Diff = *AP2 - *AP1; 4224 bool HasNUW = BO1->hasNoUnsignedWrap() && Diff.ule(*AP2); 4225 bool HasNSW = BO1->hasNoSignedWrap(); 4226 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff); 4227 Value *NewAdd = Builder.CreateAdd(C, C3, "", HasNUW, HasNSW); 4228 return new ICmpInst(Pred, A, NewAdd); 4229 } 4230 } 4231 Constant *Cst1, *Cst2; 4232 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) && 4233 ICmpInst::isEquality(Pred)) { 4234 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1); 4235 Value *NewAdd = Builder.CreateAdd(C, Diff); 4236 return new ICmpInst(Pred, A, NewAdd); 4237 } 4238 } 4239 4240 // Analyze the case when either Op0 or Op1 is a sub instruction. 4241 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null). 4242 A = nullptr; 4243 B = nullptr; 4244 C = nullptr; 4245 D = nullptr; 4246 if (BO0 && BO0->getOpcode() == Instruction::Sub) { 4247 A = BO0->getOperand(0); 4248 B = BO0->getOperand(1); 4249 } 4250 if (BO1 && BO1->getOpcode() == Instruction::Sub) { 4251 C = BO1->getOperand(0); 4252 D = BO1->getOperand(1); 4253 } 4254 4255 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow. 4256 if (A == Op1 && NoOp0WrapProblem) 4257 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B); 4258 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow. 4259 if (C == Op0 && NoOp1WrapProblem) 4260 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType())); 4261 4262 // Convert sub-with-unsigned-overflow comparisons into a comparison of args. 4263 // (A - B) u>/u<= A --> B u>/u<= A 4264 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) 4265 return new ICmpInst(Pred, B, A); 4266 // C u</u>= (C - D) --> C u</u>= D 4267 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) 4268 return new ICmpInst(Pred, C, D); 4269 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0 4270 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) && 4271 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 4272 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A); 4273 // C u<=/u> (C - D) --> C u</u>= D iff B != 0 4274 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) && 4275 isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 4276 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D); 4277 4278 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow. 4279 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem) 4280 return new ICmpInst(Pred, A, C); 4281 4282 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow. 4283 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem) 4284 return new ICmpInst(Pred, D, B); 4285 4286 // icmp (0-X) < cst --> x > -cst 4287 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) { 4288 Value *X; 4289 if (match(BO0, m_Neg(m_Value(X)))) 4290 if (Constant *RHSC = dyn_cast<Constant>(Op1)) 4291 if (RHSC->isNotMinSignedValue()) 4292 return new ICmpInst(I.getSwappedPredicate(), X, 4293 ConstantExpr::getNeg(RHSC)); 4294 } 4295 4296 { 4297 // Try to remove shared constant multiplier from equality comparison: 4298 // X * C == Y * C (with no overflowing/aliasing) --> X == Y 4299 Value *X, *Y; 4300 const APInt *C; 4301 if (match(Op0, m_Mul(m_Value(X), m_APInt(C))) && *C != 0 && 4302 match(Op1, m_Mul(m_Value(Y), m_SpecificInt(*C))) && I.isEquality()) 4303 if (!C->countTrailingZeros() || 4304 (BO0 && BO1 && BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap()) || 4305 (BO0 && BO1 && BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap())) 4306 return new ICmpInst(Pred, X, Y); 4307 } 4308 4309 BinaryOperator *SRem = nullptr; 4310 // icmp (srem X, Y), Y 4311 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1)) 4312 SRem = BO0; 4313 // icmp Y, (srem X, Y) 4314 else if (BO1 && BO1->getOpcode() == Instruction::SRem && 4315 Op0 == BO1->getOperand(1)) 4316 SRem = BO1; 4317 if (SRem) { 4318 // We don't check hasOneUse to avoid increasing register pressure because 4319 // the value we use is the same value this instruction was already using. 4320 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) { 4321 default: 4322 break; 4323 case ICmpInst::ICMP_EQ: 4324 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4325 case ICmpInst::ICMP_NE: 4326 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4327 case ICmpInst::ICMP_SGT: 4328 case ICmpInst::ICMP_SGE: 4329 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1), 4330 Constant::getAllOnesValue(SRem->getType())); 4331 case ICmpInst::ICMP_SLT: 4332 case ICmpInst::ICMP_SLE: 4333 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1), 4334 Constant::getNullValue(SRem->getType())); 4335 } 4336 } 4337 4338 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() && 4339 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) { 4340 switch (BO0->getOpcode()) { 4341 default: 4342 break; 4343 case Instruction::Add: 4344 case Instruction::Sub: 4345 case Instruction::Xor: { 4346 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b 4347 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4348 4349 const APInt *C; 4350 if (match(BO0->getOperand(1), m_APInt(C))) { 4351 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b 4352 if (C->isSignMask()) { 4353 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate(); 4354 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); 4355 } 4356 4357 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b 4358 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) { 4359 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate(); 4360 NewPred = I.getSwappedPredicate(NewPred); 4361 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); 4362 } 4363 } 4364 break; 4365 } 4366 case Instruction::Mul: { 4367 if (!I.isEquality()) 4368 break; 4369 4370 const APInt *C; 4371 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() && 4372 !C->isOne()) { 4373 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask) 4374 // Mask = -1 >> count-trailing-zeros(C). 4375 if (unsigned TZs = C->countTrailingZeros()) { 4376 Constant *Mask = ConstantInt::get( 4377 BO0->getType(), 4378 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs)); 4379 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask); 4380 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask); 4381 return new ICmpInst(Pred, And1, And2); 4382 } 4383 } 4384 break; 4385 } 4386 case Instruction::UDiv: 4387 case Instruction::LShr: 4388 if (I.isSigned() || !BO0->isExact() || !BO1->isExact()) 4389 break; 4390 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4391 4392 case Instruction::SDiv: 4393 if (!I.isEquality() || !BO0->isExact() || !BO1->isExact()) 4394 break; 4395 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4396 4397 case Instruction::AShr: 4398 if (!BO0->isExact() || !BO1->isExact()) 4399 break; 4400 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4401 4402 case Instruction::Shl: { 4403 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap(); 4404 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap(); 4405 if (!NUW && !NSW) 4406 break; 4407 if (!NSW && I.isSigned()) 4408 break; 4409 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4410 } 4411 } 4412 } 4413 4414 if (BO0) { 4415 // Transform A & (L - 1) `ult` L --> L != 0 4416 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes()); 4417 auto BitwiseAnd = m_c_And(m_Value(), LSubOne); 4418 4419 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) { 4420 auto *Zero = Constant::getNullValue(BO0->getType()); 4421 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero); 4422 } 4423 } 4424 4425 if (Value *V = foldMultiplicationOverflowCheck(I)) 4426 return replaceInstUsesWith(I, V); 4427 4428 if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder)) 4429 return replaceInstUsesWith(I, V); 4430 4431 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder)) 4432 return replaceInstUsesWith(I, V); 4433 4434 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder)) 4435 return replaceInstUsesWith(I, V); 4436 4437 return nullptr; 4438 } 4439 4440 /// Fold icmp Pred min|max(X, Y), X. 4441 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) { 4442 ICmpInst::Predicate Pred = Cmp.getPredicate(); 4443 Value *Op0 = Cmp.getOperand(0); 4444 Value *X = Cmp.getOperand(1); 4445 4446 // Canonicalize minimum or maximum operand to LHS of the icmp. 4447 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) || 4448 match(X, m_c_SMax(m_Specific(Op0), m_Value())) || 4449 match(X, m_c_UMin(m_Specific(Op0), m_Value())) || 4450 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) { 4451 std::swap(Op0, X); 4452 Pred = Cmp.getSwappedPredicate(); 4453 } 4454 4455 Value *Y; 4456 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) { 4457 // smin(X, Y) == X --> X s<= Y 4458 // smin(X, Y) s>= X --> X s<= Y 4459 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE) 4460 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 4461 4462 // smin(X, Y) != X --> X s> Y 4463 // smin(X, Y) s< X --> X s> Y 4464 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT) 4465 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 4466 4467 // These cases should be handled in InstSimplify: 4468 // smin(X, Y) s<= X --> true 4469 // smin(X, Y) s> X --> false 4470 return nullptr; 4471 } 4472 4473 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) { 4474 // smax(X, Y) == X --> X s>= Y 4475 // smax(X, Y) s<= X --> X s>= Y 4476 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE) 4477 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 4478 4479 // smax(X, Y) != X --> X s< Y 4480 // smax(X, Y) s> X --> X s< Y 4481 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT) 4482 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 4483 4484 // These cases should be handled in InstSimplify: 4485 // smax(X, Y) s>= X --> true 4486 // smax(X, Y) s< X --> false 4487 return nullptr; 4488 } 4489 4490 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) { 4491 // umin(X, Y) == X --> X u<= Y 4492 // umin(X, Y) u>= X --> X u<= Y 4493 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE) 4494 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y); 4495 4496 // umin(X, Y) != X --> X u> Y 4497 // umin(X, Y) u< X --> X u> Y 4498 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT) 4499 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); 4500 4501 // These cases should be handled in InstSimplify: 4502 // umin(X, Y) u<= X --> true 4503 // umin(X, Y) u> X --> false 4504 return nullptr; 4505 } 4506 4507 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) { 4508 // umax(X, Y) == X --> X u>= Y 4509 // umax(X, Y) u<= X --> X u>= Y 4510 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE) 4511 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y); 4512 4513 // umax(X, Y) != X --> X u< Y 4514 // umax(X, Y) u> X --> X u< Y 4515 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT) 4516 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 4517 4518 // These cases should be handled in InstSimplify: 4519 // umax(X, Y) u>= X --> true 4520 // umax(X, Y) u< X --> false 4521 return nullptr; 4522 } 4523 4524 return nullptr; 4525 } 4526 4527 Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) { 4528 if (!I.isEquality()) 4529 return nullptr; 4530 4531 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4532 const CmpInst::Predicate Pred = I.getPredicate(); 4533 Value *A, *B, *C, *D; 4534 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { 4535 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 4536 Value *OtherVal = A == Op1 ? B : A; 4537 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType())); 4538 } 4539 4540 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { 4541 // A^c1 == C^c2 --> A == C^(c1^c2) 4542 ConstantInt *C1, *C2; 4543 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) && 4544 Op1->hasOneUse()) { 4545 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue()); 4546 Value *Xor = Builder.CreateXor(C, NC); 4547 return new ICmpInst(Pred, A, Xor); 4548 } 4549 4550 // A^B == A^D -> B == D 4551 if (A == C) 4552 return new ICmpInst(Pred, B, D); 4553 if (A == D) 4554 return new ICmpInst(Pred, B, C); 4555 if (B == C) 4556 return new ICmpInst(Pred, A, D); 4557 if (B == D) 4558 return new ICmpInst(Pred, A, C); 4559 } 4560 } 4561 4562 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) { 4563 // A == (A^B) -> B == 0 4564 Value *OtherVal = A == Op0 ? B : A; 4565 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType())); 4566 } 4567 4568 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 4569 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) && 4570 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) { 4571 Value *X = nullptr, *Y = nullptr, *Z = nullptr; 4572 4573 if (A == C) { 4574 X = B; 4575 Y = D; 4576 Z = A; 4577 } else if (A == D) { 4578 X = B; 4579 Y = C; 4580 Z = A; 4581 } else if (B == C) { 4582 X = A; 4583 Y = D; 4584 Z = B; 4585 } else if (B == D) { 4586 X = A; 4587 Y = C; 4588 Z = B; 4589 } 4590 4591 if (X) { // Build (X^Y) & Z 4592 Op1 = Builder.CreateXor(X, Y); 4593 Op1 = Builder.CreateAnd(Op1, Z); 4594 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType())); 4595 } 4596 } 4597 4598 { 4599 // Similar to above, but specialized for constant because invert is needed: 4600 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0 4601 Value *X, *Y; 4602 Constant *C; 4603 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) && 4604 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) { 4605 Value *Xor = Builder.CreateXor(X, Y); 4606 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C)); 4607 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType())); 4608 } 4609 } 4610 4611 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B) 4612 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B) 4613 ConstantInt *Cst1; 4614 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) && 4615 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) || 4616 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) && 4617 match(Op1, m_ZExt(m_Value(A))))) { 4618 APInt Pow2 = Cst1->getValue() + 1; 4619 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) && 4620 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth()) 4621 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType())); 4622 } 4623 4624 // (A >> C) == (B >> C) --> (A^B) u< (1 << C) 4625 // For lshr and ashr pairs. 4626 const APInt *AP1, *AP2; 4627 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowUndef(AP1)))) && 4628 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowUndef(AP2))))) || 4629 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowUndef(AP1)))) && 4630 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowUndef(AP2)))))) { 4631 if (AP1 != AP2) 4632 return nullptr; 4633 unsigned TypeBits = AP1->getBitWidth(); 4634 unsigned ShAmt = AP1->getLimitedValue(TypeBits); 4635 if (ShAmt < TypeBits && ShAmt != 0) { 4636 ICmpInst::Predicate NewPred = 4637 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 4638 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted"); 4639 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt); 4640 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal)); 4641 } 4642 } 4643 4644 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0 4645 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) && 4646 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) { 4647 unsigned TypeBits = Cst1->getBitWidth(); 4648 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); 4649 if (ShAmt < TypeBits && ShAmt != 0) { 4650 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted"); 4651 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt); 4652 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal), 4653 I.getName() + ".mask"); 4654 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType())); 4655 } 4656 } 4657 4658 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to 4659 // "icmp (and X, mask), cst" 4660 uint64_t ShAmt = 0; 4661 if (Op0->hasOneUse() && 4662 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) && 4663 match(Op1, m_ConstantInt(Cst1)) && 4664 // Only do this when A has multiple uses. This is most important to do 4665 // when it exposes other optimizations. 4666 !A->hasOneUse()) { 4667 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits(); 4668 4669 if (ShAmt < ASize) { 4670 APInt MaskV = 4671 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits()); 4672 MaskV <<= ShAmt; 4673 4674 APInt CmpV = Cst1->getValue().zext(ASize); 4675 CmpV <<= ShAmt; 4676 4677 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV)); 4678 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV)); 4679 } 4680 } 4681 4682 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I)) 4683 return ICmp; 4684 4685 // Canonicalize checking for a power-of-2-or-zero value: 4686 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants) 4687 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants) 4688 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()), 4689 m_Deferred(A)))) || 4690 !match(Op1, m_ZeroInt())) 4691 A = nullptr; 4692 4693 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants) 4694 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants) 4695 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1))))) 4696 A = Op1; 4697 else if (match(Op1, 4698 m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0))))) 4699 A = Op0; 4700 4701 if (A) { 4702 Type *Ty = A->getType(); 4703 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A); 4704 return Pred == ICmpInst::ICMP_EQ 4705 ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop, ConstantInt::get(Ty, 2)) 4706 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop, ConstantInt::get(Ty, 1)); 4707 } 4708 4709 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks the 4710 // top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s INT_MAX", 4711 // which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a few steps 4712 // of instcombine. 4713 unsigned BitWidth = Op0->getType()->getScalarSizeInBits(); 4714 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) && 4715 match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) && 4716 A->getType()->getScalarSizeInBits() == BitWidth * 2 && 4717 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) { 4718 APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1); 4719 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C)); 4720 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT 4721 : ICmpInst::ICMP_UGE, 4722 Add, ConstantInt::get(A->getType(), C.shl(1))); 4723 } 4724 4725 return nullptr; 4726 } 4727 4728 static Instruction *foldICmpWithTrunc(ICmpInst &ICmp, 4729 InstCombiner::BuilderTy &Builder) { 4730 ICmpInst::Predicate Pred = ICmp.getPredicate(); 4731 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1); 4732 4733 // Try to canonicalize trunc + compare-to-constant into a mask + cmp. 4734 // The trunc masks high bits while the compare may effectively mask low bits. 4735 Value *X; 4736 const APInt *C; 4737 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C))) 4738 return nullptr; 4739 4740 // This matches patterns corresponding to tests of the signbit as well as: 4741 // (trunc X) u< C --> (X & -C) == 0 (are all masked-high-bits clear?) 4742 // (trunc X) u> C --> (X & ~C) != 0 (are any masked-high-bits set?) 4743 APInt Mask; 4744 if (decomposeBitTestICmp(Op0, Op1, Pred, X, Mask, true /* WithTrunc */)) { 4745 Value *And = Builder.CreateAnd(X, Mask); 4746 Constant *Zero = ConstantInt::getNullValue(X->getType()); 4747 return new ICmpInst(Pred, And, Zero); 4748 } 4749 4750 unsigned SrcBits = X->getType()->getScalarSizeInBits(); 4751 if (Pred == ICmpInst::ICMP_ULT && C->isNegatedPowerOf2()) { 4752 // If C is a negative power-of-2 (high-bit mask): 4753 // (trunc X) u< C --> (X & C) != C (are any masked-high-bits clear?) 4754 Constant *MaskC = ConstantInt::get(X->getType(), C->zext(SrcBits)); 4755 Value *And = Builder.CreateAnd(X, MaskC); 4756 return new ICmpInst(ICmpInst::ICMP_NE, And, MaskC); 4757 } 4758 4759 if (Pred == ICmpInst::ICMP_UGT && (~*C).isPowerOf2()) { 4760 // If C is not-of-power-of-2 (one clear bit): 4761 // (trunc X) u> C --> (X & (C+1)) == C+1 (are all masked-high-bits set?) 4762 Constant *MaskC = ConstantInt::get(X->getType(), (*C + 1).zext(SrcBits)); 4763 Value *And = Builder.CreateAnd(X, MaskC); 4764 return new ICmpInst(ICmpInst::ICMP_EQ, And, MaskC); 4765 } 4766 4767 return nullptr; 4768 } 4769 4770 Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) { 4771 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0"); 4772 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0)); 4773 Value *X; 4774 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X)))) 4775 return nullptr; 4776 4777 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt; 4778 bool IsSignedCmp = ICmp.isSigned(); 4779 4780 // icmp Pred (ext X), (ext Y) 4781 Value *Y; 4782 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) { 4783 bool IsZext0 = isa<ZExtOperator>(ICmp.getOperand(0)); 4784 bool IsZext1 = isa<ZExtOperator>(ICmp.getOperand(1)); 4785 4786 // If we have mismatched casts, treat the zext of a non-negative source as 4787 // a sext to simulate matching casts. Otherwise, we are done. 4788 // TODO: Can we handle some predicates (equality) without non-negative? 4789 if (IsZext0 != IsZext1) { 4790 if ((IsZext0 && isKnownNonNegative(X, DL, 0, &AC, &ICmp, &DT)) || 4791 (IsZext1 && isKnownNonNegative(Y, DL, 0, &AC, &ICmp, &DT))) 4792 IsSignedExt = true; 4793 else 4794 return nullptr; 4795 } 4796 4797 // Not an extension from the same type? 4798 Type *XTy = X->getType(), *YTy = Y->getType(); 4799 if (XTy != YTy) { 4800 // One of the casts must have one use because we are creating a new cast. 4801 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse()) 4802 return nullptr; 4803 // Extend the narrower operand to the type of the wider operand. 4804 CastInst::CastOps CastOpcode = 4805 IsSignedExt ? Instruction::SExt : Instruction::ZExt; 4806 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits()) 4807 X = Builder.CreateCast(CastOpcode, X, YTy); 4808 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits()) 4809 Y = Builder.CreateCast(CastOpcode, Y, XTy); 4810 else 4811 return nullptr; 4812 } 4813 4814 // (zext X) == (zext Y) --> X == Y 4815 // (sext X) == (sext Y) --> X == Y 4816 if (ICmp.isEquality()) 4817 return new ICmpInst(ICmp.getPredicate(), X, Y); 4818 4819 // A signed comparison of sign extended values simplifies into a 4820 // signed comparison. 4821 if (IsSignedCmp && IsSignedExt) 4822 return new ICmpInst(ICmp.getPredicate(), X, Y); 4823 4824 // The other three cases all fold into an unsigned comparison. 4825 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y); 4826 } 4827 4828 // Below here, we are only folding a compare with constant. 4829 auto *C = dyn_cast<Constant>(ICmp.getOperand(1)); 4830 if (!C) 4831 return nullptr; 4832 4833 // Compute the constant that would happen if we truncated to SrcTy then 4834 // re-extended to DestTy. 4835 Type *SrcTy = CastOp0->getSrcTy(); 4836 Type *DestTy = CastOp0->getDestTy(); 4837 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy); 4838 Constant *Res2 = ConstantExpr::getCast(CastOp0->getOpcode(), Res1, DestTy); 4839 4840 // If the re-extended constant didn't change... 4841 if (Res2 == C) { 4842 if (ICmp.isEquality()) 4843 return new ICmpInst(ICmp.getPredicate(), X, Res1); 4844 4845 // A signed comparison of sign extended values simplifies into a 4846 // signed comparison. 4847 if (IsSignedExt && IsSignedCmp) 4848 return new ICmpInst(ICmp.getPredicate(), X, Res1); 4849 4850 // The other three cases all fold into an unsigned comparison. 4851 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res1); 4852 } 4853 4854 // The re-extended constant changed, partly changed (in the case of a vector), 4855 // or could not be determined to be equal (in the case of a constant 4856 // expression), so the constant cannot be represented in the shorter type. 4857 // All the cases that fold to true or false will have already been handled 4858 // by simplifyICmpInst, so only deal with the tricky case. 4859 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C)) 4860 return nullptr; 4861 4862 // Is source op positive? 4863 // icmp ult (sext X), C --> icmp sgt X, -1 4864 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT) 4865 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy)); 4866 4867 // Is source op negative? 4868 // icmp ugt (sext X), C --> icmp slt X, 0 4869 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); 4870 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy)); 4871 } 4872 4873 /// Handle icmp (cast x), (cast or constant). 4874 Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) { 4875 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as 4876 // icmp compares only pointer's value. 4877 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2. 4878 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0)); 4879 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1)); 4880 if (SimplifiedOp0 || SimplifiedOp1) 4881 return new ICmpInst(ICmp.getPredicate(), 4882 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0), 4883 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1)); 4884 4885 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0)); 4886 if (!CastOp0) 4887 return nullptr; 4888 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1))) 4889 return nullptr; 4890 4891 Value *Op0Src = CastOp0->getOperand(0); 4892 Type *SrcTy = CastOp0->getSrcTy(); 4893 Type *DestTy = CastOp0->getDestTy(); 4894 4895 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 4896 // integer type is the same size as the pointer type. 4897 auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) { 4898 if (isa<VectorType>(SrcTy)) { 4899 SrcTy = cast<VectorType>(SrcTy)->getElementType(); 4900 DestTy = cast<VectorType>(DestTy)->getElementType(); 4901 } 4902 return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth(); 4903 }; 4904 if (CastOp0->getOpcode() == Instruction::PtrToInt && 4905 CompatibleSizes(SrcTy, DestTy)) { 4906 Value *NewOp1 = nullptr; 4907 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) { 4908 Value *PtrSrc = PtrToIntOp1->getOperand(0); 4909 if (PtrSrc->getType()->getPointerAddressSpace() == 4910 Op0Src->getType()->getPointerAddressSpace()) { 4911 NewOp1 = PtrToIntOp1->getOperand(0); 4912 // If the pointer types don't match, insert a bitcast. 4913 if (Op0Src->getType() != NewOp1->getType()) 4914 NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->getType()); 4915 } 4916 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) { 4917 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy); 4918 } 4919 4920 if (NewOp1) 4921 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1); 4922 } 4923 4924 if (Instruction *R = foldICmpWithTrunc(ICmp, Builder)) 4925 return R; 4926 4927 return foldICmpWithZextOrSext(ICmp); 4928 } 4929 4930 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS) { 4931 switch (BinaryOp) { 4932 default: 4933 llvm_unreachable("Unsupported binary op"); 4934 case Instruction::Add: 4935 case Instruction::Sub: 4936 return match(RHS, m_Zero()); 4937 case Instruction::Mul: 4938 return match(RHS, m_One()); 4939 } 4940 } 4941 4942 OverflowResult 4943 InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp, 4944 bool IsSigned, Value *LHS, Value *RHS, 4945 Instruction *CxtI) const { 4946 switch (BinaryOp) { 4947 default: 4948 llvm_unreachable("Unsupported binary op"); 4949 case Instruction::Add: 4950 if (IsSigned) 4951 return computeOverflowForSignedAdd(LHS, RHS, CxtI); 4952 else 4953 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI); 4954 case Instruction::Sub: 4955 if (IsSigned) 4956 return computeOverflowForSignedSub(LHS, RHS, CxtI); 4957 else 4958 return computeOverflowForUnsignedSub(LHS, RHS, CxtI); 4959 case Instruction::Mul: 4960 if (IsSigned) 4961 return computeOverflowForSignedMul(LHS, RHS, CxtI); 4962 else 4963 return computeOverflowForUnsignedMul(LHS, RHS, CxtI); 4964 } 4965 } 4966 4967 bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp, 4968 bool IsSigned, Value *LHS, 4969 Value *RHS, Instruction &OrigI, 4970 Value *&Result, 4971 Constant *&Overflow) { 4972 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS)) 4973 std::swap(LHS, RHS); 4974 4975 // If the overflow check was an add followed by a compare, the insertion point 4976 // may be pointing to the compare. We want to insert the new instructions 4977 // before the add in case there are uses of the add between the add and the 4978 // compare. 4979 Builder.SetInsertPoint(&OrigI); 4980 4981 Type *OverflowTy = Type::getInt1Ty(LHS->getContext()); 4982 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType())) 4983 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount()); 4984 4985 if (isNeutralValue(BinaryOp, RHS)) { 4986 Result = LHS; 4987 Overflow = ConstantInt::getFalse(OverflowTy); 4988 return true; 4989 } 4990 4991 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) { 4992 case OverflowResult::MayOverflow: 4993 return false; 4994 case OverflowResult::AlwaysOverflowsLow: 4995 case OverflowResult::AlwaysOverflowsHigh: 4996 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS); 4997 Result->takeName(&OrigI); 4998 Overflow = ConstantInt::getTrue(OverflowTy); 4999 return true; 5000 case OverflowResult::NeverOverflows: 5001 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS); 5002 Result->takeName(&OrigI); 5003 Overflow = ConstantInt::getFalse(OverflowTy); 5004 if (auto *Inst = dyn_cast<Instruction>(Result)) { 5005 if (IsSigned) 5006 Inst->setHasNoSignedWrap(); 5007 else 5008 Inst->setHasNoUnsignedWrap(); 5009 } 5010 return true; 5011 } 5012 5013 llvm_unreachable("Unexpected overflow result"); 5014 } 5015 5016 /// Recognize and process idiom involving test for multiplication 5017 /// overflow. 5018 /// 5019 /// The caller has matched a pattern of the form: 5020 /// I = cmp u (mul(zext A, zext B), V 5021 /// The function checks if this is a test for overflow and if so replaces 5022 /// multiplication with call to 'mul.with.overflow' intrinsic. 5023 /// 5024 /// \param I Compare instruction. 5025 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of 5026 /// the compare instruction. Must be of integer type. 5027 /// \param OtherVal The other argument of compare instruction. 5028 /// \returns Instruction which must replace the compare instruction, NULL if no 5029 /// replacement required. 5030 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal, 5031 Value *OtherVal, 5032 InstCombinerImpl &IC) { 5033 // Don't bother doing this transformation for pointers, don't do it for 5034 // vectors. 5035 if (!isa<IntegerType>(MulVal->getType())) 5036 return nullptr; 5037 5038 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal); 5039 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal); 5040 auto *MulInstr = dyn_cast<Instruction>(MulVal); 5041 if (!MulInstr) 5042 return nullptr; 5043 assert(MulInstr->getOpcode() == Instruction::Mul); 5044 5045 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)), 5046 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1)); 5047 assert(LHS->getOpcode() == Instruction::ZExt); 5048 assert(RHS->getOpcode() == Instruction::ZExt); 5049 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0); 5050 5051 // Calculate type and width of the result produced by mul.with.overflow. 5052 Type *TyA = A->getType(), *TyB = B->getType(); 5053 unsigned WidthA = TyA->getPrimitiveSizeInBits(), 5054 WidthB = TyB->getPrimitiveSizeInBits(); 5055 unsigned MulWidth; 5056 Type *MulType; 5057 if (WidthB > WidthA) { 5058 MulWidth = WidthB; 5059 MulType = TyB; 5060 } else { 5061 MulWidth = WidthA; 5062 MulType = TyA; 5063 } 5064 5065 // In order to replace the original mul with a narrower mul.with.overflow, 5066 // all uses must ignore upper bits of the product. The number of used low 5067 // bits must be not greater than the width of mul.with.overflow. 5068 if (MulVal->hasNUsesOrMore(2)) 5069 for (User *U : MulVal->users()) { 5070 if (U == &I) 5071 continue; 5072 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 5073 // Check if truncation ignores bits above MulWidth. 5074 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits(); 5075 if (TruncWidth > MulWidth) 5076 return nullptr; 5077 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 5078 // Check if AND ignores bits above MulWidth. 5079 if (BO->getOpcode() != Instruction::And) 5080 return nullptr; 5081 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 5082 const APInt &CVal = CI->getValue(); 5083 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth) 5084 return nullptr; 5085 } else { 5086 // In this case we could have the operand of the binary operation 5087 // being defined in another block, and performing the replacement 5088 // could break the dominance relation. 5089 return nullptr; 5090 } 5091 } else { 5092 // Other uses prohibit this transformation. 5093 return nullptr; 5094 } 5095 } 5096 5097 // Recognize patterns 5098 switch (I.getPredicate()) { 5099 case ICmpInst::ICMP_EQ: 5100 case ICmpInst::ICMP_NE: 5101 // Recognize pattern: 5102 // mulval = mul(zext A, zext B) 5103 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits. 5104 ConstantInt *CI; 5105 Value *ValToMask; 5106 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) { 5107 if (ValToMask != MulVal) 5108 return nullptr; 5109 const APInt &CVal = CI->getValue() + 1; 5110 if (CVal.isPowerOf2()) { 5111 unsigned MaskWidth = CVal.logBase2(); 5112 if (MaskWidth == MulWidth) 5113 break; // Recognized 5114 } 5115 } 5116 return nullptr; 5117 5118 case ICmpInst::ICMP_UGT: 5119 // Recognize pattern: 5120 // mulval = mul(zext A, zext B) 5121 // cmp ugt mulval, max 5122 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 5123 APInt MaxVal = APInt::getMaxValue(MulWidth); 5124 MaxVal = MaxVal.zext(CI->getBitWidth()); 5125 if (MaxVal.eq(CI->getValue())) 5126 break; // Recognized 5127 } 5128 return nullptr; 5129 5130 case ICmpInst::ICMP_UGE: 5131 // Recognize pattern: 5132 // mulval = mul(zext A, zext B) 5133 // cmp uge mulval, max+1 5134 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 5135 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 5136 if (MaxVal.eq(CI->getValue())) 5137 break; // Recognized 5138 } 5139 return nullptr; 5140 5141 case ICmpInst::ICMP_ULE: 5142 // Recognize pattern: 5143 // mulval = mul(zext A, zext B) 5144 // cmp ule mulval, max 5145 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 5146 APInt MaxVal = APInt::getMaxValue(MulWidth); 5147 MaxVal = MaxVal.zext(CI->getBitWidth()); 5148 if (MaxVal.eq(CI->getValue())) 5149 break; // Recognized 5150 } 5151 return nullptr; 5152 5153 case ICmpInst::ICMP_ULT: 5154 // Recognize pattern: 5155 // mulval = mul(zext A, zext B) 5156 // cmp ule mulval, max + 1 5157 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 5158 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 5159 if (MaxVal.eq(CI->getValue())) 5160 break; // Recognized 5161 } 5162 return nullptr; 5163 5164 default: 5165 return nullptr; 5166 } 5167 5168 InstCombiner::BuilderTy &Builder = IC.Builder; 5169 Builder.SetInsertPoint(MulInstr); 5170 5171 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B) 5172 Value *MulA = A, *MulB = B; 5173 if (WidthA < MulWidth) 5174 MulA = Builder.CreateZExt(A, MulType); 5175 if (WidthB < MulWidth) 5176 MulB = Builder.CreateZExt(B, MulType); 5177 Function *F = Intrinsic::getDeclaration( 5178 I.getModule(), Intrinsic::umul_with_overflow, MulType); 5179 CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul"); 5180 IC.addToWorklist(MulInstr); 5181 5182 // If there are uses of mul result other than the comparison, we know that 5183 // they are truncation or binary AND. Change them to use result of 5184 // mul.with.overflow and adjust properly mask/size. 5185 if (MulVal->hasNUsesOrMore(2)) { 5186 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value"); 5187 for (User *U : make_early_inc_range(MulVal->users())) { 5188 if (U == &I || U == OtherVal) 5189 continue; 5190 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 5191 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth) 5192 IC.replaceInstUsesWith(*TI, Mul); 5193 else 5194 TI->setOperand(0, Mul); 5195 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 5196 assert(BO->getOpcode() == Instruction::And); 5197 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask) 5198 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1)); 5199 APInt ShortMask = CI->getValue().trunc(MulWidth); 5200 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask); 5201 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType()); 5202 IC.replaceInstUsesWith(*BO, Zext); 5203 } else { 5204 llvm_unreachable("Unexpected Binary operation"); 5205 } 5206 IC.addToWorklist(cast<Instruction>(U)); 5207 } 5208 } 5209 if (isa<Instruction>(OtherVal)) 5210 IC.addToWorklist(cast<Instruction>(OtherVal)); 5211 5212 // The original icmp gets replaced with the overflow value, maybe inverted 5213 // depending on predicate. 5214 bool Inverse = false; 5215 switch (I.getPredicate()) { 5216 case ICmpInst::ICMP_NE: 5217 break; 5218 case ICmpInst::ICMP_EQ: 5219 Inverse = true; 5220 break; 5221 case ICmpInst::ICMP_UGT: 5222 case ICmpInst::ICMP_UGE: 5223 if (I.getOperand(0) == MulVal) 5224 break; 5225 Inverse = true; 5226 break; 5227 case ICmpInst::ICMP_ULT: 5228 case ICmpInst::ICMP_ULE: 5229 if (I.getOperand(1) == MulVal) 5230 break; 5231 Inverse = true; 5232 break; 5233 default: 5234 llvm_unreachable("Unexpected predicate"); 5235 } 5236 if (Inverse) { 5237 Value *Res = Builder.CreateExtractValue(Call, 1); 5238 return BinaryOperator::CreateNot(Res); 5239 } 5240 5241 return ExtractValueInst::Create(Call, 1); 5242 } 5243 5244 /// When performing a comparison against a constant, it is possible that not all 5245 /// the bits in the LHS are demanded. This helper method computes the mask that 5246 /// IS demanded. 5247 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) { 5248 const APInt *RHS; 5249 if (!match(I.getOperand(1), m_APInt(RHS))) 5250 return APInt::getAllOnes(BitWidth); 5251 5252 // If this is a normal comparison, it demands all bits. If it is a sign bit 5253 // comparison, it only demands the sign bit. 5254 bool UnusedBit; 5255 if (InstCombiner::isSignBitCheck(I.getPredicate(), *RHS, UnusedBit)) 5256 return APInt::getSignMask(BitWidth); 5257 5258 switch (I.getPredicate()) { 5259 // For a UGT comparison, we don't care about any bits that 5260 // correspond to the trailing ones of the comparand. The value of these 5261 // bits doesn't impact the outcome of the comparison, because any value 5262 // greater than the RHS must differ in a bit higher than these due to carry. 5263 case ICmpInst::ICMP_UGT: 5264 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes()); 5265 5266 // Similarly, for a ULT comparison, we don't care about the trailing zeros. 5267 // Any value less than the RHS must differ in a higher bit because of carries. 5268 case ICmpInst::ICMP_ULT: 5269 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros()); 5270 5271 default: 5272 return APInt::getAllOnes(BitWidth); 5273 } 5274 } 5275 5276 /// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst 5277 /// should be swapped. 5278 /// The decision is based on how many times these two operands are reused 5279 /// as subtract operands and their positions in those instructions. 5280 /// The rationale is that several architectures use the same instruction for 5281 /// both subtract and cmp. Thus, it is better if the order of those operands 5282 /// match. 5283 /// \return true if Op0 and Op1 should be swapped. 5284 static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) { 5285 // Filter out pointer values as those cannot appear directly in subtract. 5286 // FIXME: we may want to go through inttoptrs or bitcasts. 5287 if (Op0->getType()->isPointerTy()) 5288 return false; 5289 // If a subtract already has the same operands as a compare, swapping would be 5290 // bad. If a subtract has the same operands as a compare but in reverse order, 5291 // then swapping is good. 5292 int GoodToSwap = 0; 5293 for (const User *U : Op0->users()) { 5294 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0)))) 5295 GoodToSwap++; 5296 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1)))) 5297 GoodToSwap--; 5298 } 5299 return GoodToSwap > 0; 5300 } 5301 5302 /// Check that one use is in the same block as the definition and all 5303 /// other uses are in blocks dominated by a given block. 5304 /// 5305 /// \param DI Definition 5306 /// \param UI Use 5307 /// \param DB Block that must dominate all uses of \p DI outside 5308 /// the parent block 5309 /// \return true when \p UI is the only use of \p DI in the parent block 5310 /// and all other uses of \p DI are in blocks dominated by \p DB. 5311 /// 5312 bool InstCombinerImpl::dominatesAllUses(const Instruction *DI, 5313 const Instruction *UI, 5314 const BasicBlock *DB) const { 5315 assert(DI && UI && "Instruction not defined\n"); 5316 // Ignore incomplete definitions. 5317 if (!DI->getParent()) 5318 return false; 5319 // DI and UI must be in the same block. 5320 if (DI->getParent() != UI->getParent()) 5321 return false; 5322 // Protect from self-referencing blocks. 5323 if (DI->getParent() == DB) 5324 return false; 5325 for (const User *U : DI->users()) { 5326 auto *Usr = cast<Instruction>(U); 5327 if (Usr != UI && !DT.dominates(DB, Usr->getParent())) 5328 return false; 5329 } 5330 return true; 5331 } 5332 5333 /// Return true when the instruction sequence within a block is select-cmp-br. 5334 static bool isChainSelectCmpBranch(const SelectInst *SI) { 5335 const BasicBlock *BB = SI->getParent(); 5336 if (!BB) 5337 return false; 5338 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator()); 5339 if (!BI || BI->getNumSuccessors() != 2) 5340 return false; 5341 auto *IC = dyn_cast<ICmpInst>(BI->getCondition()); 5342 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI)) 5343 return false; 5344 return true; 5345 } 5346 5347 /// True when a select result is replaced by one of its operands 5348 /// in select-icmp sequence. This will eventually result in the elimination 5349 /// of the select. 5350 /// 5351 /// \param SI Select instruction 5352 /// \param Icmp Compare instruction 5353 /// \param SIOpd Operand that replaces the select 5354 /// 5355 /// Notes: 5356 /// - The replacement is global and requires dominator information 5357 /// - The caller is responsible for the actual replacement 5358 /// 5359 /// Example: 5360 /// 5361 /// entry: 5362 /// %4 = select i1 %3, %C* %0, %C* null 5363 /// %5 = icmp eq %C* %4, null 5364 /// br i1 %5, label %9, label %7 5365 /// ... 5366 /// ; <label>:7 ; preds = %entry 5367 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0 5368 /// ... 5369 /// 5370 /// can be transformed to 5371 /// 5372 /// %5 = icmp eq %C* %0, null 5373 /// %6 = select i1 %3, i1 %5, i1 true 5374 /// br i1 %6, label %9, label %7 5375 /// ... 5376 /// ; <label>:7 ; preds = %entry 5377 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0! 5378 /// 5379 /// Similar when the first operand of the select is a constant or/and 5380 /// the compare is for not equal rather than equal. 5381 /// 5382 /// NOTE: The function is only called when the select and compare constants 5383 /// are equal, the optimization can work only for EQ predicates. This is not a 5384 /// major restriction since a NE compare should be 'normalized' to an equal 5385 /// compare, which usually happens in the combiner and test case 5386 /// select-cmp-br.ll checks for it. 5387 bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI, 5388 const ICmpInst *Icmp, 5389 const unsigned SIOpd) { 5390 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!"); 5391 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) { 5392 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1); 5393 // The check for the single predecessor is not the best that can be 5394 // done. But it protects efficiently against cases like when SI's 5395 // home block has two successors, Succ and Succ1, and Succ1 predecessor 5396 // of Succ. Then SI can't be replaced by SIOpd because the use that gets 5397 // replaced can be reached on either path. So the uniqueness check 5398 // guarantees that the path all uses of SI (outside SI's parent) are on 5399 // is disjoint from all other paths out of SI. But that information 5400 // is more expensive to compute, and the trade-off here is in favor 5401 // of compile-time. It should also be noticed that we check for a single 5402 // predecessor and not only uniqueness. This to handle the situation when 5403 // Succ and Succ1 points to the same basic block. 5404 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) { 5405 NumSel++; 5406 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent()); 5407 return true; 5408 } 5409 } 5410 return false; 5411 } 5412 5413 /// Try to fold the comparison based on range information we can get by checking 5414 /// whether bits are known to be zero or one in the inputs. 5415 Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) { 5416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 5417 Type *Ty = Op0->getType(); 5418 ICmpInst::Predicate Pred = I.getPredicate(); 5419 5420 // Get scalar or pointer size. 5421 unsigned BitWidth = Ty->isIntOrIntVectorTy() 5422 ? Ty->getScalarSizeInBits() 5423 : DL.getPointerTypeSizeInBits(Ty->getScalarType()); 5424 5425 if (!BitWidth) 5426 return nullptr; 5427 5428 KnownBits Op0Known(BitWidth); 5429 KnownBits Op1Known(BitWidth); 5430 5431 if (SimplifyDemandedBits(&I, 0, 5432 getDemandedBitsLHSMask(I, BitWidth), 5433 Op0Known, 0)) 5434 return &I; 5435 5436 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, 0)) 5437 return &I; 5438 5439 // Given the known and unknown bits, compute a range that the LHS could be 5440 // in. Compute the Min, Max and RHS values based on the known bits. For the 5441 // EQ and NE we use unsigned values. 5442 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); 5443 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); 5444 if (I.isSigned()) { 5445 Op0Min = Op0Known.getSignedMinValue(); 5446 Op0Max = Op0Known.getSignedMaxValue(); 5447 Op1Min = Op1Known.getSignedMinValue(); 5448 Op1Max = Op1Known.getSignedMaxValue(); 5449 } else { 5450 Op0Min = Op0Known.getMinValue(); 5451 Op0Max = Op0Known.getMaxValue(); 5452 Op1Min = Op1Known.getMinValue(); 5453 Op1Max = Op1Known.getMaxValue(); 5454 } 5455 5456 // If Min and Max are known to be the same, then SimplifyDemandedBits figured 5457 // out that the LHS or RHS is a constant. Constant fold this now, so that 5458 // code below can assume that Min != Max. 5459 if (!isa<Constant>(Op0) && Op0Min == Op0Max) 5460 return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1); 5461 if (!isa<Constant>(Op1) && Op1Min == Op1Max) 5462 return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min)); 5463 5464 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a 5465 // min/max canonical compare with some other compare. That could lead to 5466 // conflict with select canonicalization and infinite looping. 5467 // FIXME: This constraint may go away if min/max intrinsics are canonical. 5468 auto isMinMaxCmp = [&](Instruction &Cmp) { 5469 if (!Cmp.hasOneUse()) 5470 return false; 5471 Value *A, *B; 5472 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor; 5473 if (!SelectPatternResult::isMinOrMax(SPF)) 5474 return false; 5475 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) || 5476 match(Op1, m_MaxOrMin(m_Value(), m_Value())); 5477 }; 5478 if (!isMinMaxCmp(I)) { 5479 switch (Pred) { 5480 default: 5481 break; 5482 case ICmpInst::ICMP_ULT: { 5483 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) 5484 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5485 const APInt *CmpC; 5486 if (match(Op1, m_APInt(CmpC))) { 5487 // A <u C -> A == C-1 if min(A)+1 == C 5488 if (*CmpC == Op0Min + 1) 5489 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5490 ConstantInt::get(Op1->getType(), *CmpC - 1)); 5491 // X <u C --> X == 0, if the number of zero bits in the bottom of X 5492 // exceeds the log2 of C. 5493 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2()) 5494 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5495 Constant::getNullValue(Op1->getType())); 5496 } 5497 break; 5498 } 5499 case ICmpInst::ICMP_UGT: { 5500 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) 5501 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5502 const APInt *CmpC; 5503 if (match(Op1, m_APInt(CmpC))) { 5504 // A >u C -> A == C+1 if max(a)-1 == C 5505 if (*CmpC == Op0Max - 1) 5506 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5507 ConstantInt::get(Op1->getType(), *CmpC + 1)); 5508 // X >u C --> X != 0, if the number of zero bits in the bottom of X 5509 // exceeds the log2 of C. 5510 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits()) 5511 return new ICmpInst(ICmpInst::ICMP_NE, Op0, 5512 Constant::getNullValue(Op1->getType())); 5513 } 5514 break; 5515 } 5516 case ICmpInst::ICMP_SLT: { 5517 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) 5518 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5519 const APInt *CmpC; 5520 if (match(Op1, m_APInt(CmpC))) { 5521 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C 5522 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5523 ConstantInt::get(Op1->getType(), *CmpC - 1)); 5524 } 5525 break; 5526 } 5527 case ICmpInst::ICMP_SGT: { 5528 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) 5529 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5530 const APInt *CmpC; 5531 if (match(Op1, m_APInt(CmpC))) { 5532 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C 5533 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5534 ConstantInt::get(Op1->getType(), *CmpC + 1)); 5535 } 5536 break; 5537 } 5538 } 5539 } 5540 5541 // Based on the range information we know about the LHS, see if we can 5542 // simplify this comparison. For example, (x&4) < 8 is always true. 5543 switch (Pred) { 5544 default: 5545 llvm_unreachable("Unknown icmp opcode!"); 5546 case ICmpInst::ICMP_EQ: 5547 case ICmpInst::ICMP_NE: { 5548 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) 5549 return replaceInstUsesWith( 5550 I, ConstantInt::getBool(I.getType(), Pred == CmpInst::ICMP_NE)); 5551 5552 // If all bits are known zero except for one, then we know at most one bit 5553 // is set. If the comparison is against zero, then this is a check to see if 5554 // *that* bit is set. 5555 APInt Op0KnownZeroInverted = ~Op0Known.Zero; 5556 if (Op1Known.isZero()) { 5557 // If the LHS is an AND with the same constant, look through it. 5558 Value *LHS = nullptr; 5559 const APInt *LHSC; 5560 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) || 5561 *LHSC != Op0KnownZeroInverted) 5562 LHS = Op0; 5563 5564 Value *X; 5565 const APInt *C1; 5566 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) { 5567 Type *XTy = X->getType(); 5568 unsigned Log2C1 = C1->countTrailingZeros(); 5569 APInt C2 = Op0KnownZeroInverted; 5570 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1; 5571 if (C2Pow2.isPowerOf2()) { 5572 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2): 5573 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1)) 5574 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1)) 5575 unsigned Log2C2 = C2Pow2.countTrailingZeros(); 5576 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1); 5577 auto NewPred = 5578 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT; 5579 return new ICmpInst(NewPred, X, CmpC); 5580 } 5581 } 5582 } 5583 break; 5584 } 5585 case ICmpInst::ICMP_ULT: { 5586 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) 5587 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5588 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) 5589 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5590 break; 5591 } 5592 case ICmpInst::ICMP_UGT: { 5593 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) 5594 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5595 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) 5596 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5597 break; 5598 } 5599 case ICmpInst::ICMP_SLT: { 5600 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) 5601 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5602 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) 5603 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5604 break; 5605 } 5606 case ICmpInst::ICMP_SGT: { 5607 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) 5608 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5609 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) 5610 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5611 break; 5612 } 5613 case ICmpInst::ICMP_SGE: 5614 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); 5615 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) 5616 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5617 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) 5618 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5619 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B) 5620 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5621 break; 5622 case ICmpInst::ICMP_SLE: 5623 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); 5624 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) 5625 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5626 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) 5627 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5628 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B) 5629 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5630 break; 5631 case ICmpInst::ICMP_UGE: 5632 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); 5633 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) 5634 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5635 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) 5636 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5637 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B) 5638 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5639 break; 5640 case ICmpInst::ICMP_ULE: 5641 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); 5642 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) 5643 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5644 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) 5645 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5646 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B) 5647 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5648 break; 5649 } 5650 5651 // Turn a signed comparison into an unsigned one if both operands are known to 5652 // have the same sign. 5653 if (I.isSigned() && 5654 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) || 5655 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) 5656 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); 5657 5658 return nullptr; 5659 } 5660 5661 /// If one operand of an icmp is effectively a bool (value range of {0,1}), 5662 /// then try to reduce patterns based on that limit. 5663 static Instruction *foldICmpUsingBoolRange(ICmpInst &I, 5664 InstCombiner::BuilderTy &Builder) { 5665 Value *X, *Y; 5666 ICmpInst::Predicate Pred; 5667 5668 // X must be 0 and bool must be true for "ULT": 5669 // X <u (zext i1 Y) --> (X == 0) & Y 5670 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) && 5671 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT) 5672 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y); 5673 5674 // X must be 0 or bool must be true for "ULE": 5675 // X <=u (sext i1 Y) --> (X == 0) | Y 5676 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) && 5677 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE) 5678 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y); 5679 5680 return nullptr; 5681 } 5682 5683 llvm::Optional<std::pair<CmpInst::Predicate, Constant *>> 5684 InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred, 5685 Constant *C) { 5686 assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) && 5687 "Only for relational integer predicates."); 5688 5689 Type *Type = C->getType(); 5690 bool IsSigned = ICmpInst::isSigned(Pred); 5691 5692 CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred); 5693 bool WillIncrement = 5694 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT; 5695 5696 // Check if the constant operand can be safely incremented/decremented 5697 // without overflowing/underflowing. 5698 auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) { 5699 return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned); 5700 }; 5701 5702 Constant *SafeReplacementConstant = nullptr; 5703 if (auto *CI = dyn_cast<ConstantInt>(C)) { 5704 // Bail out if the constant can't be safely incremented/decremented. 5705 if (!ConstantIsOk(CI)) 5706 return llvm::None; 5707 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) { 5708 unsigned NumElts = FVTy->getNumElements(); 5709 for (unsigned i = 0; i != NumElts; ++i) { 5710 Constant *Elt = C->getAggregateElement(i); 5711 if (!Elt) 5712 return llvm::None; 5713 5714 if (isa<UndefValue>(Elt)) 5715 continue; 5716 5717 // Bail out if we can't determine if this constant is min/max or if we 5718 // know that this constant is min/max. 5719 auto *CI = dyn_cast<ConstantInt>(Elt); 5720 if (!CI || !ConstantIsOk(CI)) 5721 return llvm::None; 5722 5723 if (!SafeReplacementConstant) 5724 SafeReplacementConstant = CI; 5725 } 5726 } else { 5727 // ConstantExpr? 5728 return llvm::None; 5729 } 5730 5731 // It may not be safe to change a compare predicate in the presence of 5732 // undefined elements, so replace those elements with the first safe constant 5733 // that we found. 5734 // TODO: in case of poison, it is safe; let's replace undefs only. 5735 if (C->containsUndefOrPoisonElement()) { 5736 assert(SafeReplacementConstant && "Replacement constant not set"); 5737 C = Constant::replaceUndefsWith(C, SafeReplacementConstant); 5738 } 5739 5740 CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred); 5741 5742 // Increment or decrement the constant. 5743 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true); 5744 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne); 5745 5746 return std::make_pair(NewPred, NewC); 5747 } 5748 5749 /// If we have an icmp le or icmp ge instruction with a constant operand, turn 5750 /// it into the appropriate icmp lt or icmp gt instruction. This transform 5751 /// allows them to be folded in visitICmpInst. 5752 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) { 5753 ICmpInst::Predicate Pred = I.getPredicate(); 5754 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) || 5755 InstCombiner::isCanonicalPredicate(Pred)) 5756 return nullptr; 5757 5758 Value *Op0 = I.getOperand(0); 5759 Value *Op1 = I.getOperand(1); 5760 auto *Op1C = dyn_cast<Constant>(Op1); 5761 if (!Op1C) 5762 return nullptr; 5763 5764 auto FlippedStrictness = 5765 InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C); 5766 if (!FlippedStrictness) 5767 return nullptr; 5768 5769 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second); 5770 } 5771 5772 /// If we have a comparison with a non-canonical predicate, if we can update 5773 /// all the users, invert the predicate and adjust all the users. 5774 CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) { 5775 // Is the predicate already canonical? 5776 CmpInst::Predicate Pred = I.getPredicate(); 5777 if (InstCombiner::isCanonicalPredicate(Pred)) 5778 return nullptr; 5779 5780 // Can all users be adjusted to predicate inversion? 5781 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr)) 5782 return nullptr; 5783 5784 // Ok, we can canonicalize comparison! 5785 // Let's first invert the comparison's predicate. 5786 I.setPredicate(CmpInst::getInversePredicate(Pred)); 5787 I.setName(I.getName() + ".not"); 5788 5789 // And, adapt users. 5790 freelyInvertAllUsersOf(&I); 5791 5792 return &I; 5793 } 5794 5795 /// Integer compare with boolean values can always be turned into bitwise ops. 5796 static Instruction *canonicalizeICmpBool(ICmpInst &I, 5797 InstCombiner::BuilderTy &Builder) { 5798 Value *A = I.getOperand(0), *B = I.getOperand(1); 5799 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only"); 5800 5801 // A boolean compared to true/false can be simplified to Op0/true/false in 5802 // 14 out of the 20 (10 predicates * 2 constants) possible combinations. 5803 // Cases not handled by InstSimplify are always 'not' of Op0. 5804 if (match(B, m_Zero())) { 5805 switch (I.getPredicate()) { 5806 case CmpInst::ICMP_EQ: // A == 0 -> !A 5807 case CmpInst::ICMP_ULE: // A <=u 0 -> !A 5808 case CmpInst::ICMP_SGE: // A >=s 0 -> !A 5809 return BinaryOperator::CreateNot(A); 5810 default: 5811 llvm_unreachable("ICmp i1 X, C not simplified as expected."); 5812 } 5813 } else if (match(B, m_One())) { 5814 switch (I.getPredicate()) { 5815 case CmpInst::ICMP_NE: // A != 1 -> !A 5816 case CmpInst::ICMP_ULT: // A <u 1 -> !A 5817 case CmpInst::ICMP_SGT: // A >s -1 -> !A 5818 return BinaryOperator::CreateNot(A); 5819 default: 5820 llvm_unreachable("ICmp i1 X, C not simplified as expected."); 5821 } 5822 } 5823 5824 switch (I.getPredicate()) { 5825 default: 5826 llvm_unreachable("Invalid icmp instruction!"); 5827 case ICmpInst::ICMP_EQ: 5828 // icmp eq i1 A, B -> ~(A ^ B) 5829 return BinaryOperator::CreateNot(Builder.CreateXor(A, B)); 5830 5831 case ICmpInst::ICMP_NE: 5832 // icmp ne i1 A, B -> A ^ B 5833 return BinaryOperator::CreateXor(A, B); 5834 5835 case ICmpInst::ICMP_UGT: 5836 // icmp ugt -> icmp ult 5837 std::swap(A, B); 5838 LLVM_FALLTHROUGH; 5839 case ICmpInst::ICMP_ULT: 5840 // icmp ult i1 A, B -> ~A & B 5841 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B); 5842 5843 case ICmpInst::ICMP_SGT: 5844 // icmp sgt -> icmp slt 5845 std::swap(A, B); 5846 LLVM_FALLTHROUGH; 5847 case ICmpInst::ICMP_SLT: 5848 // icmp slt i1 A, B -> A & ~B 5849 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A); 5850 5851 case ICmpInst::ICMP_UGE: 5852 // icmp uge -> icmp ule 5853 std::swap(A, B); 5854 LLVM_FALLTHROUGH; 5855 case ICmpInst::ICMP_ULE: 5856 // icmp ule i1 A, B -> ~A | B 5857 return BinaryOperator::CreateOr(Builder.CreateNot(A), B); 5858 5859 case ICmpInst::ICMP_SGE: 5860 // icmp sge -> icmp sle 5861 std::swap(A, B); 5862 LLVM_FALLTHROUGH; 5863 case ICmpInst::ICMP_SLE: 5864 // icmp sle i1 A, B -> A | ~B 5865 return BinaryOperator::CreateOr(Builder.CreateNot(B), A); 5866 } 5867 } 5868 5869 // Transform pattern like: 5870 // (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X 5871 // (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X 5872 // Into: 5873 // (X l>> Y) != 0 5874 // (X l>> Y) == 0 5875 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp, 5876 InstCombiner::BuilderTy &Builder) { 5877 ICmpInst::Predicate Pred, NewPred; 5878 Value *X, *Y; 5879 if (match(&Cmp, 5880 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) { 5881 switch (Pred) { 5882 case ICmpInst::ICMP_ULE: 5883 NewPred = ICmpInst::ICMP_NE; 5884 break; 5885 case ICmpInst::ICMP_UGT: 5886 NewPred = ICmpInst::ICMP_EQ; 5887 break; 5888 default: 5889 return nullptr; 5890 } 5891 } else if (match(&Cmp, m_c_ICmp(Pred, 5892 m_OneUse(m_CombineOr( 5893 m_Not(m_Shl(m_AllOnes(), m_Value(Y))), 5894 m_Add(m_Shl(m_One(), m_Value(Y)), 5895 m_AllOnes()))), 5896 m_Value(X)))) { 5897 // The variant with 'add' is not canonical, (the variant with 'not' is) 5898 // we only get it because it has extra uses, and can't be canonicalized, 5899 5900 switch (Pred) { 5901 case ICmpInst::ICMP_ULT: 5902 NewPred = ICmpInst::ICMP_NE; 5903 break; 5904 case ICmpInst::ICMP_UGE: 5905 NewPred = ICmpInst::ICMP_EQ; 5906 break; 5907 default: 5908 return nullptr; 5909 } 5910 } else 5911 return nullptr; 5912 5913 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits"); 5914 Constant *Zero = Constant::getNullValue(NewX->getType()); 5915 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero); 5916 } 5917 5918 static Instruction *foldVectorCmp(CmpInst &Cmp, 5919 InstCombiner::BuilderTy &Builder) { 5920 const CmpInst::Predicate Pred = Cmp.getPredicate(); 5921 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1); 5922 Value *V1, *V2; 5923 ArrayRef<int> M; 5924 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M)))) 5925 return nullptr; 5926 5927 // If both arguments of the cmp are shuffles that use the same mask and 5928 // shuffle within a single vector, move the shuffle after the cmp: 5929 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M 5930 Type *V1Ty = V1->getType(); 5931 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) && 5932 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) { 5933 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2); 5934 return new ShuffleVectorInst(NewCmp, M); 5935 } 5936 5937 // Try to canonicalize compare with splatted operand and splat constant. 5938 // TODO: We could generalize this for more than splats. See/use the code in 5939 // InstCombiner::foldVectorBinop(). 5940 Constant *C; 5941 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C))) 5942 return nullptr; 5943 5944 // Length-changing splats are ok, so adjust the constants as needed: 5945 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M 5946 Constant *ScalarC = C->getSplatValue(/* AllowUndefs */ true); 5947 int MaskSplatIndex; 5948 if (ScalarC && match(M, m_SplatOrUndefMask(MaskSplatIndex))) { 5949 // We allow undefs in matching, but this transform removes those for safety. 5950 // Demanded elements analysis should be able to recover some/all of that. 5951 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(), 5952 ScalarC); 5953 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex); 5954 Value *NewCmp = Builder.CreateCmp(Pred, V1, C); 5955 return new ShuffleVectorInst(NewCmp, NewM); 5956 } 5957 5958 return nullptr; 5959 } 5960 5961 // extract(uadd.with.overflow(A, B), 0) ult A 5962 // -> extract(uadd.with.overflow(A, B), 1) 5963 static Instruction *foldICmpOfUAddOv(ICmpInst &I) { 5964 CmpInst::Predicate Pred = I.getPredicate(); 5965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 5966 5967 Value *UAddOv; 5968 Value *A, *B; 5969 auto UAddOvResultPat = m_ExtractValue<0>( 5970 m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B))); 5971 if (match(Op0, UAddOvResultPat) && 5972 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) || 5973 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) && 5974 (match(A, m_One()) || match(B, m_One()))) || 5975 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) && 5976 (match(A, m_AllOnes()) || match(B, m_AllOnes()))))) 5977 // extract(uadd.with.overflow(A, B), 0) < A 5978 // extract(uadd.with.overflow(A, 1), 0) == 0 5979 // extract(uadd.with.overflow(A, -1), 0) != -1 5980 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand(); 5981 else if (match(Op1, UAddOvResultPat) && 5982 Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B)) 5983 // A > extract(uadd.with.overflow(A, B), 0) 5984 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand(); 5985 else 5986 return nullptr; 5987 5988 return ExtractValueInst::Create(UAddOv, 1); 5989 } 5990 5991 static Instruction *foldICmpInvariantGroup(ICmpInst &I) { 5992 if (!I.getOperand(0)->getType()->isPointerTy() || 5993 NullPointerIsDefined( 5994 I.getParent()->getParent(), 5995 I.getOperand(0)->getType()->getPointerAddressSpace())) { 5996 return nullptr; 5997 } 5998 Instruction *Op; 5999 if (match(I.getOperand(0), m_Instruction(Op)) && 6000 match(I.getOperand(1), m_Zero()) && 6001 Op->isLaunderOrStripInvariantGroup()) { 6002 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(), 6003 Op->getOperand(0), I.getOperand(1)); 6004 } 6005 return nullptr; 6006 } 6007 6008 /// This function folds patterns produced by lowering of reduce idioms, such as 6009 /// llvm.vector.reduce.and which are lowered into instruction chains. This code 6010 /// attempts to generate fewer number of scalar comparisons instead of vector 6011 /// comparisons when possible. 6012 static Instruction *foldReductionIdiom(ICmpInst &I, 6013 InstCombiner::BuilderTy &Builder, 6014 const DataLayout &DL) { 6015 if (I.getType()->isVectorTy()) 6016 return nullptr; 6017 ICmpInst::Predicate OuterPred, InnerPred; 6018 Value *LHS, *RHS; 6019 6020 // Match lowering of @llvm.vector.reduce.and. Turn 6021 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs 6022 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8 6023 /// %res = icmp <pred> i8 %scalar_ne, 0 6024 /// 6025 /// into 6026 /// 6027 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64 6028 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64 6029 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar 6030 /// 6031 /// for <pred> in {ne, eq}. 6032 if (!match(&I, m_ICmp(OuterPred, 6033 m_OneUse(m_BitCast(m_OneUse( 6034 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))), 6035 m_Zero()))) 6036 return nullptr; 6037 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType()); 6038 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy()) 6039 return nullptr; 6040 unsigned NumBits = 6041 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth(); 6042 // TODO: Relax this to "not wider than max legal integer type"? 6043 if (!DL.isLegalInteger(NumBits)) 6044 return nullptr; 6045 6046 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) { 6047 auto *ScalarTy = Builder.getIntNTy(NumBits); 6048 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar"); 6049 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar"); 6050 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS, 6051 I.getName()); 6052 } 6053 6054 return nullptr; 6055 } 6056 6057 Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) { 6058 bool Changed = false; 6059 const SimplifyQuery Q = SQ.getWithInstruction(&I); 6060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 6061 unsigned Op0Cplxity = getComplexity(Op0); 6062 unsigned Op1Cplxity = getComplexity(Op1); 6063 6064 /// Orders the operands of the compare so that they are listed from most 6065 /// complex to least complex. This puts constants before unary operators, 6066 /// before binary operators. 6067 if (Op0Cplxity < Op1Cplxity || 6068 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) { 6069 I.swapOperands(); 6070 std::swap(Op0, Op1); 6071 Changed = true; 6072 } 6073 6074 if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q)) 6075 return replaceInstUsesWith(I, V); 6076 6077 // Comparing -val or val with non-zero is the same as just comparing val 6078 // ie, abs(val) != 0 -> val != 0 6079 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) { 6080 Value *Cond, *SelectTrue, *SelectFalse; 6081 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue), 6082 m_Value(SelectFalse)))) { 6083 if (Value *V = dyn_castNegVal(SelectTrue)) { 6084 if (V == SelectFalse) 6085 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 6086 } 6087 else if (Value *V = dyn_castNegVal(SelectFalse)) { 6088 if (V == SelectTrue) 6089 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 6090 } 6091 } 6092 } 6093 6094 if (Op0->getType()->isIntOrIntVectorTy(1)) 6095 if (Instruction *Res = canonicalizeICmpBool(I, Builder)) 6096 return Res; 6097 6098 if (Instruction *Res = canonicalizeCmpWithConstant(I)) 6099 return Res; 6100 6101 if (Instruction *Res = canonicalizeICmpPredicate(I)) 6102 return Res; 6103 6104 if (Instruction *Res = foldICmpWithConstant(I)) 6105 return Res; 6106 6107 if (Instruction *Res = foldICmpWithDominatingICmp(I)) 6108 return Res; 6109 6110 if (Instruction *Res = foldICmpUsingBoolRange(I, Builder)) 6111 return Res; 6112 6113 if (Instruction *Res = foldICmpUsingKnownBits(I)) 6114 return Res; 6115 6116 // Test if the ICmpInst instruction is used exclusively by a select as 6117 // part of a minimum or maximum operation. If so, refrain from doing 6118 // any other folding. This helps out other analyses which understand 6119 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 6120 // and CodeGen. And in this case, at least one of the comparison 6121 // operands has at least one user besides the compare (the select), 6122 // which would often largely negate the benefit of folding anyway. 6123 // 6124 // Do the same for the other patterns recognized by matchSelectPattern. 6125 if (I.hasOneUse()) 6126 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) { 6127 Value *A, *B; 6128 SelectPatternResult SPR = matchSelectPattern(SI, A, B); 6129 if (SPR.Flavor != SPF_UNKNOWN) 6130 return nullptr; 6131 } 6132 6133 // Do this after checking for min/max to prevent infinite looping. 6134 if (Instruction *Res = foldICmpWithZero(I)) 6135 return Res; 6136 6137 // FIXME: We only do this after checking for min/max to prevent infinite 6138 // looping caused by a reverse canonicalization of these patterns for min/max. 6139 // FIXME: The organization of folds is a mess. These would naturally go into 6140 // canonicalizeCmpWithConstant(), but we can't move all of the above folds 6141 // down here after the min/max restriction. 6142 ICmpInst::Predicate Pred = I.getPredicate(); 6143 const APInt *C; 6144 if (match(Op1, m_APInt(C))) { 6145 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set 6146 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) { 6147 Constant *Zero = Constant::getNullValue(Op0->getType()); 6148 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero); 6149 } 6150 6151 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear 6152 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) { 6153 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType()); 6154 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes); 6155 } 6156 } 6157 6158 // The folds in here may rely on wrapping flags and special constants, so 6159 // they can break up min/max idioms in some cases but not seemingly similar 6160 // patterns. 6161 // FIXME: It may be possible to enhance select folding to make this 6162 // unnecessary. It may also be moot if we canonicalize to min/max 6163 // intrinsics. 6164 if (Instruction *Res = foldICmpBinOp(I, Q)) 6165 return Res; 6166 6167 if (Instruction *Res = foldICmpInstWithConstant(I)) 6168 return Res; 6169 6170 // Try to match comparison as a sign bit test. Intentionally do this after 6171 // foldICmpInstWithConstant() to potentially let other folds to happen first. 6172 if (Instruction *New = foldSignBitTest(I)) 6173 return New; 6174 6175 if (Instruction *Res = foldICmpInstWithConstantNotInt(I)) 6176 return Res; 6177 6178 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'. 6179 if (auto *GEP = dyn_cast<GEPOperator>(Op0)) 6180 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I)) 6181 return NI; 6182 if (auto *GEP = dyn_cast<GEPOperator>(Op1)) 6183 if (Instruction *NI = foldGEPICmp(GEP, Op0, I.getSwappedPredicate(), I)) 6184 return NI; 6185 6186 if (auto *SI = dyn_cast<SelectInst>(Op0)) 6187 if (Instruction *NI = foldSelectICmp(I.getPredicate(), SI, Op1, I)) 6188 return NI; 6189 if (auto *SI = dyn_cast<SelectInst>(Op1)) 6190 if (Instruction *NI = foldSelectICmp(I.getSwappedPredicate(), SI, Op0, I)) 6191 return NI; 6192 6193 // Try to optimize equality comparisons against alloca-based pointers. 6194 if (Op0->getType()->isPointerTy() && I.isEquality()) { 6195 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?"); 6196 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0))) 6197 if (Instruction *New = foldAllocaCmp(I, Alloca)) 6198 return New; 6199 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1))) 6200 if (Instruction *New = foldAllocaCmp(I, Alloca)) 6201 return New; 6202 } 6203 6204 if (Instruction *Res = foldICmpBitCast(I)) 6205 return Res; 6206 6207 // TODO: Hoist this above the min/max bailout. 6208 if (Instruction *R = foldICmpWithCastOp(I)) 6209 return R; 6210 6211 if (Instruction *Res = foldICmpWithMinMax(I)) 6212 return Res; 6213 6214 { 6215 Value *A, *B; 6216 // Transform (A & ~B) == 0 --> (A & B) != 0 6217 // and (A & ~B) != 0 --> (A & B) == 0 6218 // if A is a power of 2. 6219 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) && 6220 match(Op1, m_Zero()) && 6221 isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality()) 6222 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B), 6223 Op1); 6224 6225 // ~X < ~Y --> Y < X 6226 // ~X < C --> X > ~C 6227 if (match(Op0, m_Not(m_Value(A)))) { 6228 if (match(Op1, m_Not(m_Value(B)))) 6229 return new ICmpInst(I.getPredicate(), B, A); 6230 6231 const APInt *C; 6232 if (match(Op1, m_APInt(C))) 6233 return new ICmpInst(I.getSwappedPredicate(), A, 6234 ConstantInt::get(Op1->getType(), ~(*C))); 6235 } 6236 6237 Instruction *AddI = nullptr; 6238 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B), 6239 m_Instruction(AddI))) && 6240 isa<IntegerType>(A->getType())) { 6241 Value *Result; 6242 Constant *Overflow; 6243 // m_UAddWithOverflow can match patterns that do not include an explicit 6244 // "add" instruction, so check the opcode of the matched op. 6245 if (AddI->getOpcode() == Instruction::Add && 6246 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, A, B, *AddI, 6247 Result, Overflow)) { 6248 replaceInstUsesWith(*AddI, Result); 6249 eraseInstFromFunction(*AddI); 6250 return replaceInstUsesWith(I, Overflow); 6251 } 6252 } 6253 6254 // (zext a) * (zext b) --> llvm.umul.with.overflow. 6255 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 6256 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this)) 6257 return R; 6258 } 6259 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 6260 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this)) 6261 return R; 6262 } 6263 } 6264 6265 if (Instruction *Res = foldICmpEquality(I)) 6266 return Res; 6267 6268 if (Instruction *Res = foldICmpOfUAddOv(I)) 6269 return Res; 6270 6271 // The 'cmpxchg' instruction returns an aggregate containing the old value and 6272 // an i1 which indicates whether or not we successfully did the swap. 6273 // 6274 // Replace comparisons between the old value and the expected value with the 6275 // indicator that 'cmpxchg' returns. 6276 // 6277 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to 6278 // spuriously fail. In those cases, the old value may equal the expected 6279 // value but it is possible for the swap to not occur. 6280 if (I.getPredicate() == ICmpInst::ICMP_EQ) 6281 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0)) 6282 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand())) 6283 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 && 6284 !ACXI->isWeak()) 6285 return ExtractValueInst::Create(ACXI, 1); 6286 6287 { 6288 Value *X; 6289 const APInt *C; 6290 // icmp X+Cst, X 6291 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X) 6292 return foldICmpAddOpConst(X, *C, I.getPredicate()); 6293 6294 // icmp X, X+Cst 6295 if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X) 6296 return foldICmpAddOpConst(X, *C, I.getSwappedPredicate()); 6297 } 6298 6299 if (Instruction *Res = foldICmpWithHighBitMask(I, Builder)) 6300 return Res; 6301 6302 if (I.getType()->isVectorTy()) 6303 if (Instruction *Res = foldVectorCmp(I, Builder)) 6304 return Res; 6305 6306 if (Instruction *Res = foldICmpInvariantGroup(I)) 6307 return Res; 6308 6309 if (Instruction *Res = foldReductionIdiom(I, Builder, DL)) 6310 return Res; 6311 6312 return Changed ? &I : nullptr; 6313 } 6314 6315 /// Fold fcmp ([us]itofp x, cst) if possible. 6316 Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I, 6317 Instruction *LHSI, 6318 Constant *RHSC) { 6319 if (!isa<ConstantFP>(RHSC)) return nullptr; 6320 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); 6321 6322 // Get the width of the mantissa. We don't want to hack on conversions that 6323 // might lose information from the integer, e.g. "i64 -> float" 6324 int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); 6325 if (MantissaWidth == -1) return nullptr; // Unknown. 6326 6327 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); 6328 6329 bool LHSUnsigned = isa<UIToFPInst>(LHSI); 6330 6331 if (I.isEquality()) { 6332 FCmpInst::Predicate P = I.getPredicate(); 6333 bool IsExact = false; 6334 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned); 6335 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact); 6336 6337 // If the floating point constant isn't an integer value, we know if we will 6338 // ever compare equal / not equal to it. 6339 if (!IsExact) { 6340 // TODO: Can never be -0.0 and other non-representable values 6341 APFloat RHSRoundInt(RHS); 6342 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven); 6343 if (RHS != RHSRoundInt) { 6344 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ) 6345 return replaceInstUsesWith(I, Builder.getFalse()); 6346 6347 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE); 6348 return replaceInstUsesWith(I, Builder.getTrue()); 6349 } 6350 } 6351 6352 // TODO: If the constant is exactly representable, is it always OK to do 6353 // equality compares as integer? 6354 } 6355 6356 // Check to see that the input is converted from an integer type that is small 6357 // enough that preserves all bits. TODO: check here for "known" sign bits. 6358 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. 6359 unsigned InputSize = IntTy->getScalarSizeInBits(); 6360 6361 // Following test does NOT adjust InputSize downwards for signed inputs, 6362 // because the most negative value still requires all the mantissa bits 6363 // to distinguish it from one less than that value. 6364 if ((int)InputSize > MantissaWidth) { 6365 // Conversion would lose accuracy. Check if loss can impact comparison. 6366 int Exp = ilogb(RHS); 6367 if (Exp == APFloat::IEK_Inf) { 6368 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics())); 6369 if (MaxExponent < (int)InputSize - !LHSUnsigned) 6370 // Conversion could create infinity. 6371 return nullptr; 6372 } else { 6373 // Note that if RHS is zero or NaN, then Exp is negative 6374 // and first condition is trivially false. 6375 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned) 6376 // Conversion could affect comparison. 6377 return nullptr; 6378 } 6379 } 6380 6381 // Otherwise, we can potentially simplify the comparison. We know that it 6382 // will always come through as an integer value and we know the constant is 6383 // not a NAN (it would have been previously simplified). 6384 assert(!RHS.isNaN() && "NaN comparison not already folded!"); 6385 6386 ICmpInst::Predicate Pred; 6387 switch (I.getPredicate()) { 6388 default: llvm_unreachable("Unexpected predicate!"); 6389 case FCmpInst::FCMP_UEQ: 6390 case FCmpInst::FCMP_OEQ: 6391 Pred = ICmpInst::ICMP_EQ; 6392 break; 6393 case FCmpInst::FCMP_UGT: 6394 case FCmpInst::FCMP_OGT: 6395 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; 6396 break; 6397 case FCmpInst::FCMP_UGE: 6398 case FCmpInst::FCMP_OGE: 6399 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; 6400 break; 6401 case FCmpInst::FCMP_ULT: 6402 case FCmpInst::FCMP_OLT: 6403 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; 6404 break; 6405 case FCmpInst::FCMP_ULE: 6406 case FCmpInst::FCMP_OLE: 6407 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; 6408 break; 6409 case FCmpInst::FCMP_UNE: 6410 case FCmpInst::FCMP_ONE: 6411 Pred = ICmpInst::ICMP_NE; 6412 break; 6413 case FCmpInst::FCMP_ORD: 6414 return replaceInstUsesWith(I, Builder.getTrue()); 6415 case FCmpInst::FCMP_UNO: 6416 return replaceInstUsesWith(I, Builder.getFalse()); 6417 } 6418 6419 // Now we know that the APFloat is a normal number, zero or inf. 6420 6421 // See if the FP constant is too large for the integer. For example, 6422 // comparing an i8 to 300.0. 6423 unsigned IntWidth = IntTy->getScalarSizeInBits(); 6424 6425 if (!LHSUnsigned) { 6426 // If the RHS value is > SignedMax, fold the comparison. This handles +INF 6427 // and large values. 6428 APFloat SMax(RHS.getSemantics()); 6429 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, 6430 APFloat::rmNearestTiesToEven); 6431 if (SMax < RHS) { // smax < 13123.0 6432 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || 6433 Pred == ICmpInst::ICMP_SLE) 6434 return replaceInstUsesWith(I, Builder.getTrue()); 6435 return replaceInstUsesWith(I, Builder.getFalse()); 6436 } 6437 } else { 6438 // If the RHS value is > UnsignedMax, fold the comparison. This handles 6439 // +INF and large values. 6440 APFloat UMax(RHS.getSemantics()); 6441 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, 6442 APFloat::rmNearestTiesToEven); 6443 if (UMax < RHS) { // umax < 13123.0 6444 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || 6445 Pred == ICmpInst::ICMP_ULE) 6446 return replaceInstUsesWith(I, Builder.getTrue()); 6447 return replaceInstUsesWith(I, Builder.getFalse()); 6448 } 6449 } 6450 6451 if (!LHSUnsigned) { 6452 // See if the RHS value is < SignedMin. 6453 APFloat SMin(RHS.getSemantics()); 6454 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, 6455 APFloat::rmNearestTiesToEven); 6456 if (SMin > RHS) { // smin > 12312.0 6457 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || 6458 Pred == ICmpInst::ICMP_SGE) 6459 return replaceInstUsesWith(I, Builder.getTrue()); 6460 return replaceInstUsesWith(I, Builder.getFalse()); 6461 } 6462 } else { 6463 // See if the RHS value is < UnsignedMin. 6464 APFloat UMin(RHS.getSemantics()); 6465 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false, 6466 APFloat::rmNearestTiesToEven); 6467 if (UMin > RHS) { // umin > 12312.0 6468 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT || 6469 Pred == ICmpInst::ICMP_UGE) 6470 return replaceInstUsesWith(I, Builder.getTrue()); 6471 return replaceInstUsesWith(I, Builder.getFalse()); 6472 } 6473 } 6474 6475 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or 6476 // [0, UMAX], but it may still be fractional. See if it is fractional by 6477 // casting the FP value to the integer value and back, checking for equality. 6478 // Don't do this for zero, because -0.0 is not fractional. 6479 Constant *RHSInt = LHSUnsigned 6480 ? ConstantExpr::getFPToUI(RHSC, IntTy) 6481 : ConstantExpr::getFPToSI(RHSC, IntTy); 6482 if (!RHS.isZero()) { 6483 bool Equal = LHSUnsigned 6484 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC 6485 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; 6486 if (!Equal) { 6487 // If we had a comparison against a fractional value, we have to adjust 6488 // the compare predicate and sometimes the value. RHSC is rounded towards 6489 // zero at this point. 6490 switch (Pred) { 6491 default: llvm_unreachable("Unexpected integer comparison!"); 6492 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true 6493 return replaceInstUsesWith(I, Builder.getTrue()); 6494 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false 6495 return replaceInstUsesWith(I, Builder.getFalse()); 6496 case ICmpInst::ICMP_ULE: 6497 // (float)int <= 4.4 --> int <= 4 6498 // (float)int <= -4.4 --> false 6499 if (RHS.isNegative()) 6500 return replaceInstUsesWith(I, Builder.getFalse()); 6501 break; 6502 case ICmpInst::ICMP_SLE: 6503 // (float)int <= 4.4 --> int <= 4 6504 // (float)int <= -4.4 --> int < -4 6505 if (RHS.isNegative()) 6506 Pred = ICmpInst::ICMP_SLT; 6507 break; 6508 case ICmpInst::ICMP_ULT: 6509 // (float)int < -4.4 --> false 6510 // (float)int < 4.4 --> int <= 4 6511 if (RHS.isNegative()) 6512 return replaceInstUsesWith(I, Builder.getFalse()); 6513 Pred = ICmpInst::ICMP_ULE; 6514 break; 6515 case ICmpInst::ICMP_SLT: 6516 // (float)int < -4.4 --> int < -4 6517 // (float)int < 4.4 --> int <= 4 6518 if (!RHS.isNegative()) 6519 Pred = ICmpInst::ICMP_SLE; 6520 break; 6521 case ICmpInst::ICMP_UGT: 6522 // (float)int > 4.4 --> int > 4 6523 // (float)int > -4.4 --> true 6524 if (RHS.isNegative()) 6525 return replaceInstUsesWith(I, Builder.getTrue()); 6526 break; 6527 case ICmpInst::ICMP_SGT: 6528 // (float)int > 4.4 --> int > 4 6529 // (float)int > -4.4 --> int >= -4 6530 if (RHS.isNegative()) 6531 Pred = ICmpInst::ICMP_SGE; 6532 break; 6533 case ICmpInst::ICMP_UGE: 6534 // (float)int >= -4.4 --> true 6535 // (float)int >= 4.4 --> int > 4 6536 if (RHS.isNegative()) 6537 return replaceInstUsesWith(I, Builder.getTrue()); 6538 Pred = ICmpInst::ICMP_UGT; 6539 break; 6540 case ICmpInst::ICMP_SGE: 6541 // (float)int >= -4.4 --> int >= -4 6542 // (float)int >= 4.4 --> int > 4 6543 if (!RHS.isNegative()) 6544 Pred = ICmpInst::ICMP_SGT; 6545 break; 6546 } 6547 } 6548 } 6549 6550 // Lower this FP comparison into an appropriate integer version of the 6551 // comparison. 6552 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); 6553 } 6554 6555 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary. 6556 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, 6557 Constant *RHSC) { 6558 // When C is not 0.0 and infinities are not allowed: 6559 // (C / X) < 0.0 is a sign-bit test of X 6560 // (C / X) < 0.0 --> X < 0.0 (if C is positive) 6561 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate) 6562 // 6563 // Proof: 6564 // Multiply (C / X) < 0.0 by X * X / C. 6565 // - X is non zero, if it is the flag 'ninf' is violated. 6566 // - C defines the sign of X * X * C. Thus it also defines whether to swap 6567 // the predicate. C is also non zero by definition. 6568 // 6569 // Thus X * X / C is non zero and the transformation is valid. [qed] 6570 6571 FCmpInst::Predicate Pred = I.getPredicate(); 6572 6573 // Check that predicates are valid. 6574 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) && 6575 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE)) 6576 return nullptr; 6577 6578 // Check that RHS operand is zero. 6579 if (!match(RHSC, m_AnyZeroFP())) 6580 return nullptr; 6581 6582 // Check fastmath flags ('ninf'). 6583 if (!LHSI->hasNoInfs() || !I.hasNoInfs()) 6584 return nullptr; 6585 6586 // Check the properties of the dividend. It must not be zero to avoid a 6587 // division by zero (see Proof). 6588 const APFloat *C; 6589 if (!match(LHSI->getOperand(0), m_APFloat(C))) 6590 return nullptr; 6591 6592 if (C->isZero()) 6593 return nullptr; 6594 6595 // Get swapped predicate if necessary. 6596 if (C->isNegative()) 6597 Pred = I.getSwappedPredicate(); 6598 6599 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I); 6600 } 6601 6602 /// Optimize fabs(X) compared with zero. 6603 static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) { 6604 Value *X; 6605 if (!match(I.getOperand(0), m_FAbs(m_Value(X))) || 6606 !match(I.getOperand(1), m_PosZeroFP())) 6607 return nullptr; 6608 6609 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) { 6610 I->setPredicate(P); 6611 return IC.replaceOperand(*I, 0, X); 6612 }; 6613 6614 switch (I.getPredicate()) { 6615 case FCmpInst::FCMP_UGE: 6616 case FCmpInst::FCMP_OLT: 6617 // fabs(X) >= 0.0 --> true 6618 // fabs(X) < 0.0 --> false 6619 llvm_unreachable("fcmp should have simplified"); 6620 6621 case FCmpInst::FCMP_OGT: 6622 // fabs(X) > 0.0 --> X != 0.0 6623 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X); 6624 6625 case FCmpInst::FCMP_UGT: 6626 // fabs(X) u> 0.0 --> X u!= 0.0 6627 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X); 6628 6629 case FCmpInst::FCMP_OLE: 6630 // fabs(X) <= 0.0 --> X == 0.0 6631 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X); 6632 6633 case FCmpInst::FCMP_ULE: 6634 // fabs(X) u<= 0.0 --> X u== 0.0 6635 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X); 6636 6637 case FCmpInst::FCMP_OGE: 6638 // fabs(X) >= 0.0 --> !isnan(X) 6639 assert(!I.hasNoNaNs() && "fcmp should have simplified"); 6640 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X); 6641 6642 case FCmpInst::FCMP_ULT: 6643 // fabs(X) u< 0.0 --> isnan(X) 6644 assert(!I.hasNoNaNs() && "fcmp should have simplified"); 6645 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X); 6646 6647 case FCmpInst::FCMP_OEQ: 6648 case FCmpInst::FCMP_UEQ: 6649 case FCmpInst::FCMP_ONE: 6650 case FCmpInst::FCMP_UNE: 6651 case FCmpInst::FCMP_ORD: 6652 case FCmpInst::FCMP_UNO: 6653 // Look through the fabs() because it doesn't change anything but the sign. 6654 // fabs(X) == 0.0 --> X == 0.0, 6655 // fabs(X) != 0.0 --> X != 0.0 6656 // isnan(fabs(X)) --> isnan(X) 6657 // !isnan(fabs(X) --> !isnan(X) 6658 return replacePredAndOp0(&I, I.getPredicate(), X); 6659 6660 default: 6661 return nullptr; 6662 } 6663 } 6664 6665 static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) { 6666 CmpInst::Predicate Pred = I.getPredicate(); 6667 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 6668 6669 // Canonicalize fneg as Op1. 6670 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) { 6671 std::swap(Op0, Op1); 6672 Pred = I.getSwappedPredicate(); 6673 } 6674 6675 if (!match(Op1, m_FNeg(m_Specific(Op0)))) 6676 return nullptr; 6677 6678 // Replace the negated operand with 0.0: 6679 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0 6680 Constant *Zero = ConstantFP::getNullValue(Op0->getType()); 6681 return new FCmpInst(Pred, Op0, Zero, "", &I); 6682 } 6683 6684 Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) { 6685 bool Changed = false; 6686 6687 /// Orders the operands of the compare so that they are listed from most 6688 /// complex to least complex. This puts constants before unary operators, 6689 /// before binary operators. 6690 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 6691 I.swapOperands(); 6692 Changed = true; 6693 } 6694 6695 const CmpInst::Predicate Pred = I.getPredicate(); 6696 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 6697 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(), 6698 SQ.getWithInstruction(&I))) 6699 return replaceInstUsesWith(I, V); 6700 6701 // Simplify 'fcmp pred X, X' 6702 Type *OpType = Op0->getType(); 6703 assert(OpType == Op1->getType() && "fcmp with different-typed operands?"); 6704 if (Op0 == Op1) { 6705 switch (Pred) { 6706 default: break; 6707 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) 6708 case FCmpInst::FCMP_ULT: // True if unordered or less than 6709 case FCmpInst::FCMP_UGT: // True if unordered or greater than 6710 case FCmpInst::FCMP_UNE: // True if unordered or not equal 6711 // Canonicalize these to be 'fcmp uno %X, 0.0'. 6712 I.setPredicate(FCmpInst::FCMP_UNO); 6713 I.setOperand(1, Constant::getNullValue(OpType)); 6714 return &I; 6715 6716 case FCmpInst::FCMP_ORD: // True if ordered (no nans) 6717 case FCmpInst::FCMP_OEQ: // True if ordered and equal 6718 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal 6719 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal 6720 // Canonicalize these to be 'fcmp ord %X, 0.0'. 6721 I.setPredicate(FCmpInst::FCMP_ORD); 6722 I.setOperand(1, Constant::getNullValue(OpType)); 6723 return &I; 6724 } 6725 } 6726 6727 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand, 6728 // then canonicalize the operand to 0.0. 6729 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) { 6730 if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, &TLI)) 6731 return replaceOperand(I, 0, ConstantFP::getNullValue(OpType)); 6732 6733 if (!match(Op1, m_PosZeroFP()) && isKnownNeverNaN(Op1, &TLI)) 6734 return replaceOperand(I, 1, ConstantFP::getNullValue(OpType)); 6735 } 6736 6737 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y 6738 Value *X, *Y; 6739 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) 6740 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I); 6741 6742 if (Instruction *R = foldFCmpFNegCommonOp(I)) 6743 return R; 6744 6745 // Test if the FCmpInst instruction is used exclusively by a select as 6746 // part of a minimum or maximum operation. If so, refrain from doing 6747 // any other folding. This helps out other analyses which understand 6748 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 6749 // and CodeGen. And in this case, at least one of the comparison 6750 // operands has at least one user besides the compare (the select), 6751 // which would often largely negate the benefit of folding anyway. 6752 if (I.hasOneUse()) 6753 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) { 6754 Value *A, *B; 6755 SelectPatternResult SPR = matchSelectPattern(SI, A, B); 6756 if (SPR.Flavor != SPF_UNKNOWN) 6757 return nullptr; 6758 } 6759 6760 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0: 6761 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0 6762 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP())) 6763 return replaceOperand(I, 1, ConstantFP::getNullValue(OpType)); 6764 6765 // Handle fcmp with instruction LHS and constant RHS. 6766 Instruction *LHSI; 6767 Constant *RHSC; 6768 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) { 6769 switch (LHSI->getOpcode()) { 6770 case Instruction::PHI: 6771 // Only fold fcmp into the PHI if the phi and fcmp are in the same 6772 // block. If in the same block, we're encouraging jump threading. If 6773 // not, we are just pessimizing the code by making an i1 phi. 6774 if (LHSI->getParent() == I.getParent()) 6775 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI))) 6776 return NV; 6777 break; 6778 case Instruction::SIToFP: 6779 case Instruction::UIToFP: 6780 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC)) 6781 return NV; 6782 break; 6783 case Instruction::FDiv: 6784 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC)) 6785 return NV; 6786 break; 6787 case Instruction::Load: 6788 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) 6789 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 6790 if (Instruction *Res = foldCmpLoadFromIndexedGlobal( 6791 cast<LoadInst>(LHSI), GEP, GV, I)) 6792 return Res; 6793 break; 6794 } 6795 } 6796 6797 if (Instruction *R = foldFabsWithFcmpZero(I, *this)) 6798 return R; 6799 6800 if (match(Op0, m_FNeg(m_Value(X)))) { 6801 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C 6802 Constant *C; 6803 if (match(Op1, m_Constant(C))) { 6804 Constant *NegC = ConstantExpr::getFNeg(C); 6805 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I); 6806 } 6807 } 6808 6809 if (match(Op0, m_FPExt(m_Value(X)))) { 6810 // fcmp (fpext X), (fpext Y) -> fcmp X, Y 6811 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType()) 6812 return new FCmpInst(Pred, X, Y, "", &I); 6813 6814 const APFloat *C; 6815 if (match(Op1, m_APFloat(C))) { 6816 const fltSemantics &FPSem = 6817 X->getType()->getScalarType()->getFltSemantics(); 6818 bool Lossy; 6819 APFloat TruncC = *C; 6820 TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy); 6821 6822 if (Lossy) { 6823 // X can't possibly equal the higher-precision constant, so reduce any 6824 // equality comparison. 6825 // TODO: Other predicates can be handled via getFCmpCode(). 6826 switch (Pred) { 6827 case FCmpInst::FCMP_OEQ: 6828 // X is ordered and equal to an impossible constant --> false 6829 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 6830 case FCmpInst::FCMP_ONE: 6831 // X is ordered and not equal to an impossible constant --> ordered 6832 return new FCmpInst(FCmpInst::FCMP_ORD, X, 6833 ConstantFP::getNullValue(X->getType())); 6834 case FCmpInst::FCMP_UEQ: 6835 // X is unordered or equal to an impossible constant --> unordered 6836 return new FCmpInst(FCmpInst::FCMP_UNO, X, 6837 ConstantFP::getNullValue(X->getType())); 6838 case FCmpInst::FCMP_UNE: 6839 // X is unordered or not equal to an impossible constant --> true 6840 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 6841 default: 6842 break; 6843 } 6844 } 6845 6846 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless 6847 // Avoid lossy conversions and denormals. 6848 // Zero is a special case that's OK to convert. 6849 APFloat Fabs = TruncC; 6850 Fabs.clearSign(); 6851 if (!Lossy && 6852 (!(Fabs < APFloat::getSmallestNormalized(FPSem)) || Fabs.isZero())) { 6853 Constant *NewC = ConstantFP::get(X->getType(), TruncC); 6854 return new FCmpInst(Pred, X, NewC, "", &I); 6855 } 6856 } 6857 } 6858 6859 // Convert a sign-bit test of an FP value into a cast and integer compare. 6860 // TODO: Simplify if the copysign constant is 0.0 or NaN. 6861 // TODO: Handle non-zero compare constants. 6862 // TODO: Handle other predicates. 6863 const APFloat *C; 6864 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C), 6865 m_Value(X)))) && 6866 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) { 6867 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits()); 6868 if (auto *VecTy = dyn_cast<VectorType>(OpType)) 6869 IntType = VectorType::get(IntType, VecTy->getElementCount()); 6870 6871 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0 6872 if (Pred == FCmpInst::FCMP_OLT) { 6873 Value *IntX = Builder.CreateBitCast(X, IntType); 6874 return new ICmpInst(ICmpInst::ICMP_SLT, IntX, 6875 ConstantInt::getNullValue(IntType)); 6876 } 6877 } 6878 6879 if (I.getType()->isVectorTy()) 6880 if (Instruction *Res = foldVectorCmp(I, Builder)) 6881 return Res; 6882 6883 return Changed ? &I : nullptr; 6884 } 6885