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