31 #define DEBUG_TYPE "instcombine" 34 STATISTIC(NumSel,
"Number of select opts");
40 const APInt &In2,
bool IsSigned =
false) {
43 Result = In1.
sadd_ov(In2, Overflow);
45 Result = In1.
uadd_ov(In2, Overflow);
53 const APInt &In2,
bool IsSigned =
false) {
56 Result = In1.
ssub_ov(In2, Overflow);
58 Result = In1.
usub_ov(In2, Overflow);
66 for (
auto *U : I.
users())
67 if (isa<BranchInst>(U))
106 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
112 Max = Known.
One|UnknownBits;
114 if (UnknownBits.isNegative()) {
128 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
134 Max = Known.
One|UnknownBits;
150 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
155 if (ArrayElementCount > MaxArraySizeForCombine)
176 if (!Idx)
return nullptr;
179 if ((
unsigned)IdxVal != IdxVal)
return nullptr;
181 if (
StructType *STy = dyn_cast<StructType>(EltTy))
182 EltTy = STy->getElementType(IdxVal);
183 else if (
ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
184 if (IdxVal >= ATy->getNumElements())
return nullptr;
185 EltTy = ATy->getElementType();
193 enum { Overdefined = -3, Undefined = -2 };
202 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
206 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
214 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
219 uint64_t MagicBitvector = 0;
223 for (
unsigned i = 0,
e = ArrayElementCount; i !=
e; ++i) {
225 if (!Elt)
return nullptr;
228 if (!LaterIndices.
empty())
236 CompareRHS, DL, &TLI);
238 if (isa<UndefValue>(C)) {
241 if (TrueRangeEnd == (
int)i-1)
243 if (FalseRangeEnd == (
int)i-1)
250 if (!isa<ConstantInt>(C))
return nullptr;
254 bool IsTrueForElt = !cast<ConstantInt>(
C)->
isZero();
259 if (FirstTrueElement == Undefined)
260 FirstTrueElement = TrueRangeEnd = i;
263 if (SecondTrueElement == Undefined)
264 SecondTrueElement = i;
266 SecondTrueElement = Overdefined;
269 if (TrueRangeEnd == (
int)i-1)
272 TrueRangeEnd = Overdefined;
276 if (FirstFalseElement == Undefined)
277 FirstFalseElement = FalseRangeEnd = i;
280 if (SecondFalseElement == Undefined)
281 SecondFalseElement = i;
283 SecondFalseElement = Overdefined;
286 if (FalseRangeEnd == (
int)i-1)
289 FalseRangeEnd = Overdefined;
294 if (i < 64 && IsTrueForElt)
295 MagicBitvector |= 1ULL << i;
300 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
301 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
302 FalseRangeEnd == Overdefined)
317 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
322 if (SecondTrueElement != Overdefined) {
324 if (FirstTrueElement == Undefined)
325 return replaceInstUsesWith(ICI, Builder.getFalse());
330 if (SecondTrueElement == Undefined)
334 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
336 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
337 return BinaryOperator::CreateOr(C1, C2);
342 if (SecondFalseElement != Overdefined) {
344 if (FirstFalseElement == Undefined)
345 return replaceInstUsesWith(ICI, Builder.getTrue());
350 if (SecondFalseElement == Undefined)
354 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
356 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
357 return BinaryOperator::CreateAnd(C1, C2);
362 if (TrueRangeEnd != Overdefined) {
363 assert(TrueRangeEnd != FirstTrueElement &&
"Should emit single compare");
366 if (FirstTrueElement) {
368 Idx = Builder.CreateAdd(Idx, Offs);
372 TrueRangeEnd-FirstTrueElement+1);
377 if (FalseRangeEnd != Overdefined) {
378 assert(FalseRangeEnd != FirstFalseElement &&
"Should emit single compare");
380 if (FirstFalseElement) {
382 Idx = Builder.CreateAdd(Idx, Offs);
386 FalseRangeEnd-FirstFalseElement);
399 if (ArrayElementCount <= Idx->
getType()->getIntegerBitWidth())
402 Ty = DL.getSmallestLegalIntType(Init->
getContext(), ArrayElementCount);
405 Value *V = Builder.CreateIntCast(Idx, Ty,
false);
436 for (i = 1; i !=
e; ++i, ++GTI) {
439 if (CI->isZero())
continue;
446 Offset += Size*CI->getSExtValue();
456 if (i == e)
return nullptr;
464 for (++i, ++GTI; i !=
e; ++i, ++GTI) {
466 if (!CI)
return nullptr;
469 if (CI->
isZero())
continue;
498 VariableScale =
SignExtend64(VariableScale, IntPtrWidth);
504 int64_t NewOffs = Offset / (int64_t)VariableScale;
505 if (Offset != NewOffs*(int64_t)VariableScale)
509 if (VariableIdx->
getType() != IntPtrTy)
533 while (!WorkList.
empty()) {
536 while (!WorkList.
empty()) {
537 if (Explored.
size() >= 100)
542 if (Explored.
count(V) != 0) {
547 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
548 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
553 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
555 if (!CI->isNoopCast(DL))
558 if (Explored.
count(CI->getOperand(0)) == 0)
562 if (
auto *GEP = dyn_cast<GEPOperator>(V)) {
574 if (WorkList.
back() == V) {
580 if (
auto *PN = dyn_cast<PHINode>(V)) {
582 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
590 for (
auto *PN : PHIs)
591 for (
Value *
Op : PN->incoming_values())
599 for (
Value *Val : Explored) {
605 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
606 Explored.count(PHI) == 0)
609 if (PHI->getParent() == Inst->getParent())
619 bool Before =
true) {
620 if (
auto *PHI = dyn_cast<PHINode>(V)) {
621 Builder.
SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
624 if (
auto *
I = dyn_cast<Instruction>(V)) {
626 I = &*std::next(
I->getIterator());
630 if (
auto *A = dyn_cast<Argument>(V)) {
638 assert(isa<Constant>(V) &&
"Setting insertion point for unknown value!");
660 for (
Value *Val : Explored) {
665 if (
auto *PHI = dyn_cast<PHINode>(Val))
666 NewInsts[PHI] =
PHINode::Create(IndexType, PHI->getNumIncomingValues(),
667 PHI->getName() +
".idx", PHI);
672 for (
Value *Val : Explored) {
674 if (NewInsts.
find(Val) != NewInsts.
end())
677 if (
auto *CI = dyn_cast<CastInst>(Val)) {
680 Value *V = NewInsts[CI->getOperand(0)];
684 if (
auto *GEP = dyn_cast<GEPOperator>(Val)) {
691 NewInsts[GEP->
getOperand(0)]->getType()->getScalarSizeInBits()) {
692 Index = Builder.CreateSExtOrTrunc(
693 Index, NewInsts[GEP->
getOperand(0)]->getType(),
698 if (isa<ConstantInt>(
Op) && cast<ConstantInt>(
Op)->
isZero())
701 NewInsts[
GEP] = Builder.CreateNSWAdd(
705 if (isa<PHINode>(Val))
712 for (
Value *Val : Explored) {
717 if (
auto *PHI = dyn_cast<PHINode>(Val)) {
719 for (
unsigned I = 0,
E = PHI->getNumIncomingValues();
I <
E; ++
I) {
720 Value *NewIncoming = PHI->getIncomingValue(
I);
722 if (NewInsts.
find(NewIncoming) != NewInsts.
end())
723 NewIncoming = NewInsts[NewIncoming];
725 NewPhi->
addIncoming(NewIncoming, PHI->getIncomingBlock(
I));
730 for (
Value *Val : Explored) {
739 Value *NewBase = Base;
741 NewBase = Builder.CreateBitOrPointerCast(Base, Start->
getType(),
744 Value *GEP = Builder.CreateInBoundsGEP(
748 if (!Val->getType()->isPointerTy()) {
749 Value *Cast = Builder.CreatePointerCast(GEP, Val->
getType(),
750 Val->getName() +
".conv");
756 return NewInsts[Start];
762 static std::pair<Value *, Value *>
784 if (
auto *CI = dyn_cast<IntToPtrInst>(V)) {
785 if (!CI->isNoopCast(DL))
787 V = CI->getOperand(0);
790 if (
auto *CI = dyn_cast<PtrToIntInst>(V)) {
791 if (!CI->isNoopCast(DL))
793 V = CI->getOperand(0);
857 if (!isa<GetElementPtrInst>(RHS))
878 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
901 Base = Builder.CreateVectorSplat(NumElts,
Base);
905 cast<Constant>(RHS),
Base->getType()));
906 }
else if (
GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
909 if (PtrBase != GEPRHS->getOperand(0)) {
910 bool IndicesTheSame = GEPLHS->
getNumOperands()==GEPRHS->getNumOperands();
912 GEPRHS->getOperand(0)->getType();
915 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
916 IndicesTheSame =
false;
929 if (GEPLHS->
isInBounds() && GEPRHS->isInBounds() &&
931 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
943 if (LHSIndexTy != RHSIndexTy) {
946 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
948 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
953 return replaceInstUsesWith(I, Cmp);
965 return foldGEPICmp(GEPRHS, GEPLHS->
getOperand(0),
970 if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
971 return foldGEPICmp(GEPLHS, GEPRHS->
getOperand(0), Cond,
I);
973 bool GEPsInBounds = GEPLHS->
isInBounds() && GEPRHS->isInBounds();
976 unsigned NumDifferences = 0;
977 unsigned DiffOperand = 0;
978 for (
unsigned i = 1,
e = GEPRHS->getNumOperands(); i !=
e; ++i)
979 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
981 Type *RHSType = GEPRHS->getOperand(i)->getType();
992 if (NumDifferences++)
break;
996 if (NumDifferences == 0)
997 return replaceInstUsesWith(I,
1000 else if (NumDifferences == 1 && GEPsInBounds) {
1002 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1010 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->
hasOneUse()) &&
1011 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1043 unsigned MaxIter = 32;
1046 for (
const Use &U : Alloca->
uses()) {
1047 if (Worklist.
size() >= MaxIter)
1052 unsigned NumCmps = 0;
1053 while (!Worklist.
empty()) {
1056 const Value *V = U->getUser();
1059 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1060 isa<SelectInst>(V)) {
1062 }
else if (isa<LoadInst>(V)) {
1065 }
else if (
const auto *
SI = dyn_cast<StoreInst>(V)) {
1067 if (
SI->getValueOperand() == U->get())
1070 }
else if (isa<ICmpInst>(V)) {
1074 }
else if (
const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1075 switch (Intrin->getIntrinsicID()) {
1079 case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
1080 case Intrinsic::memcpy:
case Intrinsic::memmove:
case Intrinsic::memset:
1088 for (
const Use &U : V->
uses()) {
1089 if (Worklist.
size() >= MaxIter)
1096 return replaceInstUsesWith(
1107 assert(!!C &&
"C should not be zero!");
1160 return new ICmpInst(Pred, LHS, RHS);
1167 bool IsAShr = isa<AShrOperator>(I.
getOperand(0));
1192 if (IsAShr && AP1 == AP2.
ashr(Shift)) {
1198 }
else if (AP1 == AP2.
lshr(Shift)) {
1206 return replaceInstUsesWith(I, TorF);
1219 return new ICmpInst(Pred, LHS, RHS);
1228 if (!AP1 && AP2TrailingZeros != 0)
1239 if (Shift > 0 && AP2.
shl(Shift) == AP1)
1245 return replaceInstUsesWith(I, TorF);
1273 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1287 unsigned NeededSignBits = CI1->
getBitWidth() - NewWidth + 1;
1298 if (U == AddWithCst)
1316 I.
getModule(), Intrinsic::sadd_with_overflow, NewType);
1324 Value *TruncA = Builder.CreateTrunc(A, NewType, A->
getName() +
".trunc");
1325 Value *TruncB = Builder.CreateTrunc(B, NewType, B->
getName() +
".trunc");
1326 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB},
"sadd");
1327 Value *
Add = Builder.CreateExtractValue(Call, 0,
"sadd.result");
1328 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->
getType());
1355 Value *Masked = Builder.CreateAnd(X, Mask);
1375 APInt(XBitWidth, XBitWidth - 1))))
1377 }
else if (isa<BinaryOperator>(Val) &&
1378 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1379 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1409 if (
Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1471 assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1472 "Predecessor block does not point to successor?");
1475 if (TrueBB == FalseBB)
1504 return replaceInstUsesWith(Cmp, Builder.getFalse());
1506 return replaceInstUsesWith(Cmp, Builder.getTrue());
1549 if ((Known.
Zero | Known.
One).countLeadingOnes() >= SrcBits - DstBits) {
1573 bool TrueIfSigned =
false;
1613 if (*XorC == ~C && (C + 1).isPowerOf2())
1616 if (*XorC == C && (C + 1).isPowerOf2())
1636 if (!Shift || !Shift->
isShift())
1644 unsigned ShiftOpcode = Shift->
getOpcode();
1645 bool IsShl = ShiftOpcode == Instruction::Shl;
1648 bool CanFold =
false;
1649 if (ShiftOpcode == Instruction::Shl) {
1657 bool IsAshr = ShiftOpcode == Instruction::AShr;
1666 if (!IsAshr || (C2.
shl(*C3).
lshr(*C3) == C2)) {
1675 APInt SameAsC1 = IsShl ? NewCst.
shl(*C3) : NewCst.
lshr(*C3);
1677 if (SameAsC1 != C1) {
1690 Worklist.Add(Shift);
1740 if (C2->isSignMask()) {
1743 return new ICmpInst(NewPred, X, Zero);
1748 if ((~(*C2) + 1).isPowerOf2()) {
1752 return new ICmpInst(NewPred, X, NegBOC);
1775 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->
getName());
1780 if (
Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1794 unsigned UsesRemoved = 0;
1797 if (Or->hasOneUse())
1803 Value *NewOr =
nullptr;
1804 if (
auto *C = dyn_cast<Constant>(B)) {
1805 if (UsesRemoved >= 1)
1808 if (UsesRemoved >= 3)
1809 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->
getName(),
1814 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->
getName());
1828 if (
Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1836 if (
auto *LI = dyn_cast<LoadInst>(X))
1837 if (
auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1838 if (
auto *GV = dyn_cast<GlobalVariable>(GEP->
getOperand(0)))
1840 !LI->isVolatile() && isa<ConstantInt>(
Y)) {
1842 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
1852 if (Cmp.
getOperand(1) == Y && (-
C).isPowerOf2()) {
1864 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1868 Value *Trunc = Builder.CreateTrunc(X, NTy);
1895 if ((C + 1).isPowerOf2()) {
1897 return new ICmpInst(Pred, OrOp0, OrOp1);
1903 Value *A = Builder.CreateAnd(OrOp0, ~C);
1925 Value *X1, *X2, *X3, *X4;
1930 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1931 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1987 if (CLog2 == TypeBits - 1) {
2015 }
else if (Cmp.
isEquality() && CIsPowerOf2) {
2026 const APInt *ShiftVal;
2028 return foldICmpShlConstConst(Cmp, Shl->
getOperand(1),
C, *ShiftVal);
2030 const APInt *ShiftAmt;
2037 if (ShiftAmt->uge(TypeBits))
2054 C.
ashr(*ShiftAmt).
shl(*ShiftAmt) ==
C) {
2064 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2084 C.
lshr(*ShiftAmt).
shl(*ShiftAmt) ==
C) {
2093 assert(C.
ugt(0) &&
"ult 0 should have been eliminated");
2094 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2104 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
2106 return new ICmpInst(Pred, And, LShrC);
2110 bool TrueIfSigned =
false;
2116 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
2124 if ((C + 1).isPowerOf2() &&
2126 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2135 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2148 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2150 DL.isLegalInteger(TypeBits - Amt)) {
2156 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2174 const APInt *ShiftVal;
2176 return foldICmpShrConstConst(Cmp, Shr->
getOperand(1),
C, *ShiftVal);
2178 const APInt *ShiftAmt;
2185 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
2186 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2189 bool IsAShr = Shr->
getOpcode() == Instruction::AShr;
2190 bool IsExact = Shr->
isExact();
2201 if (ShiftedC.
ashr(ShAmtVal) ==
C)
2206 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2208 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2216 if (ShiftedC.
lshr(ShAmtVal) ==
C)
2221 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2222 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2236 (!IsAShr && C.
shl(ShAmtVal).
lshr(ShAmtVal) ==
C)) &&
2237 "Expected icmp+shr simplify did not occur.");
2249 Value *And = Builder.CreateAnd(X, Mask, Shr->
getName() +
".mask");
2272 const APInt *DivisorC;
2302 assert(*C2 != 0 &&
"udiv 0, X should have been simplified already.");
2308 "icmp ugt X, UINT_MAX should have been simplified already.");
2315 assert(C != 0 &&
"icmp ult X, 0 should have been simplified already.");
2345 bool DivIsSigned = Div->
getOpcode() == Instruction::SDiv;
2361 APInt Prod = C * *C2;
2366 bool ProdOV = (DivIsSigned ? Prod.
sdiv(*C2) : Prod.
udiv(*C2)) != C;
2381 int LoOverflow = 0, HiOverflow = 0;
2382 APInt LoBound, HiBound;
2387 HiOverflow = LoOverflow = ProdOV;
2393 }
else if (C2->isStrictlyPositive()) {
2396 LoBound = -(RangeSize - 1);
2397 HiBound = RangeSize;
2400 HiOverflow = LoOverflow = ProdOV;
2406 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2408 APInt DivNeg = -RangeSize;
2409 LoOverflow =
addWithOverflow(LoBound, HiBound, DivNeg,
true) ? -1 : 0;
2412 }
else if (C2->isNegative()) {
2417 LoBound = RangeSize + 1;
2418 HiBound = -RangeSize;
2419 if (HiBound == *C2) {
2426 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2428 LoOverflow =
addWithOverflow(LoBound, HiBound, RangeSize,
true) ? -1:0;
2431 LoOverflow = HiOverflow = ProdOV;
2444 if (LoOverflow && HiOverflow)
2445 return replaceInstUsesWith(Cmp, Builder.getFalse());
2454 return replaceInstUsesWith(
2455 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned,
true));
2457 if (LoOverflow && HiOverflow)
2458 return replaceInstUsesWith(Cmp, Builder.getTrue());
2461 ICmpInst::ICMP_ULT, X,
2465 ICmpInst::ICMP_UGE, X,
2467 return replaceInstUsesWith(Cmp,
2468 insertRangeTest(X, LoBound, HiBound,
2469 DivIsSigned,
false));
2472 if (LoOverflow == +1)
2473 return replaceInstUsesWith(Cmp, Builder.getTrue());
2474 if (LoOverflow == -1)
2475 return replaceInstUsesWith(Cmp, Builder.getFalse());
2479 if (HiOverflow == +1)
2480 return replaceInstUsesWith(Cmp, Builder.getFalse());
2481 if (HiOverflow == -1)
2482 return replaceInstUsesWith(Cmp, Builder.getTrue());
2484 return new ICmpInst(ICmpInst::ICMP_UGE, X,
2544 (*C2 & (C - 1)) == (C - 1))
2589 const APInt &Lower = CR.getLower();
2661 auto FlippedStrictness =
2663 if (!FlippedStrictness)
2666 RHS2 = FlippedStrictness->second;
2678 assert(C &&
"Cmp RHS should be a constant int!");
2684 Value *OrigLHS, *OrigRHS;
2685 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2687 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2689 assert(C1LessThan && C2Equal && C3GreaterThan);
2691 bool TrueWhenLessThan =
2694 bool TrueWhenEqual =
2697 bool TrueWhenGreaterThan =
2709 Value *Cond = Builder.getFalse();
2710 if (TrueWhenLessThan)
2716 if (TrueWhenGreaterThan)
2720 return replaceInstUsesWith(Cmp, Cond);
2736 if (
Bitcast->getSrcTy()->getScalarSizeInBits() ==
2737 Bitcast->getDestTy()->getScalarSizeInBits()) {
2770 if (
Bitcast->getType()->isPointerTy() &&
2771 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2774 if (
auto *BC2 = dyn_cast<BitCastInst>(Op1))
2775 Op1 = BC2->getOperand(0);
2778 return new ICmpInst(Pred, BCSrcOp, Op1);
2790 !
Bitcast->getType()->isIntegerTy() ||
2791 !
Bitcast->getSrcTy()->isIntOrIntVectorTy())
2799 if (
auto *Elem = dyn_cast_or_null<ConstantInt>(Mask->
getSplatValue())) {
2800 auto *VecTy = cast<VectorType>(BCSrcOp->
getType());
2801 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
2802 if (C->
isSplat(EltTy->getBitWidth())) {
2810 return new ICmpInst(Pred, Extract, NewC);
2824 if (
auto *BO = dyn_cast<BinaryOperator>(Cmp.
getOperand(0))) {
2825 switch (BO->getOpcode()) {
2826 case Instruction::Xor:
2827 if (
Instruction *I = foldICmpXorConstant(Cmp, BO, *C))
2830 case Instruction::And:
2831 if (
Instruction *I = foldICmpAndConstant(Cmp, BO, *C))
2834 case Instruction::Or:
2835 if (
Instruction *I = foldICmpOrConstant(Cmp, BO, *C))
2838 case Instruction::Mul:
2839 if (
Instruction *I = foldICmpMulConstant(Cmp, BO, *C))
2842 case Instruction::Shl:
2843 if (
Instruction *I = foldICmpShlConstant(Cmp, BO, *C))
2846 case Instruction::LShr:
2847 case Instruction::AShr:
2848 if (
Instruction *I = foldICmpShrConstant(Cmp, BO, *C))
2851 case Instruction::SRem:
2852 if (
Instruction *I = foldICmpSRemConstant(Cmp, BO, *C))
2855 case Instruction::UDiv:
2856 if (
Instruction *I = foldICmpUDivConstant(Cmp, BO, *C))
2859 case Instruction::SDiv:
2860 if (
Instruction *I = foldICmpDivConstant(Cmp, BO, *C))
2863 case Instruction::Sub:
2864 if (
Instruction *I = foldICmpSubConstant(Cmp, BO, *C))
2868 if (
Instruction *I = foldICmpAddConstant(Cmp, BO, *C))
2875 if (
Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C))
2881 if (
auto *SI = dyn_cast<SelectInst>(Cmp.
getOperand(0))) {
2886 if (
Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
2890 if (
auto *TI = dyn_cast<TruncInst>(Cmp.
getOperand(0))) {
2891 if (
Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
2895 if (
auto *II = dyn_cast<IntrinsicInst>(Cmp.
getOperand(0)))
2896 if (
Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
2918 case Instruction::SRem:
2923 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->
getName());
2935 return new ICmpInst(Pred, BOp0, SubC);
2940 if (
Value *NegVal = dyn_castNegVal(BOp1))
2941 return new ICmpInst(Pred, BOp0, NegVal);
2942 if (
Value *NegVal = dyn_castNegVal(BOp0))
2943 return new ICmpInst(Pred, NegVal, BOp1);
2945 Value *Neg = Builder.CreateNeg(BOp1);
2947 return new ICmpInst(Pred, BOp0, Neg);
2952 case Instruction::Xor:
2954 if (
Constant *BOC = dyn_cast<Constant>(BOp1)) {
2960 return new ICmpInst(Pred, BOp0, BOp1);
2964 case Instruction::Sub:
2970 return new ICmpInst(Pred, BOp1, SubC);
2973 return new ICmpInst(Pred, BOp0, BOp1);
2977 case Instruction::Or: {
2984 Value *And = Builder.CreateAnd(BOp0, NotBOC);
2985 return new ICmpInst(Pred, And, NotBOC);
2989 case Instruction::And: {
2999 case Instruction::Mul:
3010 case Instruction::UDiv:
3014 return new ICmpInst(NewPred, BOp1, BOp0);
3030 case Intrinsic::bswap:
3036 case Intrinsic::ctlz:
3037 case Intrinsic::cttz: {
3039 if (C == BitWidth) {
3050 if (Num != BitWidth && II->
hasOneUse()) {
3054 APInt Mask2 = IsTrailing
3065 case Intrinsic::ctpop: {
3069 if (IsZero || C == BitWidth) {
3080 case Intrinsic::uadd_sat: {
3084 return replaceInstUsesWith(Cmp, Builder.CreateICmp(
3091 case Intrinsic::usub_sat: {
3113 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3118 case Intrinsic::ctlz: {
3129 C.
uge(1) && C.
ule(BitWidth)) {
3137 case Intrinsic::cttz: {
3152 C.
uge(1) && C.
ule(BitWidth)) {
3175 switch (LHSI->getOpcode()) {
3176 case Instruction::GetElementPtr:
3179 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3184 case Instruction::PHI:
3189 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3196 Value *Op1 =
nullptr, *Op2 =
nullptr;
3198 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3202 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3214 bool Transform =
false;
3217 else if (Op1 || Op2) {
3219 if (LHSI->hasOneUse())
3222 else if (CI && !CI->
isZero())
3227 replacedSelectWithOperand(cast<SelectInst>(LHSI), &
I, Op1 ? 2 : 1);
3231 Op1 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(1), RHSC,
3234 Op2 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(2), RHSC,
3240 case Instruction::IntToPtr:
3243 DL.getIntPtrType(RHSC->
getType()) == LHSI->getOperand(0)->getType())
3252 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3256 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
3295 case ICmpInst::Predicate::ICMP_EQ:
3297 DstPred = ICmpInst::Predicate::ICMP_ULE;
3299 case ICmpInst::Predicate::ICMP_NE:
3301 DstPred = ICmpInst::Predicate::ICMP_UGT;
3303 case ICmpInst::Predicate::ICMP_UGT:
3305 assert(X == I.
getOperand(0) &&
"instsimplify took care of commut. variant");
3306 DstPred = ICmpInst::Predicate::ICMP_UGT;
3308 case ICmpInst::Predicate::ICMP_UGE:
3310 assert(X == I.
getOperand(1) &&
"instsimplify took care of commut. variant");
3311 DstPred = ICmpInst::Predicate::ICMP_ULE;
3313 case ICmpInst::Predicate::ICMP_ULT:
3315 assert(X == I.
getOperand(1) &&
"instsimplify took care of commut. variant");
3316 DstPred = ICmpInst::Predicate::ICMP_UGT;
3318 case ICmpInst::Predicate::ICMP_ULE:
3320 assert(X == I.
getOperand(0) &&
"instsimplify took care of commut. variant");
3321 DstPred = ICmpInst::Predicate::ICMP_ULE;
3323 case ICmpInst::Predicate::ICMP_SGT:
3331 DstPred = ICmpInst::Predicate::ICMP_SGT;
3333 case ICmpInst::Predicate::ICMP_SGE:
3341 DstPred = ICmpInst::Predicate::ICMP_SLE;
3343 case ICmpInst::Predicate::ICMP_SLT:
3351 DstPred = ICmpInst::Predicate::ICMP_SGT;
3353 case ICmpInst::Predicate::ICMP_SLE:
3361 DstPred = ICmpInst::Predicate::ICMP_SLE;
3372 if (OpTy->
isVectorTy() && VecC && VecC->containsUndefElement()) {
3373 Constant *SafeReplacementConstant =
nullptr;
3375 if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
3380 assert(SafeReplacementConstant &&
"Failed to find undef replacement");
3400 const APInt *C0, *C1;
3417 const APInt &MaskedBits = *C0;
3418 assert(MaskedBits != 0 &&
"shift by zero should be folded away already.");
3422 case ICmpInst::Predicate::ICMP_EQ:
3426 DstPred = ICmpInst::Predicate::ICMP_ULT;
3428 case ICmpInst::Predicate::ICMP_NE:
3432 DstPred = ICmpInst::Predicate::ICMP_UGE;
3441 const APInt BitWidth =
APInt(XBitWidth, XBitWidth);
3442 assert(BitWidth.
ugt(MaskedBits) &&
"shifts should leave some bits untouched");
3445 const APInt KeptBits = BitWidth - MaskedBits;
3446 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) &&
"unreachable");
3449 assert(ICmpCst.isPowerOf2());
3452 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3499 "We did not look past any shifts while matching XShift though.");
3507 auto XShiftOpcode = XShift->
getOpcode();
3508 if (XShiftOpcode == YShift->
getOpcode())
3511 Value *
X, *XShAmt, *
Y, *YShAmt;
3518 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
3546 unsigned MaximalPossibleTotalShiftAmount =
3549 APInt MaximalRepresentableShiftAmount =
3551 if (MaximalRepresentableShiftAmount.
ult(MaximalPossibleTotalShiftAmount))
3555 auto *NewShAmt = dyn_cast_or_null<Constant>(
3565 if (!
match(NewShAmt,
3567 APInt(WidestBitWidth, WidestBitWidth))))
3572 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
3578 ? NewShAmt->getSplatValue()
3581 if (NewShAmtSplat &&
3587 if (
auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
3591 unsigned MaxActiveBits = Known.
getBitWidth() - MinLeadZero;
3592 if (MaxActiveBits <= 1)
3598 if (
auto *C = dyn_cast<Constant>(WidestShift->
getOperand(0))) {
3602 unsigned MaxActiveBits = Known.
getBitWidth() - MinLeadZero;
3603 if (MaxActiveBits <= 1)
3606 if (NewShAmtSplat) {
3609 if (AdjNewShAmt.
ule(MinLeadZero))
3623 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
3638 Value *InstCombiner::foldUnsignedMultiplicationOverflowCheck(
ICmpInst &I) {
3654 case ICmpInst::Predicate::ICMP_ULT:
3655 NeedNegation =
false;
3657 case ICmpInst::Predicate::ICMP_UGE:
3658 NeedNegation =
true;
3670 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
3677 bool MulHadOtherUses = Mul && !Mul->
hasOneUse();
3678 if (MulHadOtherUses)
3679 Builder.SetInsertPoint(Mul);
3683 CallInst *Call = Builder.CreateCall(F, {
X, Y},
"umul");
3688 if (MulHadOtherUses)
3689 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0,
"umul.val"));
3691 Value *Res = Builder.CreateExtractValue(Call, 1,
"umul.ov");
3693 Res = Builder.CreateNot(Res,
"umul.not.ov");
3719 return new ICmpInst(Pred, Builder.CreateNot(Op1),
X);
3723 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
3725 bool NoOp0WrapProblem =
false, NoOp1WrapProblem =
false;
3726 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3731 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3739 Value *A =
nullptr, *
B =
nullptr, *C =
nullptr, *
D =
nullptr;
3745 C = BO1->getOperand(0);
3746 D = BO1->getOperand(1);
3751 if ((A == Op1 ||
B == Op1) && NoOp0WrapProblem)
3752 return new ICmpInst(Pred, A == Op1 ?
B : A,
3757 if ((C == Op0 ||
D == Op0) && NoOp1WrapProblem)
3762 if (A && C && (A == C || A ==
D ||
B == C ||
B ==
D) && NoOp0WrapProblem &&
3770 }
else if (A ==
D) {
3774 }
else if (
B == C) {
3855 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3859 const APInt &AP1 = C1->getValue();
3860 const APInt &AP2 = C2->getValue();
3862 APInt AP1Abs = C1->getValue().
abs();
3863 APInt AP2Abs = C2->getValue().
abs();
3864 if (AP1Abs.
uge(AP2Abs)) {
3866 Value *NewAdd = Builder.CreateNSWAdd(A, C3);
3867 return new ICmpInst(Pred, NewAdd, C);
3870 Value *NewAdd = Builder.CreateNSWAdd(C, C3);
3871 return new ICmpInst(Pred, A, NewAdd);
3882 if (BO0 && BO0->
getOpcode() == Instruction::Sub) {
3886 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3887 C = BO1->getOperand(0);
3888 D = BO1->getOperand(1);
3892 if (A == Op1 && NoOp0WrapProblem)
3895 if (C == Op0 && NoOp1WrapProblem)
3915 if (
B &&
D &&
B ==
D && NoOp0WrapProblem && NoOp1WrapProblem)
3919 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
3926 if (
Constant *RHSC = dyn_cast<Constant>(Op1))
3927 if (RHSC->isNotMinSignedValue())
3937 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3938 Op0 == BO1->getOperand(1))
3962 BO1->hasOneUse() && BO0->
getOperand(1) == BO1->getOperand(1)) {
3967 case Instruction::Sub:
3968 case Instruction::Xor: {
3991 case Instruction::Mul: {
4005 Value *And2 = Builder.CreateAnd(BO1->getOperand(0),
Mask);
4006 return new ICmpInst(Pred, And1, And2);
4015 case Instruction::UDiv:
4016 case Instruction::LShr:
4021 case Instruction::SDiv:
4026 case Instruction::AShr:
4027 if (!BO0->
isExact() || !BO1->isExact())
4031 case Instruction::Shl: {
4054 if (
Value *V = foldUnsignedMultiplicationOverflowCheck(I))
4055 return replaceInstUsesWith(I, V);
4058 return replaceInstUsesWith(I, V);
4061 return replaceInstUsesWith(I, V);
4064 return replaceInstUsesWith(I, V);
4164 if (A == Op1 || B == Op1) {
4165 Value *OtherVal = A == Op1 ?
B : A;
4175 Value *Xor = Builder.CreateXor(C, NC);
4193 Value *OtherVal = A == Op0 ?
B : A;
4200 Value *X =
nullptr, *
Y =
nullptr, *Z =
nullptr;
4206 }
else if (A == D) {
4210 }
else if (B == C) {
4214 }
else if (B == D) {
4221 Op1 = Builder.CreateXor(X,
Y);
4222 Op1 = Builder.CreateAnd(Op1, Z);
4250 if (ShAmt < TypeBits && ShAmt != 0) {
4253 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
4255 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal));
4264 if (ShAmt < TypeBits && ShAmt != 0) {
4265 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
4267 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
4282 unsigned ASize = cast<IntegerType>(A->
getType())->getPrimitiveSizeInBits();
4284 if (ShAmt < ASize) {
4292 Value *
Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
4293 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
4324 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
4335 assert(isa<CastInst>(ICmp.
getOperand(0)) &&
"Expected cast for operand 0");
4336 auto *CastOp0 = cast<CastInst>(ICmp.
getOperand(0));
4341 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
4342 bool IsSignedCmp = ICmp.
isSigned();
4343 if (
auto *CastOp1 = dyn_cast<CastInst>(ICmp.
getOperand(1))) {
4347 if (CastOp0->getOpcode() != CastOp1->getOpcode())
4351 Value *
Y = CastOp1->getOperand(0);
4355 if (!CastOp0->hasOneUse() && !CastOp1->hasOneUse())
4359 X = Builder.
CreateCast(CastOp0->getOpcode(),
X, YTy);
4361 Y = Builder.
CreateCast(CastOp0->getOpcode(),
Y, XTy);
4373 if (IsSignedCmp && IsSignedExt)
4387 Type *SrcTy = CastOp0->getSrcTy();
4388 Type *DestTy = CastOp0->getDestTy();
4399 if (IsSignedExt && IsSignedCmp)
4411 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
4433 Value *Op0Src = CastOp0->getOperand(0);
4434 Type *SrcTy = CastOp0->getSrcTy();
4435 Type *DestTy = CastOp0->getDestTy();
4439 auto CompatibleSizes = [&](
Type *SrcTy,
Type *DestTy) {
4440 if (isa<VectorType>(SrcTy)) {
4441 SrcTy = cast<VectorType>(SrcTy)->getElementType();
4442 DestTy = cast<VectorType>(DestTy)->getElementType();
4446 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
4447 CompatibleSizes(SrcTy, DestTy)) {
4448 Value *NewOp1 =
nullptr;
4449 if (
auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.
getOperand(1))) {
4450 Value *PtrSrc = PtrToIntOp1->getOperand(0);
4453 NewOp1 = PtrToIntOp1->getOperand(0);
4456 NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->
getType());
4458 }
else if (
auto *RHSC = dyn_cast<Constant>(ICmp.
getOperand(1))) {
4474 case Instruction::Sub:
4476 case Instruction::Mul:
4492 case Instruction::Sub:
4497 case Instruction::Mul:
4505 bool InstCombiner::OptimizeOverflowCheck(
4508 if (OrigI.
isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
4515 Builder.SetInsertPoint(&OrigI);
4519 Overflow = Builder.getFalse();
4523 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
4528 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4530 Overflow = Builder.getTrue();
4533 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4535 Overflow = Builder.getFalse();
4536 if (
auto *Inst = dyn_cast<Instruction>(Result)) {
4538 Inst->setHasNoSignedWrap();
4540 Inst->setHasNoUnsignedWrap();
4566 if (!isa<IntegerType>(MulVal->
getType()))
4574 assert(MulInstr->getOpcode() == Instruction::Mul);
4576 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
4577 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
4578 assert(LHS->getOpcode() == Instruction::ZExt);
4579 assert(RHS->getOpcode() == Instruction::ZExt);
4580 Value *A = LHS->getOperand(0), *
B = RHS->getOperand(0);
4583 Type *TyA = A->getType(), *TyB =
B->getType();
4585 WidthB = TyB->getPrimitiveSizeInBits();
4588 if (WidthB > WidthA) {
4603 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
4606 if (TruncWidth > MulWidth)
4610 if (BO->
getOpcode() != Instruction::And)
4613 const APInt &CVal = CI->getValue();
4635 if (
ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
4636 if (Zext->hasOneUse()) {
4637 Value *ZextArg = Zext->getOperand(0);
4638 if (
TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
4649 if (ValToMask != MulVal)
4653 unsigned MaskWidth = CVal.
logBase2();
4654 if (MaskWidth == MulWidth)
4664 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4676 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4687 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4699 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4714 Value *MulA = A, *MulB =
B;
4715 if (WidthA < MulWidth)
4717 if (WidthB < MulWidth)
4720 I.
getModule(), Intrinsic::umul_with_overflow, MulType);
4731 if (U == &I || U == OtherVal)
4733 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
4734 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
4742 APInt ShortMask = CI->getValue().
trunc(MulWidth);
4754 if (isa<Instruction>(OtherVal))
4844 return GoodToSwap > 0;
4860 assert(DI && UI &&
"Instruction not defined\n");
4871 auto *Usr = cast<Instruction>(U);
4872 if (Usr != UI && !DT.dominates(DB, Usr->
getParent()))
4883 auto *BI = dyn_cast_or_null<BranchInst>(BB->
getTerminator());
4884 if (!BI || BI->getNumSuccessors() != 2)
4887 if (!IC || (IC->getOperand(0) != SI && IC->
getOperand(1) !=
SI))
4934 const unsigned SIOpd) {
4935 assert((SIOpd == 1 || SIOpd == 2) &&
"Invalid select operand!");
4976 if (SimplifyDemandedBits(&I, 0,
4988 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4989 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
5001 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
5003 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
5013 if (Op0Max.
ult(Op1Min) || Op0Min.ugt(Op1Max)) {
5022 APInt Op0KnownZeroInverted = ~Op0Known.
Zero;
5025 Value *LHS =
nullptr;
5028 *LHSC != Op0KnownZeroInverted)
5033 APInt ValToCheck = Op0KnownZeroInverted;
5040 return new ICmpInst(NewPred, X, CmpC);
5041 }
else if ((++ValToCheck).isPowerOf2()) {
5047 return new ICmpInst(NewPred, X, CmpC);
5065 if (Op0Max.
ult(Op1Min))
5067 if (Op0Min.uge(Op1Max))
5069 if (Op1Min == Op0Max)
5075 if (*CmpC == Op0Min + 1)
5087 if (Op0Min.ugt(Op1Max))
5089 if (Op0Max.
ule(Op1Min))
5091 if (Op1Max == Op0Min)
5097 if (*CmpC == Op0Max - 1)
5109 if (Op0Max.
slt(Op1Min))
5111 if (Op0Min.sge(Op1Max))
5113 if (Op1Min == Op0Max)
5117 if (*CmpC == Op0Min + 1)
5124 if (Op0Min.sgt(Op1Max))
5126 if (Op0Max.
sle(Op1Min))
5128 if (Op1Max == Op0Min)
5132 if (*CmpC == Op0Max - 1)
5139 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SGE with ConstantInt not folded!");
5140 if (Op0Min.sge(Op1Max))
5142 if (Op0Max.
slt(Op1Min))
5144 if (Op1Min == Op0Max)
5148 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SLE with ConstantInt not folded!");
5149 if (Op0Max.
sle(Op1Min))
5151 if (Op0Min.sgt(Op1Max))
5153 if (Op1Max == Op0Min)
5157 assert(!isa<ConstantInt>(Op1) &&
"ICMP_UGE with ConstantInt not folded!");
5158 if (Op0Min.uge(Op1Max))
5160 if (Op0Max.
ult(Op1Min))
5162 if (Op1Min == Op0Max)
5166 assert(!isa<ConstantInt>(Op1) &&
"ICMP_ULE with ConstantInt not folded!");
5167 if (Op0Max.
ule(Op1Min))
5169 if (Op0Min.ugt(Op1Max))
5171 if (Op1Max == Op0Min)
5190 "Only for relational integer predicates.");
5196 bool WillIncrement =
5201 auto ConstantIsOk = [WillIncrement, IsSigned](
ConstantInt *
C) {
5202 return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
5205 Constant *SafeReplacementConstant =
nullptr;
5206 if (
auto *CI = dyn_cast<ConstantInt>(C)) {
5208 if (!ConstantIsOk(CI))
5212 for (
unsigned i = 0; i != NumElts; ++i) {
5217 if (isa<UndefValue>(Elt))
5223 if (!CI || !ConstantIsOk(CI))
5226 if (!SafeReplacementConstant)
5227 SafeReplacementConstant = CI;
5238 assert(SafeReplacementConstant &&
"Replacement constant not set");
5248 return std::make_pair(NewPred, NewC);
5267 if (!FlippedStrictness)
5270 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
5311 return BinaryOperator::CreateXor(A,
B);
5319 return BinaryOperator::CreateAnd(Builder.
CreateNot(A),
B);
5327 return BinaryOperator::CreateAnd(Builder.
CreateNot(
B), A);
5335 return BinaryOperator::CreateOr(Builder.
CreateNot(A),
B);
5343 return BinaryOperator::CreateOr(Builder.
CreateNot(
B), A);
5432 auto UAddOvResultPat = m_ExtractValue<0>(
5433 m_Intrinsic<Intrinsic::uadd_with_overflow>(
m_Value(A),
m_Value(B)));
5434 if (
match(Op0, UAddOvResultPat) &&
5443 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
5444 else if (
match(Op1, UAddOvResultPat) &&
5447 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
5455 bool Changed =
false;
5464 if (Op0Cplxity < Op1Cplxity ||
5472 return replaceInstUsesWith(I, V);
5477 Value *Cond, *SelectTrue, *SelectFalse;
5480 if (
Value *V = dyn_castNegVal(SelectTrue)) {
5481 if (V == SelectFalse)
5484 else if (
Value *V = dyn_castNegVal(SelectFalse)) {
5485 if (V == SelectTrue)
5552 if (
Instruction *Res = foldICmpInstWithConstant(I))
5560 if (
Instruction *Res = foldICmpInstWithConstantNotInt(I))
5564 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
5567 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
5574 assert(Op1->getType()->isPointerTy() &&
"Comparing pointer with non-pointer?");
5576 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op1))
5579 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op0))
5618 isa<IntegerType>(A->
getType())) {
5622 *AddI, Result, Overflow)) {
5623 replaceInstUsesWith(*AddI, Result);
5624 return replaceInstUsesWith(I, Overflow);
5655 if (
auto *EVI = dyn_cast<ExtractValueInst>(Op0))
5656 if (
auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
5657 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
5680 return Changed ? &
I :
nullptr;
5686 if (!isa<ConstantFP>(RHSC))
return nullptr;
5687 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5692 if (MantissaWidth == -1)
return nullptr;
5696 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5700 bool IsExact =
false;
5712 return replaceInstUsesWith(I, Builder.getFalse());
5715 return replaceInstUsesWith(I, Builder.getTrue());
5731 if ((
int)InputSize > MantissaWidth) {
5733 int Exp =
ilogb(RHS);
5736 if (MaxExponent < (
int)InputSize - !LHSUnsigned)
5742 if (MantissaWidth <= Exp && Exp <= (
int)InputSize - !LHSUnsigned)
5751 assert(!RHS.
isNaN() &&
"NaN comparison not already folded!");
5781 return replaceInstUsesWith(I, Builder.getTrue());
5783 return replaceInstUsesWith(I, Builder.getFalse());
5801 return replaceInstUsesWith(I, Builder.getTrue());
5802 return replaceInstUsesWith(I, Builder.getFalse());
5813 return replaceInstUsesWith(I, Builder.getTrue());
5814 return replaceInstUsesWith(I, Builder.getFalse());
5826 return replaceInstUsesWith(I, Builder.getTrue());
5827 return replaceInstUsesWith(I, Builder.getFalse());
5837 return replaceInstUsesWith(I, Builder.getTrue());
5838 return replaceInstUsesWith(I, Builder.getFalse());
5850 bool Equal = LHSUnsigned
5860 return replaceInstUsesWith(I, Builder.getTrue());
5862 return replaceInstUsesWith(I, Builder.getFalse());
5867 return replaceInstUsesWith(I, Builder.getFalse());
5879 return replaceInstUsesWith(I, Builder.getFalse());
5892 return replaceInstUsesWith(I, Builder.getTrue());
5904 return replaceInstUsesWith(I, Builder.getTrue());
6034 bool Changed =
false;
6048 return replaceInstUsesWith(I, V);
6052 assert(OpType == Op1->getType() &&
"fcmp with different-typed operands?");
6121 case Instruction::PHI:
6126 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
6129 case Instruction::SIToFP:
6130 case Instruction::UIToFP:
6134 case Instruction::FDiv:
6139 if (
auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->
getOperand(0)))
6140 if (
auto *GV = dyn_cast<GlobalVariable>(GEP->
getOperand(0)))
6143 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
6164 return new FCmpInst(Pred, X, Y,
"", &I);
6183 return new FCmpInst(Pred, X, NewC,
"", &I);
6192 return Changed ? &
I :
nullptr;
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
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...
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
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 non-negative 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.
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.
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
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.
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CxtI) const
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
SimplifyQuery getWithInstruction(Instruction *I) const
BinaryOps getOpcode() const
size_type size() const
Determine the number of elements in the SetVector.
unsigned countMinPopulation() const
Returns the number of bits known to be one.
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.
Optional< std::vector< StOtherPiece > > Other
static bool isCanonicalPredicate(CmpInst::Predicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
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)
Always overflows in the direction of signed/unsigned min value.
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.
const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers...
bool sgt(const APInt &RHS) const
Signed greater 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 Value * foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, InstCombiner::BuilderTy &Builder)
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.
static Instruction * foldICmpBitCast(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
unsigned getBitWidth() const
Get the bit width of this value.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
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.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
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)
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, OpTy > m_ZExtOrSelf(const OpTy &Op)
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
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.
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.
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
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.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
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 * foldICmpWithZextOrSext(ICmpInst &ICmp, InstCombiner::BuilderTy &Builder)
static Instruction * foldICmpWithHighBitMask(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
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.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS)
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="")
match_combine_or< CastClass_match< OpTy, Instruction::Trunc >, OpTy > m_TruncOrSelf(const OpTy &Op)
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void takeName(Value *V)
Transfer the name from V to this value.
static Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
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.
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Constant * getSplatValue(bool AllowUndefs=false) const
If all elements of the vector constant have the same value, return that value.
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")
OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
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.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
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.
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.
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...
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.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
static Constant * getAnd(Constant *C1, Constant *C2)
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.
Value * SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
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.
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, CastClass_match< OpTy, Instruction::SExt > > m_ZExtOrSExt(const OpTy &Op)
Value * getPointerOperand()
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_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Class to represent integer types.
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
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.
const Function * getFunction() const
Return the function this instruction belongs to.
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 address space casts.
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...
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="")
bool containsUndefElement() const
Return true if this is a vector constant that includes any undefined elements.
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
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
This class represents a range of values.
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
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.
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
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 NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool isCommutative() const
Return true if the instruction is commutative:
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
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 isIntPredicate() const
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 isKnownNonZero(const Value *V, const DataLayout &DL, 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 be non-zero when defined.
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 bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI)
For pattern like:
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.
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
const Value * getFalseValue() const
static Constant * getZExtOrBitCast(Constant *C, Type *Ty)
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...
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Predicate getPredicate() const
Return the predicate for this instruction.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Always overflows in the direction of signed/unsigned max value.
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.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
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)
llvm::Optional< std::pair< CmpInst::Predicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred, Constant *C)
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.
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
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
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.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
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)
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
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.
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
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
static Instruction * foldICmpOfUAddOv(ICmpInst &I)
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