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