33using namespace PatternMatch;
35#define DEBUG_TYPE "instcombine"
44 const APInt &In2,
bool IsSigned =
false) {
47 Result = In1.
sadd_ov(In2, Overflow);
49 Result = In1.
uadd_ov(In2, Overflow);
57 const APInt &In2,
bool IsSigned =
false) {
60 Result = In1.
ssub_ov(In2, Overflow);
62 Result = In1.
usub_ov(In2, Overflow);
70 for (
auto *U :
I.users())
71 if (isa<BranchInst>(U))
81 if (!ICmpInst::isSigned(Pred))
88 if (Pred == ICmpInst::ICMP_SLT) {
89 Pred = ICmpInst::ICMP_SLE;
92 }
else if (
C.isAllOnes()) {
93 if (Pred == ICmpInst::ICMP_SGT) {
94 Pred = ICmpInst::ICMP_SGE;
119 if (!isa<ConstantArray>(
Init) && !isa<ConstantDataArray>(
Init))
122 uint64_t ArrayElementCount =
Init->getType()->getArrayNumElements();
131 if (
GEP->getNumOperands() < 3 || !isa<ConstantInt>(
GEP->getOperand(1)) ||
132 !cast<ConstantInt>(
GEP->getOperand(1))->isZero() ||
133 isa<Constant>(
GEP->getOperand(2)))
141 Type *EltTy =
Init->getType()->getArrayElementType();
142 for (
unsigned i = 3, e =
GEP->getNumOperands(); i != e; ++i) {
148 if ((
unsigned)IdxVal != IdxVal)
151 if (
StructType *STy = dyn_cast<StructType>(EltTy))
152 EltTy = STy->getElementType(IdxVal);
153 else if (
ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
154 if (IdxVal >= ATy->getNumElements())
156 EltTy = ATy->getElementType();
164 enum { Overdefined = -3, Undefined = -2 };
173 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
177 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
185 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
194 for (
unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
200 if (!LaterIndices.
empty()) {
215 CompareRHS,
DL, &
TLI);
220 if (isa<UndefValue>(
C)) {
223 if (TrueRangeEnd == (
int)i - 1)
225 if (FalseRangeEnd == (
int)i - 1)
232 if (!isa<ConstantInt>(
C))
237 bool IsTrueForElt = !cast<ConstantInt>(
C)->isZero();
242 if (FirstTrueElement == Undefined)
243 FirstTrueElement = TrueRangeEnd = i;
246 if (SecondTrueElement == Undefined)
247 SecondTrueElement = i;
249 SecondTrueElement = Overdefined;
252 if (TrueRangeEnd == (
int)i - 1)
255 TrueRangeEnd = Overdefined;
259 if (FirstFalseElement == Undefined)
260 FirstFalseElement = FalseRangeEnd = i;
263 if (SecondFalseElement == Undefined)
264 SecondFalseElement = i;
266 SecondFalseElement = Overdefined;
269 if (FalseRangeEnd == (
int)i - 1)
272 FalseRangeEnd = Overdefined;
277 if (i < 64 && IsTrueForElt)
278 MagicBitvector |= 1ULL << i;
283 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
284 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
285 FalseRangeEnd == Overdefined)
296 if (!
GEP->isInBounds()) {
299 if (
Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)
310 unsigned ElementSize =
323 if (SecondTrueElement != Overdefined) {
326 if (FirstTrueElement == Undefined)
329 Value *FirstTrueIdx = ConstantInt::get(
Idx->getType(), FirstTrueElement);
332 if (SecondTrueElement == Undefined)
337 Value *SecondTrueIdx = ConstantInt::get(
Idx->getType(), SecondTrueElement);
339 return BinaryOperator::CreateOr(C1, C2);
344 if (SecondFalseElement != Overdefined) {
347 if (FirstFalseElement == Undefined)
350 Value *FirstFalseIdx = ConstantInt::get(
Idx->getType(), FirstFalseElement);
353 if (SecondFalseElement == Undefined)
358 Value *SecondFalseIdx =
359 ConstantInt::get(
Idx->getType(), SecondFalseElement);
361 return BinaryOperator::CreateAnd(C1, C2);
366 if (TrueRangeEnd != Overdefined) {
367 assert(TrueRangeEnd != FirstTrueElement &&
"Should emit single compare");
371 if (FirstTrueElement) {
372 Value *Offs = ConstantInt::get(
Idx->getType(), -FirstTrueElement);
377 ConstantInt::get(
Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
382 if (FalseRangeEnd != Overdefined) {
383 assert(FalseRangeEnd != FirstFalseElement &&
"Should emit single compare");
386 if (FirstFalseElement) {
387 Value *Offs = ConstantInt::get(
Idx->getType(), -FirstFalseElement);
392 ConstantInt::get(
Idx->getType(), FalseRangeEnd - FirstFalseElement);
405 if (ArrayElementCount <= Idx->
getType()->getIntegerBitWidth())
439 while (!WorkList.
empty()) {
442 while (!WorkList.
empty()) {
443 if (Explored.
size() >= 100)
453 if (!isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
458 if (
auto *
GEP = dyn_cast<GEPOperator>(V)) {
460 auto IsNonConst = [](
Value *V) {
return !isa<ConstantInt>(V); };
461 if (!
GEP->isInBounds() ||
count_if(
GEP->indices(), IsNonConst) > 1)
469 if (WorkList.
back() == V) {
475 if (
auto *PN = dyn_cast<PHINode>(V)) {
477 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
485 for (
auto *PN : PHIs)
486 for (
Value *
Op : PN->incoming_values())
494 for (
Value *Val : Explored) {
497 auto *
PHI = dyn_cast<PHINode>(
Use);
498 auto *Inst = dyn_cast<Instruction>(Val);
500 if (Inst ==
Base || Inst ==
PHI || !Inst || !
PHI ||
504 if (
PHI->getParent() == Inst->getParent())
515 if (
auto *
PHI = dyn_cast<PHINode>(V)) {
520 if (
auto *
I = dyn_cast<Instruction>(V)) {
522 I = &*std::next(
I->getIterator());
526 if (
auto *
A = dyn_cast<Argument>(V)) {
528 BasicBlock &Entry =
A->getParent()->getEntryBlock();
534 assert(isa<Constant>(V) &&
"Setting insertion point for unknown value!");
551 Base->getContext(),
DL.getIndexTypeSizeInBits(Start->getType()));
557 for (
Value *Val : Explored) {
562 if (
auto *
PHI = dyn_cast<PHINode>(Val))
565 PHI->getName() +
".idx",
PHI->getIterator());
570 for (
Value *Val : Explored) {
574 if (
auto *
GEP = dyn_cast<GEPOperator>(Val)) {
578 if (isa<ConstantInt>(
Op) && cast<ConstantInt>(
Op)->
isZero())
579 NewInsts[
GEP] = OffsetV;
582 Op, OffsetV,
GEP->getOperand(0)->getName() +
".add",
587 if (isa<PHINode>(Val))
594 for (
Value *Val : Explored) {
599 if (
auto *
PHI = dyn_cast<PHINode>(Val)) {
601 for (
unsigned I = 0, E =
PHI->getNumIncomingValues();
I < E; ++
I) {
602 Value *NewIncoming =
PHI->getIncomingValue(
I);
604 auto It = NewInsts.
find(NewIncoming);
605 if (It != NewInsts.
end())
606 NewIncoming = It->second;
613 for (
Value *Val : Explored) {
620 Val->getName() +
".ptr", NW);
627 return NewInsts[Start];
689 if (!isa<GetElementPtrInst>(
RHS))
721 isa<Constant>(
RHS) && cast<Constant>(
RHS)->isNullValue() &&
743 auto EC = cast<VectorType>(GEPLHS->
getType())->getElementCount();
748 cast<Constant>(
RHS),
Base->getType()));
752 if (PtrBase != GEPRHS->getOperand(0)) {
753 bool IndicesTheSame =
756 GEPRHS->getPointerOperand()->getType() &&
760 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
761 IndicesTheSame =
false;
774 if (GEPLHS->
isInBounds() && GEPRHS->isInBounds() &&
776 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
780 Value *LOffset = EmitGEPOffset(GEPLHS);
781 Value *ROffset = EmitGEPOffset(GEPRHS);
788 if (LHSIndexTy != RHSIndexTy) {
811 unsigned NumDifferences = 0;
812 unsigned DiffOperand = 0;
813 for (
unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
814 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
816 Type *RHSType = GEPRHS->getOperand(i)->getType();
827 if (NumDifferences++)
break;
831 if (NumDifferences == 0)
835 else if (NumDifferences == 1 && CanFold(NW)) {
837 Value *RHSV = GEPRHS->getOperand(DiffOperand);
838 return NewICmp(NW, LHSV, RHSV);
844 Value *L = EmitGEPOffset(GEPLHS,
true);
845 Value *R = EmitGEPOffset(GEPRHS,
true);
846 return NewICmp(NW, L, R);
872 bool Captured =
false;
877 CmpCaptureTracker(
AllocaInst *Alloca) : Alloca(Alloca) {}
879 void tooManyUses()
override { Captured =
true; }
881 bool captured(
const Use *U)
override {
882 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
890 ICmps[ICmp] |= 1u << U->getOperandNo();
899 CmpCaptureTracker Tracker(Alloca);
901 if (Tracker.Captured)
904 bool Changed =
false;
905 for (
auto [ICmp,
Operands] : Tracker.ICmps) {
911 auto *Res = ConstantInt::get(
937 assert(!!
C &&
"C should not be zero!");
943 Constant *R = ConstantInt::get(
X->getType(),
953 ConstantInt::get(
X->getType(), -
C));
965 ConstantInt::get(
X->getType(),
SMax -
C));
976 ConstantInt::get(
X->getType(),
SMax - (
C - 1)));
985 assert(
I.isEquality() &&
"Cannot fold icmp gt/lt");
988 if (
I.getPredicate() ==
I.ICMP_NE)
997 bool IsAShr = isa<AShrOperator>(
I.getOperand(0));
1009 return getICmp(
I.ICMP_UGT,
A,
1010 ConstantInt::get(
A->getType(), AP2.
logBase2()));
1022 if (IsAShr && AP1 == AP2.
ashr(Shift)) {
1026 return getICmp(
I.ICMP_UGE,
A, ConstantInt::get(
A->getType(), Shift));
1027 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
1028 }
else if (AP1 == AP2.
lshr(Shift)) {
1029 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
1035 auto *TorF = ConstantInt::get(
I.getType(),
I.getPredicate() ==
I.ICMP_NE);
1044 assert(
I.isEquality() &&
"Cannot fold icmp gt/lt");
1047 if (
I.getPredicate() ==
I.ICMP_NE)
1058 if (!AP1 && AP2TrailingZeros != 0)
1061 ConstantInt::get(
A->getType(), AP2.
getBitWidth() - AP2TrailingZeros));
1069 if (Shift > 0 && AP2.
shl(Shift) == AP1)
1070 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
1074 auto *TorF = ConstantInt::get(
I.getType(),
I.getPredicate() ==
I.ICMP_NE);
1095 Instruction *AddWithCst = cast<Instruction>(
I.getOperand(0));
1103 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1127 if (U == AddWithCst)
1145 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1174 if (!
I.isEquality())
1205 APInt(XBitWidth, XBitWidth - 1))))
1207 }
else if (isa<BinaryOperator>(Val) &&
1232 return new ICmpInst(Pred,
B, Cmp.getOperand(1));
1234 return new ICmpInst(Pred,
A, Cmp.getOperand(1));
1251 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1263 return new ICmpInst(Pred,
Y, Cmp.getOperand(1));
1269 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1271 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1272 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1280 return new ICmpInst(Pred,
Y, Cmp.getOperand(1));
1285 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1317 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1330 if (
auto *Phi = dyn_cast<PHINode>(Op0))
1331 if (
all_of(Phi->operands(), [](
Value *V) { return isa<Constant>(V); })) {
1333 for (
Value *V : Phi->incoming_values()) {
1342 for (
auto [V, Pred] :
zip(Ops, Phi->blocks()))
1357 Value *
X = Cmp.getOperand(0), *
Y = Cmp.getOperand(1);
1390 if (Cmp.isEquality() || (IsSignBit &&
hasBranchUse(Cmp)))
1395 if (Cmp.hasOneUse() &&
1409 if (!
match(BI->getCondition(),
1415 if (
auto *V = handleDomCond(DomPred, DomC))
1435 Type *SrcTy =
X->getType();
1441 if (shouldChangeType(Trunc->
getType(), SrcTy)) {
1443 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy,
C.sext(SrcBits)));
1445 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy,
C.zext(SrcBits)));
1448 if (
C.isOne() &&
C.getBitWidth() > 1) {
1453 ConstantInt::get(V->getType(), 1));
1463 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1464 return new ICmpInst(NewPred,
Y, ConstantInt::get(SrcTy, DstBits));
1469 return new ICmpInst(Pred,
Y, ConstantInt::get(SrcTy,
C.logBase2()));
1472 if (Cmp.isEquality() && Trunc->
hasOneUse()) {
1475 if (!SrcTy->
isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1479 Constant *WideC = ConstantInt::get(SrcTy,
C.zext(SrcBits));
1488 if ((Known.
Zero | Known.
One).countl_one() >= SrcBits - DstBits) {
1490 APInt NewRHS =
C.zext(SrcBits);
1492 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy, NewRHS));
1500 const APInt *ShAmtC;
1521 bool YIsSExt =
false;
1524 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1525 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1526 if (Cmp.isSigned()) {
1537 if (
X->getType() !=
Y->getType() &&
1538 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1540 if (!isDesirableIntType(
X->getType()->getScalarSizeInBits()) &&
1541 isDesirableIntType(
Y->getType()->getScalarSizeInBits())) {
1543 Pred = Cmp.getSwappedPredicate(Pred);
1548 else if (!Cmp.isSigned() &&
1558 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1562 Type *TruncTy = Cmp.getOperand(0)->getType();
1567 if (isDesirableIntType(TruncBits) &&
1568 !isDesirableIntType(
X->getType()->getScalarSizeInBits()))
1591 bool TrueIfSigned =
false;
1608 if (
Xor->hasOneUse()) {
1610 if (!Cmp.isEquality() && XorC->
isSignMask()) {
1611 Pred = Cmp.getFlippedSignednessPredicate();
1612 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(),
C ^ *XorC));
1617 Pred = Cmp.getFlippedSignednessPredicate();
1618 Pred = Cmp.getSwappedPredicate(Pred);
1619 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(),
C ^ *XorC));
1626 if (*XorC == ~
C && (
C + 1).isPowerOf2())
1629 if (*XorC ==
C && (
C + 1).isPowerOf2())
1634 if (*XorC == -
C &&
C.isPowerOf2())
1636 ConstantInt::get(
X->getType(), ~
C));
1638 if (*XorC ==
C && (-
C).isPowerOf2())
1640 ConstantInt::get(
X->getType(), ~
C));
1662 const APInt *ShiftC;
1667 Type *XType =
X->getType();
1673 return new ICmpInst(Pred,
Add, ConstantInt::get(XType, Bound));
1682 if (!Shift || !Shift->
isShift())
1690 unsigned ShiftOpcode = Shift->
getOpcode();
1691 bool IsShl = ShiftOpcode == Instruction::Shl;
1694 APInt NewAndCst, NewCmpCst;
1695 bool AnyCmpCstBitsShiftedOut;
1696 if (ShiftOpcode == Instruction::Shl) {
1704 NewCmpCst = C1.
lshr(*C3);
1705 NewAndCst = C2.
lshr(*C3);
1706 AnyCmpCstBitsShiftedOut = NewCmpCst.
shl(*C3) != C1;
1707 }
else if (ShiftOpcode == Instruction::LShr) {
1712 NewCmpCst = C1.
shl(*C3);
1713 NewAndCst = C2.
shl(*C3);
1714 AnyCmpCstBitsShiftedOut = NewCmpCst.
lshr(*C3) != C1;
1720 assert(ShiftOpcode == Instruction::AShr &&
"Unknown shift opcode");
1721 NewCmpCst = C1.
shl(*C3);
1722 NewAndCst = C2.
shl(*C3);
1723 AnyCmpCstBitsShiftedOut = NewCmpCst.
ashr(*C3) != C1;
1724 if (NewAndCst.
ashr(*C3) != C2)
1728 if (AnyCmpCstBitsShiftedOut) {
1738 Shift->
getOperand(0), ConstantInt::get(
And->getType(), NewAndCst));
1739 return new ICmpInst(Cmp.getPredicate(),
1740 NewAnd, ConstantInt::get(
And->getType(), NewCmpCst));
1757 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1772 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.
isZero() &&
1774 return new TruncInst(
And->getOperand(0), Cmp.getType());
1785 ConstantInt::get(
X->getType(), ~*C2));
1790 ConstantInt::get(
X->getType(), -*C2));
1793 if (!
And->hasOneUse())
1796 if (Cmp.isEquality() && C1.
isZero()) {
1814 Constant *NegBOC = ConstantInt::get(
And->getType(), -NewC2);
1816 return new ICmpInst(NewPred,
X, NegBOC);
1834 if (!Cmp.getType()->isVectorTy()) {
1835 Type *WideType = W->getType();
1837 Constant *ZextC1 = ConstantInt::get(WideType, C1.
zext(WideScalarBits));
1838 Constant *ZextC2 = ConstantInt::get(WideType, C2->
zext(WideScalarBits));
1840 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1851 if (!Cmp.isSigned() && C1.
isZero() &&
And->getOperand(0)->hasOneUse() &&
1853 Constant *One = cast<Constant>(
And->getOperand(1));
1858 unsigned UsesRemoved = 0;
1859 if (
And->hasOneUse())
1861 if (
Or->hasOneUse())
1868 if (UsesRemoved >= RequireUsesRemoved) {
1872 One,
Or->getName());
1874 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1884 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1885 Attribute::NoImplicitFloat) &&
1888 Type *FPType = V->getType()->getScalarType();
1889 if (FPType->isIEEELikeFPTy() && C1 == *C2) {
1890 APInt ExponentMask =
1892 if (C1 == ExponentMask) {
1925 Constant *MinSignedC = ConstantInt::get(
1929 return new ICmpInst(NewPred,
X, MinSignedC);
1938 if (
auto *C2 = dyn_cast<ConstantInt>(
Y))
1939 if (
auto *LI = dyn_cast<LoadInst>(
X))
1940 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1941 if (
auto *GV = dyn_cast<GlobalVariable>(
GEP->getOperand(0)))
1946 if (!Cmp.isEquality())
1952 if (Cmp.getOperand(1) ==
Y &&
C.isNegatedPowerOf2()) {
1955 return new ICmpInst(NewPred,
X,
SubOne(cast<Constant>(Cmp.getOperand(1))));
1968 assert(Cmp.isEquality() &&
"Not expecting non-equality predicates");
1970 const APInt *TC, *FC;
1987 X->getType()->isIntOrIntVectorTy(1) && (
C.isZero() ||
C.isOne())) {
1993 return BinaryOperator::CreateAnd(TruncY,
X);
2011 const APInt *Addend, *Msk;
2014 Msk->
isMask() &&
C.ule(*Msk)) {
2015 APInt NewComperand = (
C - *Addend) & *Msk;
2041 while (!WorkList.
empty()) {
2042 auto MatchOrOperatorArgument = [&](
Value *OrOperatorArgument) {
2045 if (
match(OrOperatorArgument,
2051 if (
match(OrOperatorArgument,
2061 Value *OrOperatorLhs, *OrOperatorRhs;
2063 if (!
match(CurrentValue,
2068 MatchOrOperatorArgument(OrOperatorRhs);
2069 MatchOrOperatorArgument(OrOperatorLhs);
2075 CmpValues.
rbegin()->second);
2077 for (
auto It = CmpValues.
rbegin() + 1; It != CmpValues.
rend(); ++It) {
2079 LhsCmp = Builder.
CreateBinOp(BOpc, LhsCmp, RhsCmp);
2095 ConstantInt::get(V->getType(), 1));
2098 Value *OrOp0 =
Or->getOperand(0), *OrOp1 =
Or->getOperand(1);
2103 cast<PossiblyDisjointInst>(
Or)->isDisjoint()) {
2106 return new ICmpInst(Pred, OrOp0, NewC);
2110 if (
match(OrOp1,
m_APInt(MaskC)) && Cmp.isEquality()) {
2111 if (*MaskC ==
C && (
C + 1).isPowerOf2()) {
2116 return new ICmpInst(Pred, OrOp0, OrOp1);
2123 if (
Or->hasOneUse()) {
2125 Constant *NewC = ConstantInt::get(
Or->getType(),
C ^ (*MaskC));
2137 Constant *NewC = ConstantInt::get(
X->getType(), TrueIfSigned ? 1 : 0);
2165 if (!Cmp.isEquality() || !
C.isZero() || !
Or->hasOneUse())
2197 if (Cmp.isEquality() &&
C.isZero() &&
X ==
Mul->getOperand(1) &&
2198 (
Mul->hasNoUnsignedWrap() ||
Mul->hasNoSignedWrap()))
2220 if (Cmp.isEquality()) {
2222 if (
Mul->hasNoSignedWrap() &&
C.srem(*MulC).isZero()) {
2223 Constant *NewC = ConstantInt::get(MulTy,
C.sdiv(*MulC));
2231 if (
C.urem(*MulC).isZero()) {
2234 if ((*MulC & 1).isOne() ||
Mul->hasNoUnsignedWrap()) {
2235 Constant *NewC = ConstantInt::get(MulTy,
C.udiv(*MulC));
2248 if (
C.isMinSignedValue() && MulC->
isAllOnes())
2254 NewC = ConstantInt::get(
2258 "Unexpected predicate");
2259 NewC = ConstantInt::get(
2264 NewC = ConstantInt::get(
2268 "Unexpected predicate");
2269 NewC = ConstantInt::get(
2274 return NewC ?
new ICmpInst(Pred,
X, NewC) :
nullptr;
2286 unsigned TypeBits =
C.getBitWidth();
2288 if (Cmp.isUnsigned()) {
2308 return new ICmpInst(Pred,
Y, ConstantInt::get(ShiftType, CLog2));
2309 }
else if (Cmp.isSigned() && C2->
isOne()) {
2310 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2331 const APInt *ShiftVal;
2361 const APInt *ShiftAmt;
2367 unsigned TypeBits =
C.getBitWidth();
2368 if (ShiftAmt->
uge(TypeBits))
2380 APInt ShiftedC =
C.ashr(*ShiftAmt);
2381 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2384 C.ashr(*ShiftAmt).shl(*ShiftAmt) ==
C) {
2385 APInt ShiftedC =
C.ashr(*ShiftAmt);
2386 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2393 assert(!
C.isMinSignedValue() &&
"Unexpected icmp slt");
2394 APInt ShiftedC = (
C - 1).ashr(*ShiftAmt) + 1;
2395 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2405 APInt ShiftedC =
C.lshr(*ShiftAmt);
2406 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2409 C.lshr(*ShiftAmt).shl(*ShiftAmt) ==
C) {
2410 APInt ShiftedC =
C.lshr(*ShiftAmt);
2411 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2418 assert(
C.ugt(0) &&
"ult 0 should have been eliminated");
2419 APInt ShiftedC = (
C - 1).lshr(*ShiftAmt) + 1;
2420 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2424 if (Cmp.isEquality() && Shl->
hasOneUse()) {
2430 Constant *LShrC = ConstantInt::get(ShType,
C.lshr(*ShiftAmt));
2435 bool TrueIfSigned =
false;
2447 if (Cmp.isUnsigned() && Shl->
hasOneUse()) {
2449 if ((
C + 1).isPowerOf2() &&
2457 if (
C.isPowerOf2() &&
2486 if (
auto FlippedStrictness =
2488 Pred, ConstantInt::get(ShType->
getContext(),
C))) {
2489 CmpPred = FlippedStrictness->first;
2490 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2497 ConstantInt::get(TruncTy, RHSC.
ashr(*ShiftAmt).
trunc(TypeBits - Amt));
2516 if (Cmp.isEquality() && Shr->
isExact() &&
C.isZero())
2517 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
2519 bool IsAShr = Shr->
getOpcode() == Instruction::AShr;
2520 const APInt *ShiftValC;
2522 if (Cmp.isEquality())
2540 assert(ShiftValC->
uge(
C) &&
"Expected simplify of compare");
2541 assert((IsUGT || !
C.isZero()) &&
"Expected X u< 0 to simplify");
2543 unsigned CmpLZ = IsUGT ?
C.countl_zero() : (
C - 1).
countl_zero();
2551 const APInt *ShiftAmtC;
2557 unsigned TypeBits =
C.getBitWidth();
2559 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2562 bool IsExact = Shr->
isExact();
2570 (
C - 1).isPowerOf2() &&
C.countLeadingZeros() > ShAmtVal) {
2576 APInt ShiftedC = (
C - 1).shl(ShAmtVal) + 1;
2577 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2583 APInt ShiftedC =
C.shl(ShAmtVal);
2584 if (ShiftedC.
ashr(ShAmtVal) ==
C)
2585 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2589 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2590 if (!
C.isMaxSignedValue() && !(
C + 1).shl(ShAmtVal).isMinSignedValue() &&
2591 (ShiftedC + 1).ashr(ShAmtVal) == (
C + 1))
2592 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2598 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2599 if ((ShiftedC + 1).ashr(ShAmtVal) == (
C + 1) ||
2600 (
C + 1).shl(ShAmtVal).isMinSignedValue())
2601 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2608 if (
C.getBitWidth() > 2 &&
C.getNumSignBits() <= ShAmtVal) {
2618 }
else if (!IsAShr) {
2622 APInt ShiftedC =
C.shl(ShAmtVal);
2623 if (ShiftedC.
lshr(ShAmtVal) ==
C)
2624 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2628 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2629 if ((ShiftedC + 1).lshr(ShAmtVal) == (
C + 1))
2630 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2634 if (!Cmp.isEquality())
2642 assert(((IsAShr &&
C.shl(ShAmtVal).ashr(ShAmtVal) ==
C) ||
2643 (!IsAShr &&
C.shl(ShAmtVal).lshr(ShAmtVal) ==
C)) &&
2644 "Expected icmp+shr simplify did not occur.");
2649 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy,
C << ShAmtVal));
2655 ConstantInt::get(ShrTy, (
C + 1).shl(ShAmtVal)));
2658 ConstantInt::get(ShrTy, (
C + 1).shl(ShAmtVal) - 1));
2665 Constant *Mask = ConstantInt::get(ShrTy, Val);
2667 return new ICmpInst(Pred,
And, ConstantInt::get(ShrTy,
C << ShAmtVal));
2690 const APInt *DivisorC;
2699 !
C.isStrictlyPositive()))
2705 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2709 return new ICmpInst(Pred,
And, ConstantInt::get(Ty,
C));
2736 assert(*C2 != 0 &&
"udiv 0, X should have been simplified already.");
2741 "icmp ugt X, UINT_MAX should have been simplified already.");
2743 ConstantInt::get(Ty, C2->
udiv(
C + 1)));
2748 assert(
C != 0 &&
"icmp ult X, 0 should have been simplified already.");
2750 ConstantInt::get(Ty, C2->
udiv(
C)));
2764 bool DivIsSigned = Div->
getOpcode() == Instruction::SDiv;
2774 if (Cmp.isEquality() && Div->
hasOneUse() &&
C.isSignBitSet() &&
2775 (!DivIsSigned ||
C.isMinSignedValue())) {
2800 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2819 bool ProdOV = (DivIsSigned ? Prod.
sdiv(*C2) : Prod.
udiv(*C2)) !=
C;
2832 int LoOverflow = 0, HiOverflow = 0;
2833 APInt LoBound, HiBound;
2838 HiOverflow = LoOverflow = ProdOV;
2847 LoBound = -(RangeSize - 1);
2848 HiBound = RangeSize;
2849 }
else if (
C.isStrictlyPositive()) {
2851 HiOverflow = LoOverflow = ProdOV;
2857 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2859 APInt DivNeg = -RangeSize;
2860 LoOverflow =
addWithOverflow(LoBound, HiBound, DivNeg,
true) ? -1 : 0;
2868 LoBound = RangeSize + 1;
2869 HiBound = -RangeSize;
2870 if (HiBound == *C2) {
2874 }
else if (
C.isStrictlyPositive()) {
2877 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2883 LoOverflow = HiOverflow = ProdOV;
2896 if (LoOverflow && HiOverflow)
2900 X, ConstantInt::get(Ty, LoBound));
2903 X, ConstantInt::get(Ty, HiBound));
2907 if (LoOverflow && HiOverflow)
2911 X, ConstantInt::get(Ty, LoBound));
2914 X, ConstantInt::get(Ty, HiBound));
2919 if (LoOverflow == +1)
2921 if (LoOverflow == -1)
2923 return new ICmpInst(Pred,
X, ConstantInt::get(Ty, LoBound));
2926 if (HiOverflow == +1)
2928 if (HiOverflow == -1)
2961 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2963 return new ICmpInst(SwappedPred,
Y, ConstantInt::get(Ty, SubResult));
2971 if (Cmp.isEquality() &&
C.isZero() &&
3007 (*C2 & (
C - 1)) == (
C - 1))
3020 return new ICmpInst(SwappedPred,
Add, ConstantInt::get(Ty, ~
C));
3026 auto FoldConstant = [&](
bool Val) {
3030 cast<VectorType>(Op0->
getType())->getElementCount(), Res);
3034 switch (Table.to_ulong()) {
3036 return FoldConstant(
false);
3066 return FoldConstant(
true);
3089 unsigned BW =
C.getBitWidth();
3090 std::bitset<4> Table;
3091 auto ComputeTable = [&](
bool Op0Val,
bool Op1Val) {
3094 Res += isa<ZExtInst>(Ext0) ? 1 : -1;
3096 Res += isa<ZExtInst>(Ext1) ? 1 : -1;
3100 Table[0] = ComputeTable(
false,
false);
3101 Table[1] = ComputeTable(
false,
true);
3102 Table[2] = ComputeTable(
true,
false);
3103 Table[3] = ComputeTable(
true,
true);
3118 if ((
Add->hasNoSignedWrap() &&
3120 (
Add->hasNoUnsignedWrap() &&
3124 Cmp.isSigned() ?
C.ssub_ov(*C2, Overflow) :
C.usub_ov(*C2, Overflow);
3130 return new ICmpInst(Pred,
X, ConstantInt::get(Ty, NewC));
3134 C.isNonNegative() && (
C - *C2).isNonNegative() &&
3137 ConstantInt::get(Ty,
C - *C2));
3142 if (Cmp.isSigned()) {
3143 if (
Lower.isSignMask())
3145 if (
Upper.isSignMask())
3148 if (
Lower.isMinValue())
3150 if (
Upper.isMinValue())
3183 if (!
Add->hasOneUse())
3198 ConstantInt::get(Ty,
C * 2));
3213 ConstantInt::get(Ty, ~
C));
3218 Type *NewCmpTy = V->getType();
3220 if (shouldChangeType(Ty, NewCmpTy)) {
3221 if (CR.getActiveBits() <= NewCmpBW) {
3233 ConstantInt::get(NewCmpTy, EquivInt));
3256 Value *EqualVal = SI->getTrueValue();
3257 Value *UnequalVal = SI->getFalseValue();
3280 auto FlippedStrictness =
3282 PredB, cast<Constant>(RHS2));
3283 if (!FlippedStrictness)
3286 "basic correctness failure");
3287 RHS2 = FlippedStrictness->second;
3299 assert(
C &&
"Cmp RHS should be a constant int!");
3305 Value *OrigLHS, *OrigRHS;
3306 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3307 if (Cmp.hasOneUse() &&
3310 assert(C1LessThan && C2Equal && C3GreaterThan);
3313 C1LessThan->
getValue(),
C->getValue(), Cmp.getPredicate());
3315 Cmp.getPredicate());
3317 C3GreaterThan->
getValue(),
C->getValue(), Cmp.getPredicate());
3328 if (TrueWhenLessThan)
3334 if (TrueWhenGreaterThan)
3344 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3349 Value *Op1 = Cmp.getOperand(1);
3350 Value *BCSrcOp = Bitcast->getOperand(0);
3351 Type *SrcType = Bitcast->getSrcTy();
3352 Type *DstType = Bitcast->getType();
3372 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(), 1));
3399 Type *XType =
X->getType();
3404 if (
auto *XVTy = dyn_cast<VectorType>(XType))
3418 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3419 Attribute::NoImplicitFloat) &&
3420 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3444 if (Cmp.isEquality() &&
C->isAllOnes() && Bitcast->hasOneUse()) {
3445 if (
Value *NotBCSrcOp =
3456 if (Cmp.isEquality() &&
C->isZero() && Bitcast->hasOneUse() &&
3458 if (
auto *VecTy = dyn_cast<FixedVectorType>(
X->getType())) {
3477 auto *VecTy = cast<VectorType>(SrcType);
3478 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3479 if (
C->isSplat(EltTy->getBitWidth())) {
3487 Value *NewC = ConstantInt::get(EltTy,
C->trunc(EltTy->getBitWidth()));
3488 return new ICmpInst(Pred, Extract, NewC);
3501 if (
auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3505 if (
auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3509 if (
auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3513 if (
auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3517 if (
auto *
II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3524 Value *Cmp0 = Cmp.getOperand(0);
3526 if (
C->isZero() && Cmp.isEquality() && Cmp0->
hasOneUse() &&
3528 m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3531 m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3533 return new ICmpInst(Cmp.getPredicate(),
X,
Y);
3548 if (!Cmp.isEquality())
3553 Constant *
RHS = cast<Constant>(Cmp.getOperand(1));
3557 case Instruction::SRem:
3568 case Instruction::Add: {
3572 if (
Constant *C2 = dyn_cast<Constant>(BOp1)) {
3575 }
else if (
C.isZero()) {
3578 if (
Value *NegVal = dyn_castNegVal(BOp1))
3579 return new ICmpInst(Pred, BOp0, NegVal);
3580 if (
Value *NegVal = dyn_castNegVal(BOp0))
3581 return new ICmpInst(Pred, NegVal, BOp1);
3590 return new ICmpInst(Pred, BOp0, Neg);
3595 case Instruction::Xor:
3596 if (
Constant *BOC = dyn_cast<Constant>(BOp1)) {
3600 }
else if (
C.isZero()) {
3602 return new ICmpInst(Pred, BOp0, BOp1);
3605 case Instruction::Or: {
3626 Cond->getType() == Cmp.getType()) {
3664 case Instruction::UDiv:
3665 case Instruction::SDiv:
3675 return new ICmpInst(Pred, BOp0, BOp1);
3678 Instruction::Mul, BO->
getOpcode() == Instruction::SDiv, BOp1,
3679 Cmp.getOperand(1), BO);
3683 return new ICmpInst(Pred, YC, BOp0);
3687 if (BO->
getOpcode() == Instruction::UDiv &&
C.isZero()) {
3690 return new ICmpInst(NewPred, BOp1, BOp0);
3704 "Non-ctpop intrin in ctpop fold");
3740 Type *Ty =
II->getType();
3744 switch (
II->getIntrinsicID()) {
3745 case Intrinsic::abs:
3748 if (
C.isZero() ||
C.isMinSignedValue())
3749 return new ICmpInst(Pred,
II->getArgOperand(0), ConstantInt::get(Ty,
C));
3752 case Intrinsic::bswap:
3754 return new ICmpInst(Pred,
II->getArgOperand(0),
3755 ConstantInt::get(Ty,
C.byteSwap()));
3757 case Intrinsic::bitreverse:
3759 return new ICmpInst(Pred,
II->getArgOperand(0),
3760 ConstantInt::get(Ty,
C.reverseBits()));
3762 case Intrinsic::ctlz:
3763 case Intrinsic::cttz: {
3766 return new ICmpInst(Pred,
II->getArgOperand(0),
3772 unsigned Num =
C.getLimitedValue(
BitWidth);
3774 bool IsTrailing =
II->getIntrinsicID() == Intrinsic::cttz;
3777 APInt Mask2 = IsTrailing
3781 ConstantInt::get(Ty, Mask2));
3786 case Intrinsic::ctpop: {
3789 bool IsZero =
C.isZero();
3791 return new ICmpInst(Pred,
II->getArgOperand(0),
3798 case Intrinsic::fshl:
3799 case Intrinsic::fshr:
3800 if (
II->getArgOperand(0) ==
II->getArgOperand(1)) {
3801 const APInt *RotAmtC;
3805 return new ICmpInst(Pred,
II->getArgOperand(0),
3806 II->getIntrinsicID() == Intrinsic::fshl
3807 ? ConstantInt::get(Ty,
C.rotr(*RotAmtC))
3808 : ConstantInt::get(Ty,
C.rotl(*RotAmtC)));
3812 case Intrinsic::umax:
3813 case Intrinsic::uadd_sat: {
3816 if (
C.isZero() &&
II->hasOneUse()) {
3823 case Intrinsic::ssub_sat:
3826 return new ICmpInst(Pred,
II->getArgOperand(0),
II->getArgOperand(1));
3828 case Intrinsic::usub_sat: {
3833 return new ICmpInst(NewPred,
II->getArgOperand(0),
II->getArgOperand(1));
3848 assert(Cmp.isEquality());
3851 Value *Op0 = Cmp.getOperand(0);
3852 Value *Op1 = Cmp.getOperand(1);
3853 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3854 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3855 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3858 switch (IIOp0->getIntrinsicID()) {
3859 case Intrinsic::bswap:
3860 case Intrinsic::bitreverse:
3863 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3864 case Intrinsic::fshl:
3865 case Intrinsic::fshr: {
3868 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3870 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3872 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
3873 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3879 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3884 Builder.
CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
3886 Op0->
getType(), IIOp0->getIntrinsicID(),
3887 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
3888 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
3905 if (
auto *
II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3906 switch (
II->getIntrinsicID()) {
3909 case Intrinsic::fshl:
3910 case Intrinsic::fshr:
3911 if (Cmp.isEquality() &&
II->getArgOperand(0) ==
II->getArgOperand(1)) {
3913 if (
C.isZero() ||
C.isAllOnes())
3914 return new ICmpInst(Pred,
II->getArgOperand(0), Cmp.getOperand(1));
3928 case Instruction::Xor:
3932 case Instruction::And:
3936 case Instruction::Or:
3940 case Instruction::Mul:
3944 case Instruction::Shl:
3948 case Instruction::LShr:
3949 case Instruction::AShr:
3953 case Instruction::SRem:
3957 case Instruction::UDiv:
3961 case Instruction::SDiv:
3965 case Instruction::Sub:
3969 case Instruction::Add:
3987 if (!
II->hasOneUse())
4003 Value *Op0 =
II->getOperand(0);
4004 Value *Op1 =
II->getOperand(1);
4013 switch (
II->getIntrinsicID()) {
4016 "This function only works with usub_sat and uadd_sat for now!");
4017 case Intrinsic::uadd_sat:
4020 case Intrinsic::usub_sat:
4030 II->getBinaryOp(), *COp1,
II->getNoWrapKind());
4037 if (
II->getBinaryOp() == Instruction::Add)
4043 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4045 std::optional<ConstantRange> Combination;
4046 if (CombiningOp == Instruction::BinaryOps::Or)
4058 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4063 ConstantInt::get(Op1->
getType(), EquivInt));
4070 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4075 NewPredicate = Pred;
4079 else if (
C.isAllOnes())
4087 else if (
C.isZero())
4104 if (!
C.isZero() && !
C.isAllOnes())
4115 if (
I->getIntrinsicID() == Intrinsic::scmp)
4129 switch (
II->getIntrinsicID()) {
4132 case Intrinsic::uadd_sat:
4133 case Intrinsic::usub_sat:
4138 case Intrinsic::ctpop: {
4143 case Intrinsic::scmp:
4144 case Intrinsic::ucmp:
4150 if (Cmp.isEquality())
4153 Type *Ty =
II->getType();
4155 switch (
II->getIntrinsicID()) {
4156 case Intrinsic::ctpop: {
4168 case Intrinsic::ctlz: {
4171 unsigned Num =
C.getLimitedValue();
4174 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4179 unsigned Num =
C.getLimitedValue();
4182 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4186 case Intrinsic::cttz: {
4188 if (!
II->hasOneUse())
4208 case Intrinsic::ssub_sat:
4212 return new ICmpInst(Pred,
II->getArgOperand(0),
II->getArgOperand(1));
4216 II->getArgOperand(1));
4220 II->getArgOperand(1));
4232 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
4233 Constant *RHSC = dyn_cast<Constant>(Op1);
4239 case Instruction::PHI:
4243 case Instruction::IntToPtr:
4252 case Instruction::Load:
4255 dyn_cast<GetElementPtrInst>(LHSI->
getOperand(0)))
4270 auto SimplifyOp = [&](
Value *
Op,
bool SelectCondIsTrue) ->
Value * {