32 #define DEBUG_TYPE "instcombine" 35 STATISTIC(NumSel,
"Number of select opts");
41 const APInt &In2,
bool IsSigned =
false) {
44 Result = In1.
sadd_ov(In2, Overflow);
46 Result = In1.
uadd_ov(In2, Overflow);
54 const APInt &In2,
bool IsSigned =
false) {
57 Result = In1.
ssub_ov(In2, Overflow);
59 Result = In1.
usub_ov(In2, Overflow);
67 for (
auto *U : I.
users())
68 if (isa<BranchInst>(U))
135 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
141 Max = Known.
One|UnknownBits;
143 if (UnknownBits.isNegative()) {
157 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
163 Max = Known.
One|UnknownBits;
179 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
184 if (ArrayElementCount > MaxArraySizeForCombine)
205 if (!Idx)
return nullptr;
208 if ((
unsigned)IdxVal != IdxVal)
return nullptr;
210 if (
StructType *STy = dyn_cast<StructType>(EltTy))
211 EltTy = STy->getElementType(IdxVal);
212 else if (
ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
213 if (IdxVal >= ATy->getNumElements())
return nullptr;
214 EltTy = ATy->getElementType();
222 enum { Overdefined = -3, Undefined = -2 };
231 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
235 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
243 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
248 uint64_t MagicBitvector = 0;
252 for (
unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
254 if (!Elt)
return nullptr;
257 if (!LaterIndices.
empty())
265 CompareRHS, DL, &TLI);
267 if (isa<UndefValue>(C)) {
270 if (TrueRangeEnd == (
int)i-1)
272 if (FalseRangeEnd == (
int)i-1)
279 if (!isa<ConstantInt>(C))
return nullptr;
283 bool IsTrueForElt = !cast<ConstantInt>(
C)->
isZero();
288 if (FirstTrueElement == Undefined)
289 FirstTrueElement = TrueRangeEnd = i;
292 if (SecondTrueElement == Undefined)
293 SecondTrueElement = i;
295 SecondTrueElement = Overdefined;
298 if (TrueRangeEnd == (
int)i-1)
301 TrueRangeEnd = Overdefined;
305 if (FirstFalseElement == Undefined)
306 FirstFalseElement = FalseRangeEnd = i;
309 if (SecondFalseElement == Undefined)
310 SecondFalseElement = i;
312 SecondFalseElement = Overdefined;
315 if (FalseRangeEnd == (
int)i-1)
318 FalseRangeEnd = Overdefined;
323 if (i < 64 && IsTrueForElt)
324 MagicBitvector |= 1ULL << i;
329 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
330 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
331 FalseRangeEnd == Overdefined)
346 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
351 if (SecondTrueElement != Overdefined) {
353 if (FirstTrueElement == Undefined)
354 return replaceInstUsesWith(ICI, Builder.getFalse());
359 if (SecondTrueElement == Undefined)
363 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
365 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
366 return BinaryOperator::CreateOr(C1, C2);
371 if (SecondFalseElement != Overdefined) {
373 if (FirstFalseElement == Undefined)
374 return replaceInstUsesWith(ICI, Builder.getTrue());
379 if (SecondFalseElement == Undefined)
383 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
385 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
386 return BinaryOperator::CreateAnd(C1, C2);
391 if (TrueRangeEnd != Overdefined) {
392 assert(TrueRangeEnd != FirstTrueElement &&
"Should emit single compare");
395 if (FirstTrueElement) {
397 Idx = Builder.CreateAdd(Idx, Offs);
401 TrueRangeEnd-FirstTrueElement+1);
406 if (FalseRangeEnd != Overdefined) {
407 assert(FalseRangeEnd != FirstFalseElement &&
"Should emit single compare");
409 if (FirstFalseElement) {
411 Idx = Builder.CreateAdd(Idx, Offs);
415 FalseRangeEnd-FirstFalseElement);
428 if (ArrayElementCount <= Idx->
getType()->getIntegerBitWidth())
431 Ty = DL.getSmallestLegalIntType(Init->
getContext(), ArrayElementCount);
434 Value *V = Builder.CreateIntCast(Idx, Ty,
false);
465 for (i = 1; i != e; ++i, ++GTI) {
468 if (CI->isZero())
continue;
475 Offset += Size*CI->getSExtValue();
485 if (i == e)
return nullptr;
493 for (++i, ++GTI; i != e; ++i, ++GTI) {
495 if (!CI)
return nullptr;
498 if (CI->
isZero())
continue;
527 VariableScale =
SignExtend64(VariableScale, IntPtrWidth);
533 int64_t NewOffs = Offset / (int64_t)VariableScale;
534 if (Offset != NewOffs*(int64_t)VariableScale)
538 if (VariableIdx->
getType() != IntPtrTy)
562 while (!WorkList.
empty()) {
565 while (!WorkList.
empty()) {
566 if (Explored.
size() >= 100)
571 if (Explored.
count(V) != 0) {
576 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
577 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
582 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
584 if (!CI->isNoopCast(DL))
587 if (Explored.
count(CI->getOperand(0)) == 0)
591 if (
auto *GEP = dyn_cast<GEPOperator>(V)) {
603 if (WorkList.
back() == V) {
609 if (
auto *PN = dyn_cast<PHINode>(V)) {
611 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
619 for (
auto *PN : PHIs)
620 for (
Value *
Op : PN->incoming_values())
628 for (
Value *Val : Explored) {
634 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
635 Explored.count(PHI) == 0)
638 if (PHI->getParent() == Inst->getParent())
648 bool Before =
true) {
649 if (
auto *PHI = dyn_cast<PHINode>(V)) {
650 Builder.
SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
653 if (
auto *
I = dyn_cast<Instruction>(V)) {
655 I = &*std::next(
I->getIterator());
659 if (
auto *A = dyn_cast<Argument>(V)) {
661 BasicBlock &Entry = A->getParent()->getEntryBlock();
667 assert(isa<Constant>(V) &&
"Setting insertion point for unknown value!");
689 for (
Value *Val : Explored) {
694 if (
auto *PHI = dyn_cast<PHINode>(Val))
695 NewInsts[PHI] =
PHINode::Create(IndexType, PHI->getNumIncomingValues(),
696 PHI->getName() +
".idx", PHI);
701 for (
Value *Val : Explored) {
703 if (NewInsts.
find(Val) != NewInsts.
end())
706 if (
auto *CI = dyn_cast<CastInst>(Val)) {
707 NewInsts[CI] = NewInsts[CI->getOperand(0)];
710 if (
auto *GEP = dyn_cast<GEPOperator>(Val)) {
717 NewInsts[GEP->
getOperand(0)]->getType()->getScalarSizeInBits()) {
718 Index = Builder.CreateSExtOrTrunc(
719 Index, NewInsts[GEP->
getOperand(0)]->getType(),
724 if (isa<ConstantInt>(
Op) && cast<ConstantInt>(
Op)->
isZero())
727 NewInsts[
GEP] = Builder.CreateNSWAdd(
731 if (isa<PHINode>(Val))
738 for (
Value *Val : Explored) {
743 if (
auto *PHI = dyn_cast<PHINode>(Val)) {
745 for (
unsigned I = 0,
E = PHI->getNumIncomingValues();
I <
E; ++
I) {
746 Value *NewIncoming = PHI->getIncomingValue(
I);
748 if (NewInsts.
find(NewIncoming) != NewInsts.
end())
749 NewIncoming = NewInsts[NewIncoming];
751 NewPhi->
addIncoming(NewIncoming, PHI->getIncomingBlock(
I));
756 for (
Value *Val : Explored) {
765 Value *NewBase = Base;
767 NewBase = Builder.CreateBitOrPointerCast(Base, Start->
getType(),
770 Value *GEP = Builder.CreateInBoundsGEP(
774 if (!Val->getType()->isPointerTy()) {
775 Value *Cast = Builder.CreatePointerCast(GEP, Val->
getType(),
776 Val->getName() +
".conv");
782 return NewInsts[Start];
788 static std::pair<Value *, Value *>
810 if (
auto *CI = dyn_cast<IntToPtrInst>(V)) {
811 if (!CI->isNoopCast(DL))
813 V = CI->getOperand(0);
816 if (
auto *CI = dyn_cast<PtrToIntInst>(V)) {
817 if (!CI->isNoopCast(DL))
819 V = CI->getOperand(0);
879 if (!isa<GetElementPtrInst>(RHS))
895 }
else if (
GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
898 if (PtrBase != GEPRHS->getOperand(0)) {
899 bool IndicesTheSame = GEPLHS->
getNumOperands()==GEPRHS->getNumOperands();
901 GEPRHS->getOperand(0)->getType();
904 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
905 IndicesTheSame =
false;
917 if (GEPLHS->
isInBounds() && GEPRHS->isInBounds() &&
919 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
930 if (LHSIndexTy != RHSIndexTy) {
933 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
935 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
940 return replaceInstUsesWith(I, Cmp);
951 return foldGEPICmp(GEPRHS, GEPLHS->
getOperand(0),
955 if (GEPRHS->hasAllZeroIndices())
956 return foldGEPICmp(GEPLHS, GEPRHS->
getOperand(0), Cond,
I);
958 bool GEPsInBounds = GEPLHS->
isInBounds() && GEPRHS->isInBounds();
961 unsigned NumDifferences = 0;
962 unsigned DiffOperand = 0;
963 for (
unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
964 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
966 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
971 if (NumDifferences++)
break;
976 if (NumDifferences == 0)
977 return replaceInstUsesWith(I,
980 else if (NumDifferences == 1 && GEPsInBounds) {
982 Value *RHSV = GEPRHS->getOperand(DiffOperand);
990 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->
hasOneUse()) &&
991 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1023 unsigned MaxIter = 32;
1026 for (
const Use &U : Alloca->
uses()) {
1027 if (Worklist.
size() >= MaxIter)
1032 unsigned NumCmps = 0;
1033 while (!Worklist.
empty()) {
1036 const Value *V = U->getUser();
1039 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1040 isa<SelectInst>(V)) {
1042 }
else if (isa<LoadInst>(V)) {
1045 }
else if (
const auto *
SI = dyn_cast<StoreInst>(V)) {
1047 if (
SI->getValueOperand() == U->get())
1050 }
else if (isa<ICmpInst>(V)) {
1054 }
else if (
const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1055 switch (Intrin->getIntrinsicID()) {
1068 for (
const Use &U : V->
uses()) {
1069 if (Worklist.
size() >= MaxIter)
1076 return replaceInstUsesWith(
1087 assert(!!C &&
"C should not be zero!");
1140 return new ICmpInst(Pred, LHS, RHS);
1147 bool IsAShr = isa<AShrOperator>(I.
getOperand(0));
1172 if (IsAShr && AP1 == AP2.
ashr(Shift)) {
1178 }
else if (AP1 == AP2.
lshr(Shift)) {
1186 return replaceInstUsesWith(I, TorF);
1199 return new ICmpInst(Pred, LHS, RHS);
1208 if (!AP1 && AP2TrailingZeros != 0)
1219 if (Shift > 0 && AP2.
shl(Shift) == AP1)
1225 return replaceInstUsesWith(I, TorF);
1253 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1267 unsigned NeededSignBits = CI1->
getBitWidth() - NewWidth + 1;
1278 if (U == AddWithCst)
1304 Value *TruncA = Builder.CreateTrunc(A, NewType, A->
getName() +
".trunc");
1305 Value *TruncB = Builder.CreateTrunc(B, NewType, B->
getName() +
".trunc");
1306 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB},
"sadd");
1307 Value *
Add = Builder.CreateExtractValue(Call, 0,
"sadd.result");
1308 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->
getType());
1379 assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1380 "Predecessor block does not point to successor?");
1383 if (TrueBB == FalseBB)
1412 return replaceInstUsesWith(Cmp, Builder.getFalse());
1414 return replaceInstUsesWith(Cmp, Builder.getTrue());
1457 if ((Known.
Zero | Known.
One).countLeadingOnes() >= SrcBits - DstBits) {
1481 bool TrueIfSigned =
false;
1521 if (*XorC == ~C && (C + 1).isPowerOf2())
1524 if (*XorC == C && (C + 1).isPowerOf2())
1544 if (!Shift || !Shift->
isShift())
1552 unsigned ShiftOpcode = Shift->
getOpcode();
1553 bool IsShl = ShiftOpcode == Instruction::Shl;
1556 bool CanFold =
false;
1557 if (ShiftOpcode == Instruction::Shl) {
1565 bool IsAshr = ShiftOpcode == Instruction::AShr;
1574 if (!IsAshr || (C2.
shl(*C3).
lshr(*C3) == C2)) {
1583 APInt SameAsC1 = IsShl ? NewCst.
shl(*C3) : NewCst.
lshr(*C3);
1585 if (SameAsC1 != C1) {
1598 Worklist.Add(Shift);
1660 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->
getName());
1665 if (
Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1679 unsigned UsesRemoved = 0;
1682 if (Or->hasOneUse())
1688 Value *NewOr =
nullptr;
1689 if (
auto *C = dyn_cast<Constant>(B)) {
1690 if (UsesRemoved >= 1)
1693 if (UsesRemoved >= 3)
1694 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->
getName(),
1699 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->
getName());
1713 if (
Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1721 if (
auto *LI = dyn_cast<LoadInst>(X))
1722 if (
auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1723 if (
auto *GV = dyn_cast<GlobalVariable>(GEP->
getOperand(0)))
1725 !LI->isVolatile() && isa<ConstantInt>(
Y)) {
1727 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
1737 if (Cmp.
getOperand(1) == Y && (-
C).isPowerOf2()) {
1749 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1753 Value *Trunc = Builder.CreateTrunc(X, NTy);
1779 (C + 1).isPowerOf2()) {
1801 Value *X1, *X2, *X3, *X4;
1806 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1807 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1863 if (CLog2 == TypeBits - 1) {
1891 }
else if (Cmp.
isEquality() && CIsPowerOf2) {
1902 const APInt *ShiftVal;
1904 return foldICmpShlConstConst(Cmp, Shl->
getOperand(1),
C, *ShiftVal);
1906 const APInt *ShiftAmt;
1913 if (ShiftAmt->uge(TypeBits))
1930 C.
ashr(*ShiftAmt).
shl(*ShiftAmt) ==
C) {
1940 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
1960 C.
lshr(*ShiftAmt).
shl(*ShiftAmt) ==
C) {
1969 assert(C.
ugt(0) &&
"ult 0 should have been eliminated");
1970 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
1980 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
1982 return new ICmpInst(Pred, And, LShrC);
1986 bool TrueIfSigned =
false;
1992 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
2003 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2005 DL.isLegalInteger(TypeBits - Amt)) {
2011 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2029 const APInt *ShiftVal;
2031 return foldICmpShrConstConst(Cmp, Shr->
getOperand(1),
C, *ShiftVal);
2033 const APInt *ShiftAmt;
2040 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
2041 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2044 bool IsAShr = Shr->
getOpcode() == Instruction::AShr;
2045 bool IsExact = Shr->
isExact();
2056 if (ShiftedC.
ashr(ShAmtVal) ==
C)
2061 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2063 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2071 if (ShiftedC.
lshr(ShAmtVal) ==
C)
2076 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2077 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2091 (!IsAShr && C.
shl(ShAmtVal).
lshr(ShAmtVal) ==
C)) &&
2092 "Expected icmp+shr simplify did not occur.");
2104 Value *And = Builder.CreateAnd(X, Mask, Shr->
getName() +
".mask");
2119 assert(*C2 != 0 &&
"udiv 0, X should have been simplified already.");
2125 "icmp ugt X, UINT_MAX should have been simplified already.");
2132 assert(C != 0 &&
"icmp ult X, 0 should have been simplified already.");
2162 bool DivIsSigned = Div->
getOpcode() == Instruction::SDiv;
2178 APInt Prod = C * *C2;
2183 bool ProdOV = (DivIsSigned ? Prod.
sdiv(*C2) : Prod.
udiv(*C2)) != C;
2198 int LoOverflow = 0, HiOverflow = 0;
2199 APInt LoBound, HiBound;
2204 HiOverflow = LoOverflow = ProdOV;
2210 }
else if (C2->isStrictlyPositive()) {
2213 LoBound = -(RangeSize - 1);
2214 HiBound = RangeSize;
2217 HiOverflow = LoOverflow = ProdOV;
2223 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2225 APInt DivNeg = -RangeSize;
2226 LoOverflow =
addWithOverflow(LoBound, HiBound, DivNeg,
true) ? -1 : 0;
2229 }
else if (C2->isNegative()) {
2234 LoBound = RangeSize + 1;
2235 HiBound = -RangeSize;
2236 if (HiBound == *C2) {
2243 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2245 LoOverflow =
addWithOverflow(LoBound, HiBound, RangeSize,
true) ? -1:0;
2248 LoOverflow = HiOverflow = ProdOV;
2261 if (LoOverflow && HiOverflow)
2262 return replaceInstUsesWith(Cmp, Builder.getFalse());
2271 return replaceInstUsesWith(
2272 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned,
true));
2274 if (LoOverflow && HiOverflow)
2275 return replaceInstUsesWith(Cmp, Builder.getTrue());
2278 ICmpInst::ICMP_ULT, X,
2282 ICmpInst::ICMP_UGE, X,
2284 return replaceInstUsesWith(Cmp,
2285 insertRangeTest(X, LoBound, HiBound,
2286 DivIsSigned,
false));
2289 if (LoOverflow == +1)
2290 return replaceInstUsesWith(Cmp, Builder.getTrue());
2291 if (LoOverflow == -1)
2292 return replaceInstUsesWith(Cmp, Builder.getFalse());
2296 if (HiOverflow == +1)
2297 return replaceInstUsesWith(Cmp, Builder.getFalse());
2298 if (HiOverflow == -1)
2299 return replaceInstUsesWith(Cmp, Builder.getTrue());
2301 return new ICmpInst(ICmpInst::ICMP_UGE, X,
2347 (*C2 & (C - 1)) == (C - 1))
2395 const APInt &Lower = CR.getLower();
2452 assert(C &&
"Cmp RHS should be a constant int!");
2458 Value *OrigLHS, *OrigRHS;
2459 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2461 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2463 assert(C1LessThan && C2Equal && C3GreaterThan);
2465 bool TrueWhenLessThan =
2468 bool TrueWhenEqual =
2471 bool TrueWhenGreaterThan =
2483 Value *Cond = Builder.getFalse();
2484 if (TrueWhenLessThan)
2485 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
2487 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
2488 if (TrueWhenGreaterThan)
2489 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
2491 return replaceInstUsesWith(Cmp, Cond);
2511 Value *Vec =
nullptr;
2516 if (
auto *Elem = dyn_cast_or_null<ConstantInt>(Mask->
getSplatValue())) {
2517 auto *VecTy = cast<VectorType>(BCIOp->
getType());
2518 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
2520 if (C.
isSplat(EltTy->getBitWidth())) {
2526 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
2528 return new ICmpInst(Pred, Extract, NewC);
2542 if (
auto *BO = dyn_cast<BinaryOperator>(Cmp.
getOperand(0))) {
2543 switch (BO->getOpcode()) {
2544 case Instruction::Xor:
2545 if (
Instruction *I = foldICmpXorConstant(Cmp, BO, *C))
2548 case Instruction::And:
2549 if (
Instruction *I = foldICmpAndConstant(Cmp, BO, *C))
2552 case Instruction::Or:
2553 if (
Instruction *I = foldICmpOrConstant(Cmp, BO, *C))
2556 case Instruction::Mul:
2557 if (
Instruction *I = foldICmpMulConstant(Cmp, BO, *C))
2560 case Instruction::Shl:
2561 if (
Instruction *I = foldICmpShlConstant(Cmp, BO, *C))
2564 case Instruction::LShr:
2565 case Instruction::AShr:
2566 if (
Instruction *I = foldICmpShrConstant(Cmp, BO, *C))
2569 case Instruction::UDiv:
2570 if (
Instruction *I = foldICmpUDivConstant(Cmp, BO, *C))
2573 case Instruction::SDiv:
2574 if (
Instruction *I = foldICmpDivConstant(Cmp, BO, *C))
2577 case Instruction::Sub:
2578 if (
Instruction *I = foldICmpSubConstant(Cmp, BO, *C))
2582 if (
Instruction *I = foldICmpAddConstant(Cmp, BO, *C))
2589 if (
Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C))
2595 if (
auto *SI = dyn_cast<SelectInst>(Cmp.
getOperand(0))) {
2600 if (
Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
2604 if (
auto *TI = dyn_cast<TruncInst>(Cmp.
getOperand(0))) {
2605 if (
Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
2609 if (
auto *BCI = dyn_cast<BitCastInst>(Cmp.
getOperand(0))) {
2610 if (
Instruction *I = foldICmpBitCastConstant(Cmp, BCI, *C))
2614 if (
Instruction *I = foldICmpIntrinsicWithConstant(Cmp, *C))
2636 case Instruction::SRem:
2641 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->
getName());
2653 return new ICmpInst(Pred, BOp0, SubC);
2658 if (
Value *NegVal = dyn_castNegVal(BOp1))
2659 return new ICmpInst(Pred, BOp0, NegVal);
2660 if (
Value *NegVal = dyn_castNegVal(BOp0))
2661 return new ICmpInst(Pred, NegVal, BOp1);
2663 Value *Neg = Builder.CreateNeg(BOp1);
2665 return new ICmpInst(Pred, BOp0, Neg);
2670 case Instruction::Xor:
2672 if (
Constant *BOC = dyn_cast<Constant>(BOp1)) {
2678 return new ICmpInst(Pred, BOp0, BOp1);
2682 case Instruction::Sub:
2688 return new ICmpInst(Pred, BOp1, SubC);
2691 return new ICmpInst(Pred, BOp0, BOp1);
2695 case Instruction::Or: {
2702 Value *And = Builder.CreateAnd(BOp0, NotBOC);
2703 return new ICmpInst(Pred, And, NotBOC);
2707 case Instruction::And: {
2723 return new ICmpInst(NewPred, BOp0, Zero);
2727 if (C.
isNullValue() && (~(*BOC) + 1).isPowerOf2()) {
2730 return new ICmpInst(NewPred, BOp0, NegBOC);
2735 case Instruction::Mul:
2746 case Instruction::UDiv:
2750 return new ICmpInst(NewPred, BOp1, BOp0);
2779 if (C == BitWidth) {
2790 if (Num != BitWidth && II->
hasOneUse()) {
2794 APInt Mask2 = IsTrailing
2809 if (IsZero || C == BitWidth) {
2834 switch (LHSI->getOpcode()) {
2835 case Instruction::GetElementPtr:
2838 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2843 case Instruction::PHI:
2848 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
2855 Value *Op1 =
nullptr, *Op2 =
nullptr;
2857 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2861 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2873 bool Transform =
false;
2876 else if (Op1 || Op2) {
2878 if (LHSI->hasOneUse())
2881 else if (CI && !CI->
isZero())
2886 replacedSelectWithOperand(cast<SelectInst>(LHSI), &
I, Op1 ? 2 : 1);
2890 Op1 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(1), RHSC,
2893 Op2 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(2), RHSC,
2899 case Instruction::IntToPtr:
2902 DL.getIntPtrType(RHSC->
getType()) == LHSI->getOperand(0)->getType())
2911 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2915 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
2954 case ICmpInst::Predicate::ICMP_EQ:
2956 DstPred = ICmpInst::Predicate::ICMP_ULE;
2958 case ICmpInst::Predicate::ICMP_NE:
2960 DstPred = ICmpInst::Predicate::ICMP_UGT;
2962 case ICmpInst::Predicate::ICMP_UGT:
2964 assert(X == I.
getOperand(0) &&
"instsimplify took care of commut. variant");
2965 DstPred = ICmpInst::Predicate::ICMP_UGT;
2967 case ICmpInst::Predicate::ICMP_UGE:
2969 assert(X == I.
getOperand(1) &&
"instsimplify took care of commut. variant");
2970 DstPred = ICmpInst::Predicate::ICMP_ULE;
2972 case ICmpInst::Predicate::ICMP_ULT:
2974 assert(X == I.
getOperand(1) &&
"instsimplify took care of commut. variant");
2975 DstPred = ICmpInst::Predicate::ICMP_UGT;
2977 case ICmpInst::Predicate::ICMP_ULE:
2979 assert(X == I.
getOperand(0) &&
"instsimplify took care of commut. variant");
2980 DstPred = ICmpInst::Predicate::ICMP_ULE;
2982 case ICmpInst::Predicate::ICMP_SGT:
2986 DstPred = ICmpInst::Predicate::ICMP_SGT;
2988 case ICmpInst::Predicate::ICMP_SGE:
2996 DstPred = ICmpInst::Predicate::ICMP_SLE;
2998 case ICmpInst::Predicate::ICMP_SLT:
3006 DstPred = ICmpInst::Predicate::ICMP_SGT;
3008 case ICmpInst::Predicate::ICMP_SLE:
3012 DstPred = ICmpInst::Predicate::ICMP_SLE;
3034 const APInt *C0, *C1;
3051 const APInt &MaskedBits = *C0;
3052 assert(MaskedBits != 0 &&
"shift by zero should be folded away already.");
3056 case ICmpInst::Predicate::ICMP_EQ:
3060 DstPred = ICmpInst::Predicate::ICMP_ULT;
3062 case ICmpInst::Predicate::ICMP_NE:
3066 DstPred = ICmpInst::Predicate::ICMP_UGE;
3075 const APInt BitWidth =
APInt(XBitWidth, XBitWidth);
3076 assert(BitWidth.
ugt(MaskedBits) &&
"shifts should leave some bits untouched");
3079 const APInt KeptBits = BitWidth - MaskedBits;
3080 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) &&
"unreachable");
3083 assert(ICmpCst.isPowerOf2());
3086 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3117 return new ICmpInst(Pred, Builder.CreateNot(Op1),
X);
3120 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
3122 bool NoOp0WrapProblem =
false, NoOp1WrapProblem =
false;
3123 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3128 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3136 Value *A =
nullptr, *
B =
nullptr, *C =
nullptr, *
D =
nullptr;
3142 C = BO1->getOperand(0);
3143 D = BO1->getOperand(1);
3147 if ((A == Op1 ||
B == Op1) && NoOp0WrapProblem)
3148 return new ICmpInst(Pred, A == Op1 ?
B : A,
3152 if ((C == Op0 ||
D == Op0) && NoOp1WrapProblem)
3157 if (A && C && (A == C || A ==
D ||
B == C ||
B ==
D) && NoOp0WrapProblem &&
3167 }
else if (A ==
D) {
3171 }
else if (
B == C) {
3252 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3256 const APInt &AP1 = C1->getValue();
3257 const APInt &AP2 = C2->getValue();
3259 APInt AP1Abs = C1->getValue().
abs();
3260 APInt AP2Abs = C2->getValue().
abs();
3261 if (AP1Abs.
uge(AP2Abs)) {
3263 Value *NewAdd = Builder.CreateNSWAdd(A, C3);
3264 return new ICmpInst(Pred, NewAdd, C);
3267 Value *NewAdd = Builder.CreateNSWAdd(C, C3);
3268 return new ICmpInst(Pred, A, NewAdd);
3279 if (BO0 && BO0->
getOpcode() == Instruction::Sub) {
3283 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3284 C = BO1->getOperand(0);
3285 D = BO1->getOperand(1);
3289 if (A == Op1 && NoOp0WrapProblem)
3292 if (C == Op0 && NoOp1WrapProblem)
3303 if (
B &&
D &&
B ==
D && NoOp0WrapProblem && NoOp1WrapProblem &&
3308 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3317 if (
Constant *RHSC = dyn_cast<Constant>(Op1))
3318 if (RHSC->isNotMinSignedValue())
3328 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3329 Op0 == BO1->getOperand(1))
3353 BO1->hasOneUse() && BO0->
getOperand(1) == BO1->getOperand(1)) {
3358 case Instruction::Sub:
3359 case Instruction::Xor: {
3382 case Instruction::Mul: {
3396 Value *And2 = Builder.CreateAnd(BO1->getOperand(0),
Mask);
3397 return new ICmpInst(Pred, And1, And2);
3406 case Instruction::UDiv:
3407 case Instruction::LShr:
3412 case Instruction::SDiv:
3417 case Instruction::AShr:
3418 if (!BO0->
isExact() || !BO1->isExact())
3422 case Instruction::Shl: {
3446 return replaceInstUsesWith(I, V);
3449 return replaceInstUsesWith(I, V);
3549 if (A == Op1 || B == Op1) {
3550 Value *OtherVal = A == Op1 ?
B : A;
3560 Value *Xor = Builder.CreateXor(C, NC);
3578 Value *OtherVal = A == Op0 ?
B : A;
3585 Value *X =
nullptr, *
Y =
nullptr, *Z =
nullptr;
3591 }
else if (A == D) {
3595 }
else if (B == C) {
3599 }
else if (B == D) {
3606 Op1 = Builder.CreateXor(X,
Y);
3607 Op1 = Builder.CreateAnd(Op1, Z);
3635 if (ShAmt < TypeBits && ShAmt != 0) {
3638 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
3640 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal));
3649 if (ShAmt < TypeBits && ShAmt != 0) {
3650 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
3652 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
3667 unsigned ASize = cast<IntegerType>(A->
getType())->getPrimitiveSizeInBits();
3669 if (ShAmt < ASize) {
3677 Value *
Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
3678 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
3699 Type *SrcTy = LHSCIOp->getType();
3705 const auto& CompatibleSizes = [&](
Type* SrcTy,
Type* DestTy) ->
bool {
3706 if (isa<VectorType>(SrcTy)) {
3707 SrcTy = cast<VectorType>(SrcTy)->getElementType();
3708 DestTy = cast<VectorType>(DestTy)->getElementType();
3712 if (LHSCI->
getOpcode() == Instruction::PtrToInt &&
3713 CompatibleSizes(SrcTy, DestTy)) {
3714 Value *RHSOp =
nullptr;
3715 if (
auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.
getOperand(1))) {
3716 Value *RHSCIOp = RHSC->getOperand(0);
3718 LHSCIOp->getType()->getPointerAddressSpace()) {
3719 RHSOp = RHSC->getOperand(0);
3721 if (LHSCIOp->getType() != RHSOp->
getType())
3722 RHSOp = Builder.CreateBitCast(RHSOp, LHSCIOp->
getType());
3724 }
else if (
auto *RHSC = dyn_cast<Constant>(ICmp.
getOperand(1))) {
3734 if (LHSCI->
getOpcode() != Instruction::ZExt &&
3735 LHSCI->
getOpcode() != Instruction::SExt)
3738 bool isSignedExt = LHSCI->
getOpcode() == Instruction::SExt;
3739 bool isSignedCmp = ICmp.
isSigned();
3741 if (
auto *CI = dyn_cast<CastInst>(ICmp.
getOperand(1))) {
3743 RHSCIOp = CI->getOperand(0);
3744 if (RHSCIOp->
getType() != LHSCIOp->getType())
3749 if (CI->getOpcode() != LHSCI->
getOpcode())
3758 if (isSignedCmp && isSignedExt)
3783 if (isSignedExt && isSignedCmp)
3797 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
3806 Value *Result = Builder.CreateICmpSGT(LHSCIOp, NegOne, ICmp.
getName());
3810 return replaceInstUsesWith(ICmp, Result);
3819 if (OrigI.
isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
3822 auto SetResult = [&](
Value *OpResult,
Constant *OverflowVal,
bool ReuseName) {
3824 Overflow = OverflowVal;
3834 Builder.SetInsertPoint(&OrigI);
3843 return SetResult(Builder.CreateNUWAdd(LHS, RHS), Builder.getFalse(),
3847 return SetResult(Builder.CreateAdd(LHS, RHS), Builder.getTrue(),
true);
3855 return SetResult(LHS, Builder.getFalse(),
false);
3860 if (willNotOverflowSignedAdd(LHS, RHS, OrigI))
3861 return SetResult(Builder.CreateNSWAdd(LHS, RHS), Builder.getFalse(),
3870 return SetResult(LHS, Builder.getFalse(),
false);
3873 if (willNotOverflowSignedSub(LHS, RHS, OrigI))
3874 return SetResult(Builder.CreateNSWSub(LHS, RHS), Builder.getFalse(),
3877 if (willNotOverflowUnsignedSub(LHS, RHS, OrigI))
3878 return SetResult(Builder.CreateNUWSub(LHS, RHS), Builder.getFalse(),
3887 return SetResult(Builder.CreateNUWMul(LHS, RHS), Builder.getFalse(),
3890 return SetResult(Builder.CreateMul(LHS, RHS), Builder.getTrue(),
true);
3895 if (isa<UndefValue>(RHS))
3900 return SetResult(RHS, Builder.getFalse(),
false);
3904 return SetResult(LHS, Builder.getFalse(),
false);
3907 if (willNotOverflowSignedMul(LHS, RHS, OrigI))
3908 return SetResult(Builder.CreateNSWMul(LHS, RHS), Builder.getFalse(),
3934 if (!isa<IntegerType>(MulVal->
getType()))
3942 assert(MulInstr->getOpcode() == Instruction::Mul);
3944 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
3945 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
3946 assert(LHS->getOpcode() == Instruction::ZExt);
3947 assert(RHS->getOpcode() == Instruction::ZExt);
3948 Value *A = LHS->getOperand(0), *
B = RHS->getOperand(0);
3951 Type *TyA = A->getType(), *TyB =
B->getType();
3953 WidthB = TyB->getPrimitiveSizeInBits();
3956 if (WidthB > WidthA) {
3971 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
3974 if (TruncWidth > MulWidth)
3978 if (BO->
getOpcode() != Instruction::And)
3981 const APInt &CVal = CI->getValue();
4003 if (
ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
4004 if (Zext->hasOneUse()) {
4005 Value *ZextArg = Zext->getOperand(0);
4006 if (
TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
4017 if (ValToMask != MulVal)
4021 unsigned MaskWidth = CVal.
logBase2();
4022 if (MaskWidth == MulWidth)
4032 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4044 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4055 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4067 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4082 Value *MulA = A, *MulB =
B;
4083 if (WidthA < MulWidth)
4085 if (WidthB < MulWidth)
4099 if (U == &I || U == OtherVal)
4101 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
4102 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
4110 APInt ShortMask = CI->getValue().
trunc(MulWidth);
4122 if (isa<Instruction>(OtherVal))
4212 return GoodToSwap > 0;
4228 assert(DI && UI &&
"Instruction not defined\n");
4239 auto *Usr = cast<Instruction>(U);
4240 if (Usr != UI && !DT.dominates(DB, Usr->
getParent()))
4251 auto *BI = dyn_cast_or_null<BranchInst>(BB->
getTerminator());
4252 if (!BI || BI->getNumSuccessors() != 2)
4255 if (!IC || (IC->getOperand(0) != SI && IC->
getOperand(1) !=
SI))
4302 const unsigned SIOpd) {
4303 assert((SIOpd == 1 || SIOpd == 2) &&
"Invalid select operand!");
4344 if (SimplifyDemandedBits(&I, 0,
4356 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4357 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4369 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
4371 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
4381 if (Op0Max.
ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4390 APInt Op0KnownZeroInverted = ~Op0Known.
Zero;
4393 Value *LHS =
nullptr;
4396 *LHSC != Op0KnownZeroInverted)
4401 APInt ValToCheck = Op0KnownZeroInverted;
4408 return new ICmpInst(NewPred, X, CmpC);
4409 }
else if ((++ValToCheck).isPowerOf2()) {
4415 return new ICmpInst(NewPred, X, CmpC);
4433 if (Op0Max.
ult(Op1Min))
4435 if (Op0Min.uge(Op1Max))
4437 if (Op1Min == Op0Max)
4443 if (*CmpC == Op0Min + 1)
4455 if (Op0Min.ugt(Op1Max))
4457 if (Op0Max.
ule(Op1Min))
4459 if (Op1Max == Op0Min)
4465 if (*CmpC == Op0Max - 1)
4477 if (Op0Max.
slt(Op1Min))
4479 if (Op0Min.sge(Op1Max))
4481 if (Op1Min == Op0Max)
4485 if (*CmpC == Op0Min + 1)
4492 if (Op0Min.sgt(Op1Max))
4494 if (Op0Max.
sle(Op1Min))
4496 if (Op1Max == Op0Min)
4500 if (*CmpC == Op0Max - 1)
4507 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SGE with ConstantInt not folded!");
4508 if (Op0Min.sge(Op1Max))
4510 if (Op0Max.
slt(Op1Min))
4512 if (Op1Min == Op0Max)
4516 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SLE with ConstantInt not folded!");
4517 if (Op0Max.
sle(Op1Min))
4519 if (Op0Min.sgt(Op1Max))
4521 if (Op1Max == Op0Min)
4525 assert(!isa<ConstantInt>(Op1) &&
"ICMP_UGE with ConstantInt not folded!");
4526 if (Op0Min.uge(Op1Max))
4528 if (Op0Max.
ult(Op1Min))
4530 if (Op1Min == Op0Max)
4534 assert(!isa<ConstantInt>(Op1) &&
"ICMP_ULE with ConstantInt not folded!");
4535 if (Op0Max.
ule(Op1Min))
4537 if (Op0Min.ugt(Op1Max))
4539 if (Op1Max == Op0Min)
4579 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
4585 for (
unsigned i = 0; i != NumElts; ++i) {
4590 if (isa<UndefValue>(Elt))
4596 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
4650 return BinaryOperator::CreateXor(A,
B);
4658 return BinaryOperator::CreateAnd(Builder.
CreateNot(A),
B);
4666 return BinaryOperator::CreateAnd(Builder.
CreateNot(
B), A);
4674 return BinaryOperator::CreateOr(Builder.
CreateNot(A),
B);
4682 return BinaryOperator::CreateOr(Builder.
CreateNot(
B), A);
4764 bool Changed =
false;
4772 if (Op0Cplxity < Op1Cplxity ||
4780 SQ.getWithInstruction(&I)))
4781 return replaceInstUsesWith(I, V);
4786 Value *Cond, *SelectTrue, *SelectFalse;
4789 if (
Value *V = dyn_castNegVal(SelectTrue)) {
4790 if (V == SelectFalse)
4793 else if (
Value *V = dyn_castNegVal(SelectFalse)) {
4794 if (V == SelectTrue)
4810 if (
Instruction *Res = foldICmpWithDominatingICmp(I))
4858 if (
Instruction *Res = foldICmpInstWithConstant(I))
4861 if (
Instruction *Res = foldICmpInstWithConstantNotInt(I))
4865 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
4868 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
4875 assert(Op1->getType()->isPointerTy() &&
"Comparing pointer with non-pointer?");
4877 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op1))
4880 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op0))
4915 if (
BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4917 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
4920 Op0 = CI->getOperand(0);
4924 if (
BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4925 Op1 = CI2->getOperand(0);
4928 if (Op0->
getType() != Op1->getType()) {
4929 if (
Constant *Op1C = dyn_cast<Constant>(Op1)) {
4933 Op1 = Builder.CreateBitCast(Op1, Op0->
getType());
4940 if (isa<CastInst>(Op0)) {
4947 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
4984 isa<IntegerType>(A->
getType())) {
4989 replaceInstUsesWith(*AddI, Result);
4990 return replaceInstUsesWith(I, Overflow);
5018 if (
auto *EVI = dyn_cast<ExtractValueInst>(Op0))
5019 if (
auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
5020 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
5043 return Changed ? &
I :
nullptr;
5049 if (!isa<ConstantFP>(RHSC))
return nullptr;
5050 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5055 if (MantissaWidth == -1)
return nullptr;
5059 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5063 bool IsExact =
false;
5075 return replaceInstUsesWith(I, Builder.getFalse());
5078 return replaceInstUsesWith(I, Builder.getTrue());
5094 if ((
int)InputSize > MantissaWidth) {
5096 int Exp =
ilogb(RHS);
5099 if (MaxExponent < (
int)InputSize - !LHSUnsigned)
5105 if (MantissaWidth <= Exp && Exp <= (
int)InputSize - !LHSUnsigned)
5114 assert(!RHS.
isNaN() &&
"NaN comparison not already folded!");
5144 return replaceInstUsesWith(I, Builder.getTrue());
5146 return replaceInstUsesWith(I, Builder.getFalse());
5164 return replaceInstUsesWith(I, Builder.getTrue());
5165 return replaceInstUsesWith(I, Builder.getFalse());
5176 return replaceInstUsesWith(I, Builder.getTrue());
5177 return replaceInstUsesWith(I, Builder.getFalse());
5189 return replaceInstUsesWith(I, Builder.getTrue());
5190 return replaceInstUsesWith(I, Builder.getFalse());
5200 return replaceInstUsesWith(I, Builder.getTrue());
5201 return replaceInstUsesWith(I, Builder.getFalse());
5213 bool Equal = LHSUnsigned
5223 return replaceInstUsesWith(I, Builder.getTrue());
5225 return replaceInstUsesWith(I, Builder.getFalse());
5230 return replaceInstUsesWith(I, Builder.getFalse());
5242 return replaceInstUsesWith(I, Builder.getFalse());
5255 return replaceInstUsesWith(I, Builder.getTrue());
5267 return replaceInstUsesWith(I, Builder.getTrue());
5397 bool Changed =
false;
5410 SQ.getWithInstruction(&I)))
5411 return replaceInstUsesWith(I, V);
5477 case Instruction::PHI:
5482 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
5485 case Instruction::SIToFP:
5486 case Instruction::UIToFP:
5490 case Instruction::FDiv:
5495 if (
auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->
getOperand(0)))
5496 if (
auto *GV = dyn_cast<GlobalVariable>(GEP->
getOperand(0)))
5499 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
5525 return new FCmpInst(Pred, X, Y,
"", &I);
5544 return new FCmpInst(Pred, X, NewC,
"", &I);
5553 return Changed ? &
I :
nullptr;
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
APInt abs() const
Get the absolute value;.
opStatus roundToIntegral(roundingMode RM)
bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the given value is known be positive (i.e.
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1-In2, returning true if the result overflowed for this type.
Value * SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
bool hasNoInfs() const
Determine whether the no-infs flag is set.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of nonnegative values.
static bool isEquality(Predicate Pred)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
void setSignBit()
Set the sign bit to 1.
This class is the base class for the comparison instructions.
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
iterator_range< use_iterator > uses()
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Type * getSrcTy() const
Return the source type, as a convenience.
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
DiagnosticInfoOptimizationBase::Argument NV
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Value * SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
BinaryOps getOpcode() const
size_type size() const
Determine the number of elements in the SetVector.
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
m_Intrinsic_Ty< Opnd0 >::Ty m_BitReverse(const Opnd0 &Op0)
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
bool dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const
True when DB dominates all uses of DI except UI.
This class represents zero extension of integer types.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
void push_back(const T &Elt)
static Instruction * foldVectorCmp(CmpInst &Cmp, InstCombiner::BuilderTy &Builder)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
APInt zext(unsigned width) const
Zero extend to a new width.
bool slt(const APInt &RHS) const
Signed less than comparison.
APInt udiv(const APInt &RHS) const
Unsigned division operation.
This class represents a function call, abstracting a target machine's calling convention.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(const Opnd0 &Op0)
const Value * getTrueValue() const
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
0 1 0 0 True if ordered and less than
static Instruction * foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold (C / X) < 0.0 –> X < 0.0 if possible. Swap predicate if necessary.
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
static Constant * getNUWShl(Constant *C1, Constant *C2)
1 1 1 0 True if unordered or not equal
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate, true > m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
bool sgt(const APInt &RHS) const
Signed greather than comparison.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
APInt trunc(unsigned width) const
Truncate to new width.
STATISTIC(NumFunctions, "Total number of functions")
bool isArithmeticShift() const
Return true if this is an arithmetic shift right.
const fltSemantics & getSemantics() const
ThreeOps_match< V1_t, V2_t, Mask_t, Instruction::ShuffleVector > m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m)
Matches ShuffleVectorInst.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp, const unsigned SIOpd)
Try to replace select with select operand SIOpd in SI-ICmp sequence.
bool sle(const APInt &RHS) const
Signed less or equal comparison.
unsigned getBitWidth() const
Get the bit width of this value.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit...
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Value * CreateNot(Value *V, const Twine &Name="")
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Value * getArgOperand(unsigned i) const
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
1 0 0 1 True if unordered or equal
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to have exactly one bit set when defined. ...
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
Type * getPointerElementType() const
OverflowCheckFlavor
Specific patterns of overflow check idioms that we match.
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
APInt shl(unsigned shiftAmt) const
Left-shift function.
uint64_t getArrayNumElements() const
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
static Instruction * canonicalizeICmpBool(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Integer compare with boolean values can always be turned into bitwise ops.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
static Value * foldICmpWithLowBitMaskedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
The core instruction combiner logic.
0 1 0 1 True if ordered and less than or equal
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
unsigned getNumIndices() const
unsigned getActiveBits() const
Compute the number of active bits in the value.
static Instruction * transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, ICmpInst::Predicate Cond, const DataLayout &DL)
Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
apfloat_match m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CastClass_match< OpTy, Instruction::FPExt > m_FPExt(const OpTy &Op)
Matches FPExt.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
static void computeSignedMinMaxValuesFromKnownBits(const KnownBits &Known, APInt &Min, APInt &Max)
Given a signed integer type and a set of known zero and one bits, compute the maximum and minimum val...
Class to represent array types.
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
This instruction compares its operands according to the predicate given to the constructor.
static Instruction * processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombiner &IC)
The caller has matched a pattern of the form: I = icmp ugt (add (add A, B), CI2), CI1 If this is of t...
int32_t exactLogBase2() const
This class represents a no-op cast from one type to another.
static Instruction * foldICmpWithHighBitMask(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Get a value with upper bits starting at loBit set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
int getFPMantissaWidth() const
Return the width of the mantissa of this type.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void takeName(Value *V)
Transfer the name from V to this value.
static bool isChainSelectCmpBranch(const SelectInst *SI)
Return true when the instruction sequence within a block is select-cmp-br.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
This class represents a truncation of integer types.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
static std::pair< Value *, Value * > getAsConstantIndexedAddress(Value *V, const DataLayout &DL)
Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express the input Value as a constant...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty, true > m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
static Value * foldICmpWithTruncSignExtendedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
OneUse_match< T > m_OneUse(const T &SubPattern)
bool isNegative() const
Determine sign of this APInt.
static Constant * getFNeg(Constant *C)
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
bool isAllOnesValue() const
Determine if all bits are set.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
static bool canRewriteGEPAsOffset(Value *Start, Value *Base, const DataLayout &DL, SetVector< Value *> &Explored)
Returns true if we can rewrite Start as a GEP with pointer Base and some integer offset.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
bool isPointerTy() const
True if this is an instance of PointerType.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
static Constant * getAnd(Constant *C1, Constant *C2)
static ManagedStatic< OptionRegistry > OR
bool isOneValue() const
Determine if this is a value of 1.
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
static Constant * getSExtOrBitCast(Constant *C, Type *Ty)
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
bool isMinSignedValue() const
Determine if this is the smallest signed value.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1+In2, returning true if the result overflowed for this type.
Instruction * visitICmpInst(ICmpInst &I)
0 1 1 1 True if ordered (no nans)
static Instruction * foldFabsWithFcmpZero(FCmpInst &I)
Optimize fabs(X) compared with zero.
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty, true > m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Class to represent integer types.
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
static Constant * getNot(Constant *C)
static Value * rewriteGEPAsOffset(Value *Start, Value *Base, const DataLayout &DL, SetVector< Value *> &Explored)
Returns a re-written value of Start as an indexed GEP using Base as a pointer.
void clearSignBit()
Set the sign bit to 0.
const Value * getCondition() const
bool eq(const APInt &RHS) const
Equality comparison.
static Constant * getAllOnesValue(Type *Ty)
bool isZero() const
Returns true if value is all zero.
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
bool isSplat(unsigned SplatSizeInBits) const
Check if the APInt consists of a repeated bit pattern.
static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth)
When performing a comparison against a constant, it is possible that not all the bits in the LHS are ...
Type * getIndexedType() const
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
void swapOperands()
Exchange the two operands to this instruction in such a way that it does not modify the semantics of ...
unsigned ceilLogBase2() const
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
static wasm::ValType getType(const TargetRegisterClass *RC)
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
bool isExact() const
Determine whether the exact flag is set.
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
Constant * getSplatValue() const
If this is a splat vector constant, meaning that all of the elements have the same value...
1 1 0 1 True if unordered, less than, or equal
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
deferredval_ty< Value > m_Deferred(Value *const &V)
A commutative-friendly version of m_Specific().
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
static bool hasBranchUse(ICmpInst &I)
Given an icmp instruction, return true if any use of this comparison is a branch on sign bit comparis...
InstCombineWorklist & Worklist
A worklist of the instructions that need to be simplified.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty, true > m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
bool isEmptySet() const
Return true if this set contains no members.
0 0 1 0 True if ordered and greater than
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
static Constant * getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
StructType * getStructTypeOrNull() const
unsigned getNumOperands() const
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
bool isMaxSignedValue() const
Determine if this is the largest signed value.
This is the shared class of boolean and integer constants.
SelectPatternFlavor Flavor
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
1 1 0 0 True if unordered or less than
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
unsigned ComputeNumSignBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
This class represents a range of values.
LLVM_NODISCARD T pop_back_val()
bool isMaxValue() const
Determine if this is the largest unsigned value.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
void negate()
Negate this APInt in place.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Instruction * foldICmpWithMinMax(ICmpInst &Cmp)
Fold icmp Pred min|max(X, Y), X.
CastClass_match< OpTy, Instruction::UIToFP > m_UIToFP(const OpTy &Op)
Matches UIToFP.
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
static ConstantInt * getTrue(LLVMContext &Context)
bool isCommutative() const
Return true if the instruction is commutative:
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
unsigned logBase2() const
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getVectorNumElements() const
unsigned countTrailingOnes() const
Count the number of trailing one bits.
bool isTrueWhenEqual() const
This is just a convenience.
static ICmpInst * canonicalizeCmpWithConstant(ICmpInst &I)
If we have an icmp le or icmp ge instruction with a constant operand, turn it into the appropriate ic...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
static Value * evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC, const DataLayout &DL)
Return a value that can be used to compare the offset implied by a GEP to zero.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
CastClass_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
iterator_range< user_iterator > users()
static Constant * getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
const Value * getFalseValue() const
static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C)
Returns true if the exploded icmp can be expressed as a signed comparison to zero and updates the pre...
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Predicate getPredicate() const
Return the predicate for this instruction.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
uint64_t getElementOffset(unsigned Idx) const
unsigned getIntegerBitWidth() const
LLVM_NODISCARD bool empty() const
unsigned greater or equal
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty, true > m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static Constant * getOr(Constant *C1, Constant *C2)
static void computeUnsignedMinMaxValuesFromKnownBits(const KnownBits &Known, APInt &Min, APInt &Max)
Given an unsigned integer type and a set of known zero and one bits, compute the maximum and minimum ...
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
0 1 1 0 True if ordered and operands are unequal
static Instruction * foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, const APInt &C)
Fold icmp (shl 1, Y), C.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
CastClass_match< OpTy, Instruction::SIToFP > m_SIToFP(const OpTy &Op)
Matches SIToFP.
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
static Instruction * processUMulZExtIdiom(ICmpInst &I, Value *MulVal, Value *OtherVal, InstCombiner &IC)
Recognize and process idiom involving test for multiplication overflow.
1 0 1 0 True if unordered or greater than
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
bool isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
bool isMinValue() const
Determine if this is the smallest unsigned value.
Optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
void swapOperands()
Exchange the two operands to this instruction in such a way that it does not modify the semantics of ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1)
Check if the order of Op0 and Op1 as operands in an ICmpInst should be swapped.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
0 0 0 1 True if ordered and equal
LLVM Value Representation.
This file provides internal interfaces used to implement the InstCombine.
1 0 1 1 True if unordered, greater than, or equal
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static Constant * getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Instruction * visitFCmpInst(FCmpInst &I)
bool hasNoNaNs() const
Determine whether the no-NaNs flag is set.
bool hasOneUse() const
Return true if there is exactly one user of this value.
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
unsigned countLeadingOnes() const
Count the number of leading one bits.
void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
Type * getArrayElementType() const
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
static bool isVolatile(Instruction *Inst)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
0 0 1 1 True if ordered and greater than or equal
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
int ilogb(const IEEEFloat &Arg)
bool isNullValue() const
Determine if all bits are clear.
cmpResult compare(const APFloat &RHS) const
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
A wrapper class for inspecting calls to intrinsic functions.
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
const fltSemantics & getFltSemantics() const
static Constant * getXor(Constant *C1, Constant *C2)
gep_type_iterator gep_type_begin(const User *GEP)
APInt usub_ov(const APInt &RHS, bool &Overflow) const