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