32 using namespace PatternMatch;
34 #define DEBUG_TYPE "instcombine"
37 STATISTIC(NumSel,
"Number of select opts");
58 Constant *In2,
bool IsSigned =
false) {
62 for (
unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
74 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
93 Constant *In2,
bool IsSigned =
false) {
97 for (
unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
109 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
116 for (
auto *U : I.
users())
117 if (isa<BranchInst>(U))
126 bool &TrueIfSigned) {
135 TrueIfSigned =
false;
184 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
190 Max = Known.
One|UnknownBits;
192 if (UnknownBits.isNegative()) {
206 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
212 Max = Known.
One|UnknownBits;
228 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
233 if (ArrayElementCount > MaxArraySizeForCombine)
254 if (!Idx)
return nullptr;
257 if ((
unsigned)IdxVal != IdxVal)
return nullptr;
259 if (
StructType *STy = dyn_cast<StructType>(EltTy))
260 EltTy = STy->getElementType(IdxVal);
261 else if (
ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
262 if (IdxVal >= ATy->getNumElements())
return nullptr;
263 EltTy = ATy->getElementType();
271 enum { Overdefined = -3, Undefined = -2 };
280 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
284 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
292 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
297 uint64_t MagicBitvector = 0;
301 for (
unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
303 if (!Elt)
return nullptr;
306 if (!LaterIndices.
empty())
314 CompareRHS,
DL, &TLI);
316 if (isa<UndefValue>(C)) {
319 if (TrueRangeEnd == (
int)i-1)
321 if (FalseRangeEnd == (
int)i-1)
328 if (!isa<ConstantInt>(C))
return nullptr;
332 bool IsTrueForElt = !cast<ConstantInt>(
C)->
isZero();
337 if (FirstTrueElement == Undefined)
338 FirstTrueElement = TrueRangeEnd = i;
341 if (SecondTrueElement == Undefined)
342 SecondTrueElement = i;
344 SecondTrueElement = Overdefined;
347 if (TrueRangeEnd == (
int)i-1)
350 TrueRangeEnd = Overdefined;
354 if (FirstFalseElement == Undefined)
355 FirstFalseElement = FalseRangeEnd = i;
358 if (SecondFalseElement == Undefined)
359 SecondFalseElement = i;
361 SecondFalseElement = Overdefined;
364 if (FalseRangeEnd == (
int)i-1)
367 FalseRangeEnd = Overdefined;
372 if (i < 64 && IsTrueForElt)
373 MagicBitvector |= 1ULL << i;
378 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
379 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
380 FalseRangeEnd == Overdefined)
395 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
400 if (SecondTrueElement != Overdefined) {
402 if (FirstTrueElement == Undefined)
403 return replaceInstUsesWith(ICI, Builder.getFalse());
408 if (SecondTrueElement == Undefined)
412 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
414 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
415 return BinaryOperator::CreateOr(C1, C2);
420 if (SecondFalseElement != Overdefined) {
422 if (FirstFalseElement == Undefined)
423 return replaceInstUsesWith(ICI, Builder.getTrue());
428 if (SecondFalseElement == Undefined)
432 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
434 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
435 return BinaryOperator::CreateAnd(C1, C2);
440 if (TrueRangeEnd != Overdefined) {
441 assert(TrueRangeEnd != FirstTrueElement &&
"Should emit single compare");
444 if (FirstTrueElement) {
446 Idx = Builder.CreateAdd(Idx, Offs);
450 TrueRangeEnd-FirstTrueElement+1);
455 if (FalseRangeEnd != Overdefined) {
456 assert(FalseRangeEnd != FirstFalseElement &&
"Should emit single compare");
458 if (FirstFalseElement) {
460 Idx = Builder.CreateAdd(Idx, Offs);
464 FalseRangeEnd-FirstFalseElement);
478 if (ArrayElementCount <= Idx->
getType()->getIntegerBitWidth())
481 Ty = DL.getSmallestLegalIntType(Init->
getContext(), ArrayElementCount);
484 Value *V = Builder.CreateIntCast(Idx, Ty,
false);
515 for (i = 1; i != e; ++i, ++GTI) {
518 if (CI->isZero())
continue;
525 Offset += Size*CI->getSExtValue();
535 if (i == e)
return nullptr;
543 for (++i, ++GTI; i != e; ++i, ++GTI) {
545 if (!CI)
return nullptr;
548 if (CI->
isZero())
continue;
576 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
578 Offset &= PtrSizeMask;
579 VariableScale &= PtrSizeMask;
585 int64_t NewOffs = Offset / (int64_t)VariableScale;
586 if (Offset != NewOffs*(int64_t)VariableScale)
590 if (VariableIdx->
getType() != IntPtrTy)
614 while (!WorkList.
empty()) {
617 while (!WorkList.
empty()) {
618 if (Explored.
size() >= 100)
623 if (Explored.
count(V) != 0) {
628 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
629 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
634 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
636 if (!CI->isNoopCast(DL))
639 if (Explored.
count(CI->getOperand(0)) == 0)
643 if (
auto *GEP = dyn_cast<GEPOperator>(V)) {
655 if (WorkList.
back() == V) {
661 if (
auto *PN = dyn_cast<PHINode>(V)) {
663 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
671 for (
auto *PN : PHIs)
672 for (
Value *
Op : PN->incoming_values())
680 for (
Value *Val : Explored) {
686 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
687 Explored.count(PHI) == 0)
690 if (PHI->getParent() == Inst->getParent())
700 bool Before =
true) {
701 if (
auto *PHI = dyn_cast<PHINode>(V)) {
702 Builder.
SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
705 if (
auto *
I = dyn_cast<Instruction>(V)) {
707 I = &*std::next(
I->getIterator());
711 if (
auto *
A = dyn_cast<Argument>(V)) {
713 BasicBlock &Entry =
A->getParent()->getEntryBlock();
719 assert(isa<Constant>(V) &&
"Setting insertion point for unknown value!");
741 for (
Value *Val : Explored) {
746 if (
auto *PHI = dyn_cast<PHINode>(Val))
747 NewInsts[PHI] =
PHINode::Create(IndexType, PHI->getNumIncomingValues(),
748 PHI->getName() +
".idx", PHI);
753 for (
Value *Val : Explored) {
755 if (NewInsts.
find(Val) != NewInsts.
end())
758 if (
auto *CI = dyn_cast<CastInst>(Val)) {
759 NewInsts[CI] = NewInsts[CI->getOperand(0)];
762 if (
auto *GEP = dyn_cast<GEPOperator>(Val)) {
769 NewInsts[GEP->
getOperand(0)]->getType()->getScalarSizeInBits()) {
770 Index = Builder.CreateSExtOrTrunc(
771 Index, NewInsts[GEP->
getOperand(0)]->getType(),
776 if (isa<ConstantInt>(
Op) && dyn_cast<ConstantInt>(
Op)->
isZero())
777 NewInsts[
GEP] = Index;
779 NewInsts[
GEP] = Builder.CreateNSWAdd(
783 if (isa<PHINode>(Val))
790 for (
Value *Val : Explored) {
795 if (
auto *PHI = dyn_cast<PHINode>(Val)) {
797 for (
unsigned I = 0,
E = PHI->getNumIncomingValues();
I <
E; ++
I) {
798 Value *NewIncoming = PHI->getIncomingValue(
I);
800 if (NewInsts.
find(NewIncoming) != NewInsts.
end())
801 NewIncoming = NewInsts[NewIncoming];
803 NewPhi->
addIncoming(NewIncoming, PHI->getIncomingBlock(
I));
808 for (
Value *Val : Explored) {
817 Value *NewBase = Base;
819 NewBase = Builder.CreateBitOrPointerCast(Base, Start->
getType(),
822 Value *GEP = Builder.CreateInBoundsGEP(
826 if (!Val->getType()->isPointerTy()) {
827 Value *Cast = Builder.CreatePointerCast(GEP, Val->
getType(),
828 Val->getName() +
".conv");
834 return NewInsts[Start];
840 static std::pair<Value *, Value *>
862 if (
auto *CI = dyn_cast<IntToPtrInst>(V)) {
863 if (!CI->isNoopCast(DL))
865 V = CI->getOperand(0);
868 if (
auto *CI = dyn_cast<PtrToIntInst>(V)) {
869 if (!CI->isNoopCast(DL))
871 V = CI->getOperand(0);
892 Value *PtrBase, *Index;
931 if (!isa<GetElementPtrInst>(RHS))
947 }
else if (
GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
950 if (PtrBase != GEPRHS->getOperand(0)) {
951 bool IndicesTheSame = GEPLHS->
getNumOperands()==GEPRHS->getNumOperands();
953 GEPRHS->getOperand(0)->getType();
956 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
957 IndicesTheSame =
false;
968 if (GEPLHS->
isInBounds() && GEPRHS->isInBounds() &&
970 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
981 if (LHSIndexTy != RHSIndexTy) {
984 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
986 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
991 return replaceInstUsesWith(I, Cmp);
1002 return foldGEPICmp(GEPRHS, GEPLHS->
getOperand(0),
1006 if (GEPRHS->hasAllZeroIndices())
1007 return foldGEPICmp(GEPLHS, GEPRHS->
getOperand(0), Cond,
I);
1009 bool GEPsInBounds = GEPLHS->
isInBounds() && GEPRHS->isInBounds();
1012 unsigned NumDifferences = 0;
1013 unsigned DiffOperand = 0;
1014 for (
unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1015 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
1017 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1022 if (NumDifferences++)
break;
1027 if (NumDifferences == 0)
1028 return replaceInstUsesWith(I,
1031 else if (NumDifferences == 1 && GEPsInBounds) {
1033 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1041 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->
hasOneUse()) &&
1042 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1057 const Value *Other) {
1074 unsigned MaxIter = 32;
1077 for (
const Use &U : Alloca->
uses()) {
1078 if (Worklist.
size() >= MaxIter)
1083 unsigned NumCmps = 0;
1084 while (!Worklist.
empty()) {
1087 const Value *V = U->getUser();
1090 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1091 isa<SelectInst>(V)) {
1093 }
else if (isa<LoadInst>(V)) {
1096 }
else if (
const auto *SI = dyn_cast<StoreInst>(V)) {
1098 if (
SI->getValueOperand() == U->get())
1101 }
else if (isa<ICmpInst>(V)) {
1105 }
else if (
const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1106 switch (Intrin->getIntrinsicID()) {
1110 case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
1111 case Intrinsic::dbg_declare:
case Intrinsic::dbg_value:
1112 case Intrinsic::memcpy:
case Intrinsic::memmove:
case Intrinsic::memset:
1120 for (
const Use &U : V->
uses()) {
1121 if (Worklist.
size() >= MaxIter)
1128 return replaceInstUsesWith(
1192 return new ICmpInst(Pred, LHS, RHS);
1199 bool IsAShr = isa<AShrOperator>(I.
getOperand(0));
1224 if (IsAShr && AP1 == AP2.
ashr(Shift)) {
1230 }
else if (AP1 == AP2.
lshr(Shift)) {
1238 return replaceInstUsesWith(I, TorF);
1251 return new ICmpInst(Pred, LHS, RHS);
1260 if (!AP1 && AP2TrailingZeros != 0)
1271 if (Shift > 0 && AP2.
shl(Shift) == AP1)
1277 return replaceInstUsesWith(I, TorF);
1305 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1319 unsigned NeededSignBits = CI1->
getBitWidth() - NewWidth + 1;
1330 if (U == AddWithCst)
1348 Intrinsic::sadd_with_overflow, NewType);
1356 Value *TruncA = Builder.CreateTrunc(A, NewType, A->
getName() +
".trunc");
1357 Value *TruncB = Builder.CreateTrunc(B, NewType, B->
getName() +
".trunc");
1358 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB},
"sadd");
1359 Value *
Add = Builder.CreateExtractValue(Call, 0,
"sadd.result");
1360 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->
getType());
1379 Value *A =
nullptr, *
B =
nullptr;
1397 Cmp, A,
B, CI2, cast<ConstantInt>(Cmp.
getOperand(1)), *
this))
1425 TrueBB, FalseBB)) &&
1426 TrueBB != FalseBB) {
1437 return replaceInstUsesWith(Cmp, Builder.getFalse());
1439 return replaceInstUsesWith(Cmp, Builder.getTrue());
1485 if ((Known.
Zero | Known.
One).countLeadingOnes() >= SrcBits - DstBits) {
1524 isTrueIfPositive ^=
true;
1527 if (isTrueIfPositive)
1567 if (!Shift || !Shift->
isShift())
1575 unsigned ShiftOpcode = Shift->
getOpcode();
1576 bool IsShl = ShiftOpcode == Instruction::Shl;
1579 bool CanFold =
false;
1580 if (ShiftOpcode == Instruction::AShr) {
1584 }
else if (ShiftOpcode == Instruction::Shl) {
1591 }
else if (ShiftOpcode == Instruction::LShr) {
1603 APInt SameAsC1 = IsShl ? NewCst.
shl(*C3) : NewCst.
lshr(*C3);
1605 if (SameAsC1 != *C1) {
1615 APInt NewAndCst = IsShl ? C2->
lshr(*C3) : C2->
shl(*C3);
1618 Worklist.Add(Shift);
1673 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->
getName());
1678 if (
Instruction *I = foldICmpAndShift(Cmp, And, C1, C2))
1692 unsigned UsesRemoved = 0;
1695 if (Or->hasOneUse())
1701 Value *NewOr =
nullptr;
1702 if (
auto *C = dyn_cast<Constant>(B)) {
1703 if (UsesRemoved >= 1)
1706 if (UsesRemoved >= 3)
1707 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->
getName(),
1712 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->
getName());
1735 if (
Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1743 if (
auto *LI = dyn_cast<LoadInst>(X))
1744 if (
auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1745 if (
auto *GV = dyn_cast<GlobalVariable>(GEP->
getOperand(0)))
1747 !LI->isVolatile() && isa<ConstantInt>(
Y)) {
1749 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
1759 if (Cmp.
getOperand(1) == Y && (-(*C)).isPowerOf2()) {
1771 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1775 Value *Trunc = Builder.CreateTrunc(X, NTy);
1801 (*C + 1).isPowerOf2()) {
1823 Value *X1, *X2, *X3, *X4;
1828 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1829 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1885 if (CLog2 == TypeBits - 1) {
1913 }
else if (Cmp.
isEquality() && CIsPowerOf2) {
1924 const APInt *ShiftVal;
1926 return foldICmpShlConstConst(Cmp, Shl->
getOperand(1), *
C, *ShiftVal);
1928 const APInt *ShiftAmt;
1935 if (ShiftAmt->uge(TypeBits))
1955 "Compare known true or false was not folded");
1965 APInt ShiftedC = (*C - 1).ashr(*ShiftAmt) + 1;
1988 "Compare known true or false was not folded");
1997 assert(C->
ugt(0) &&
"ult 0 should have been eliminated");
1998 APInt ShiftedC = (*C - 1).lshr(*ShiftAmt) + 1;
2008 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
2010 return new ICmpInst(Pred, And, LShrC);
2014 bool TrueIfSigned =
false;
2020 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
2031 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2033 DL.isLegalInteger(TypeBits - Amt)) {
2039 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2057 const APInt *ShiftVal;
2059 return foldICmpShrConstConst(Cmp, Shr->
getOperand(1), *
C, *ShiftVal);
2061 const APInt *ShiftAmt;
2068 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
2069 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2072 bool IsAShr = Shr->
getOpcode() == Instruction::AShr;
2082 if (IsAShr && (!Shr->
isExact() || ShAmtVal == TypeBits - 1))
2091 Value *Tmp = IsAShr ? Builder.CreateSDiv(X, DivCst,
"", Shr->
isExact())
2092 : Builder.CreateUDiv(X, DivCst,
"", Shr->
isExact());
2103 TheDiv->
getOpcode() == Instruction::UDiv);
2105 Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C);
2106 assert(Res &&
"This div/cst should have folded!");
2116 (!IsAShr && C->
shl(ShAmtVal).
lshr(ShAmtVal) == *
C)) &&
2117 "Expected icmp+shr simplify did not occur.");
2125 return new ICmpInst(Pred, X, ShiftedCmpRHS);
2130 Value *And = Builder.CreateAnd(X, Mask, Shr->
getName() +
".mask");
2131 return new ICmpInst(Pred, And, ShiftedCmpRHS);
2145 assert(*C2 != 0 &&
"udiv 0, X should have been simplified already.");
2151 "icmp ugt X, UINT_MAX should have been simplified already.");
2158 assert(*C != 0 &&
"icmp ult X, 0 should have been simplified already.");
2188 bool DivIsSigned = Div->
getOpcode() == Instruction::SDiv;
2230 int LoOverflow = 0, HiOverflow = 0;
2231 Constant *LoBound =
nullptr, *HiBound =
nullptr;
2236 HiOverflow = LoOverflow = ProdOV;
2246 HiBound = RangeSize;
2249 HiOverflow = LoOverflow = ProdOV;
2255 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2258 LoOverflow =
addWithOverflow(LoBound, HiBound, DivNeg,
true) ? -1 : 0;
2266 LoBound =
AddOne(RangeSize);
2268 if (HiBound == DivRHS) {
2275 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2277 LoOverflow =
addWithOverflow(LoBound, HiBound, RangeSize,
true) ? -1:0;
2280 LoOverflow = HiOverflow = ProdOV;
2293 if (LoOverflow && HiOverflow)
2294 return replaceInstUsesWith(Cmp, Builder.getFalse());
2301 return replaceInstUsesWith(
2303 HiBound->getUniqueInteger(), DivIsSigned,
true));
2305 if (LoOverflow && HiOverflow)
2306 return replaceInstUsesWith(Cmp, Builder.getTrue());
2313 return replaceInstUsesWith(Cmp,
2315 HiBound->getUniqueInteger(),
2316 DivIsSigned,
false));
2319 if (LoOverflow == +1)
2320 return replaceInstUsesWith(Cmp, Builder.getTrue());
2321 if (LoOverflow == -1)
2322 return replaceInstUsesWith(Cmp, Builder.getFalse());
2323 return new ICmpInst(Pred, X, LoBound);
2326 if (HiOverflow == +1)
2327 return replaceInstUsesWith(Cmp, Builder.getFalse());
2328 if (HiOverflow == -1)
2329 return replaceInstUsesWith(Cmp, Builder.getTrue());
2375 (*C2 & (*C - 1)) == (*C - 1))
2450 bool InstCombiner::matchThreeWayIntCompare(
SelectInst *SI,
Value *&LHS,
2477 assert(C &&
"Cmp RHS should be a constant int!");
2483 Value *OrigLHS, *OrigRHS;
2484 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2486 matchThreeWayIntCompare(cast<SelectInst>(Select), OrigLHS, OrigRHS,
2487 C1LessThan, C2Equal, C3GreaterThan)) {
2488 assert(C1LessThan && C2Equal && C3GreaterThan);
2490 bool TrueWhenLessThan =
2493 bool TrueWhenEqual =
2496 bool TrueWhenGreaterThan =
2508 Value *Cond = Builder.getFalse();
2509 if (TrueWhenLessThan)
2510 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
2512 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
2513 if (TrueWhenGreaterThan)
2514 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
2516 return replaceInstUsesWith(Cmp, Cond);
2531 case Instruction::Xor:
2532 if (
Instruction *I = foldICmpXorConstant(Cmp, BO, C))
2535 case Instruction::And:
2536 if (
Instruction *I = foldICmpAndConstant(Cmp, BO, C))
2539 case Instruction::Or:
2540 if (
Instruction *I = foldICmpOrConstant(Cmp, BO, C))
2543 case Instruction::Mul:
2544 if (
Instruction *I = foldICmpMulConstant(Cmp, BO, C))
2547 case Instruction::Shl:
2548 if (
Instruction *I = foldICmpShlConstant(Cmp, BO, C))
2551 case Instruction::LShr:
2552 case Instruction::AShr:
2553 if (
Instruction *I = foldICmpShrConstant(Cmp, BO, C))
2556 case Instruction::UDiv:
2557 if (
Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
2560 case Instruction::SDiv:
2561 if (
Instruction *I = foldICmpDivConstant(Cmp, BO, C))
2564 case Instruction::Sub:
2565 if (
Instruction *I = foldICmpSubConstant(Cmp, BO, C))
2569 if (
Instruction *I = foldICmpAddConstant(Cmp, BO, C))
2576 if (
Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
2590 if (
Instruction *I = foldICmpSelectConstant(Cmp, LHSI, ConstRHS))
2594 case Instruction::Trunc:
2595 if (
Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C))
2603 if (
Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C))
2625 case Instruction::SRem:
2630 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->
getName());
2642 return new ICmpInst(Pred, BOp0, SubC);
2647 if (
Value *NegVal = dyn_castNegVal(BOp1))
2648 return new ICmpInst(Pred, BOp0, NegVal);
2649 if (
Value *NegVal = dyn_castNegVal(BOp0))
2650 return new ICmpInst(Pred, NegVal, BOp1);
2652 Value *Neg = Builder.CreateNeg(BOp1);
2654 return new ICmpInst(Pred, BOp0, Neg);
2659 case Instruction::Xor:
2661 if (
Constant *BOC = dyn_cast<Constant>(BOp1)) {
2667 return new ICmpInst(Pred, BOp0, BOp1);
2671 case Instruction::Sub:
2677 return new ICmpInst(Pred, BOp1, SubC);
2680 return new ICmpInst(Pred, BOp0, BOp1);
2684 case Instruction::Or: {
2691 Value *And = Builder.CreateAnd(BOp0, NotBOC);
2692 return new ICmpInst(Pred, And, NotBOC);
2696 case Instruction::And: {
2712 return new ICmpInst(NewPred, BOp0, Zero);
2716 if (C->
isNullValue() && (~(*BOC) + 1).isPowerOf2()) {
2719 return new ICmpInst(NewPred, BOp0, NegBOC);
2724 case Instruction::Mul:
2735 case Instruction::UDiv:
2739 return new ICmpInst(NewPred, BOp1, BOp0);
2758 case Intrinsic::bswap:
2764 case Intrinsic::ctlz:
2765 case Intrinsic::cttz:
2775 case Intrinsic::ctpop: {
2804 switch (LHSI->getOpcode()) {
2805 case Instruction::GetElementPtr:
2808 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2813 case Instruction::PHI:
2818 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
2825 Value *Op1 =
nullptr, *Op2 =
nullptr;
2827 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2831 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2843 bool Transform =
false;
2846 else if (Op1 || Op2) {
2848 if (LHSI->hasOneUse())
2851 else if (CI && !CI->
isZero())
2856 replacedSelectWithOperand(cast<SelectInst>(LHSI), &
I, Op1 ? 2 : 1);
2860 Op1 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(1), RHSC,
2863 Op2 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(2), RHSC,
2869 case Instruction::IntToPtr:
2872 DL.getIntPtrType(RHSC->
getType()) == LHSI->getOperand(0)->getType())
2881 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2885 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
2908 bool NoOp0WrapProblem =
false, NoOp1WrapProblem =
false;
2909 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2914 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2922 Value *A =
nullptr, *B =
nullptr, *C =
nullptr, *
D =
nullptr;
2928 C = BO1->getOperand(0);
2929 D = BO1->getOperand(1);
2933 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2934 return new ICmpInst(Pred, A == Op1 ? B : A,
2938 if ((C == Op0 ||
D == Op0) && NoOp1WrapProblem)
2943 if (A && C && (A == C || A ==
D || B == C || B ==
D) && NoOp0WrapProblem &&
2953 }
else if (A ==
D) {
2957 }
else if (B == C) {
3038 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3042 const APInt &AP1 = C1->getValue();
3043 const APInt &AP2 = C2->getValue();
3045 APInt AP1Abs = C1->getValue().
abs();
3046 APInt AP2Abs = C2->getValue().
abs();
3047 if (AP1Abs.
uge(AP2Abs)) {
3049 Value *NewAdd = Builder.CreateNSWAdd(A, C3);
3050 return new ICmpInst(Pred, NewAdd, C);
3053 Value *NewAdd = Builder.CreateNSWAdd(C, C3);
3054 return new ICmpInst(Pred, A, NewAdd);
3065 if (BO0 && BO0->
getOpcode() == Instruction::Sub) {
3069 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3070 C = BO1->getOperand(0);
3071 D = BO1->getOperand(1);
3075 if (A == Op1 && NoOp0WrapProblem)
3079 if (C == Op0 && NoOp1WrapProblem)
3083 if (B &&
D && B ==
D && NoOp0WrapProblem && NoOp1WrapProblem &&
3089 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3098 if (
ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3099 if (!RHSC->isMinValue(
true))
3109 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3110 Op0 == BO1->getOperand(1))
3120 case ICmpInst::ICMP_NE:
3134 BO1->hasOneUse() && BO0->
getOperand(1) == BO1->getOperand(1)) {
3139 case Instruction::Sub:
3140 case Instruction::Xor: {
3163 case Instruction::Mul: {
3177 Value *And2 = Builder.CreateAnd(BO1->getOperand(0),
Mask);
3178 return new ICmpInst(Pred, And1, And2);
3187 case Instruction::UDiv:
3188 case Instruction::LShr:
3193 case Instruction::SDiv:
3198 case Instruction::AShr:
3199 if (!BO0->
isExact() || !BO1->isExact())
3203 case Instruction::Shl: {
3222 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3324 if (A == Op1 || B == Op1) {
3325 Value *OtherVal = A == Op1 ? B :
A;
3335 Value *Xor = Builder.CreateXor(C, NC);
3353 Value *OtherVal = A == Op0 ? B :
A;
3360 Value *X =
nullptr, *Y =
nullptr, *Z =
nullptr;
3366 }
else if (A == D) {
3370 }
else if (B == C) {
3374 }
else if (B == D) {
3381 Op1 = Builder.CreateXor(X, Y);
3382 Op1 = Builder.CreateAnd(Op1, Z);
3410 if (ShAmt < TypeBits && ShAmt != 0) {
3413 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
3415 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal));
3424 if (ShAmt < TypeBits && ShAmt != 0) {
3425 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
3427 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
3442 unsigned ASize = cast<IntegerType>(A->
getType())->getPrimitiveSizeInBits();
3444 if (ShAmt < ASize) {
3452 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
3453 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
3474 Type *SrcTy = LHSCIOp->getType();
3480 if (LHSCI->
getOpcode() == Instruction::PtrToInt &&
3482 Value *RHSOp =
nullptr;
3483 if (
auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.
getOperand(1))) {
3486 LHSCIOp->getType()->getPointerAddressSpace()) {
3489 if (LHSCIOp->getType() != RHSOp->
getType())
3490 RHSOp = Builder.CreateBitCast(RHSOp, LHSCIOp->
getType());
3492 }
else if (
auto *RHSC = dyn_cast<Constant>(ICmp.
getOperand(1))) {
3502 if (LHSCI->
getOpcode() != Instruction::ZExt &&
3503 LHSCI->
getOpcode() != Instruction::SExt)
3506 bool isSignedExt = LHSCI->
getOpcode() == Instruction::SExt;
3507 bool isSignedCmp = ICmp.
isSigned();
3509 if (
auto *CI = dyn_cast<CastInst>(ICmp.
getOperand(1))) {
3512 if (RHSCIOp->
getType() != LHSCIOp->getType())
3517 if (CI->getOpcode() != LHSCI->
getOpcode())
3526 if (isSignedCmp && isSignedExt)
3551 if (isSignedExt && isSignedCmp)
3565 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
3574 Value *Result = Builder.CreateICmpSGT(LHSCIOp, NegOne, ICmp.
getName());
3578 return replaceInstUsesWith(ICmp, Result);
3587 if (OrigI.
isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
3590 auto SetResult = [&](
Value *OpResult,
Constant *OverflowVal,
bool ReuseName) {
3592 Overflow = OverflowVal;
3602 Builder.SetInsertPoint(&OrigI);
3611 return SetResult(Builder.CreateNUWAdd(LHS, RHS), Builder.getFalse(),
3615 return SetResult(Builder.CreateAdd(LHS, RHS), Builder.getTrue(),
true);
3623 return SetResult(LHS, Builder.getFalse(),
false);
3628 if (willNotOverflowSignedAdd(LHS, RHS, OrigI))
3629 return SetResult(Builder.CreateNSWAdd(LHS, RHS), Builder.getFalse(),
3638 return SetResult(LHS, Builder.getFalse(),
false);
3641 if (willNotOverflowSignedSub(LHS, RHS, OrigI))
3642 return SetResult(Builder.CreateNSWSub(LHS, RHS), Builder.getFalse(),
3645 if (willNotOverflowUnsignedSub(LHS, RHS, OrigI))
3646 return SetResult(Builder.CreateNUWSub(LHS, RHS), Builder.getFalse(),
3655 return SetResult(Builder.CreateNUWMul(LHS, RHS), Builder.getFalse(),
3658 return SetResult(Builder.CreateMul(LHS, RHS), Builder.getTrue(),
true);
3663 if (isa<UndefValue>(RHS))
3668 return SetResult(RHS, Builder.getFalse(),
false);
3672 return SetResult(LHS, Builder.getFalse(),
false);
3675 if (willNotOverflowSignedMul(LHS, RHS, OrigI))
3676 return SetResult(Builder.CreateNSWMul(LHS, RHS), Builder.getFalse(),
3702 if (!isa<IntegerType>(MulVal->
getType()))
3710 assert(MulInstr->getOpcode() == Instruction::Mul);
3712 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
3713 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
3714 assert(LHS->getOpcode() == Instruction::ZExt);
3715 assert(RHS->getOpcode() == Instruction::ZExt);
3716 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
3721 WidthB = TyB->getPrimitiveSizeInBits();
3724 if (WidthB > WidthA) {
3739 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
3742 if (TruncWidth > MulWidth)
3746 if (BO->
getOpcode() != Instruction::And)
3767 case ICmpInst::ICMP_NE:
3771 if (
ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
3772 if (Zext->hasOneUse()) {
3773 Value *ZextArg = Zext->getOperand(0);
3774 if (
TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
3785 if (ValToMask != MulVal)
3789 unsigned MaskWidth = CVal.
logBase2();
3790 if (MaskWidth == MulWidth)
3800 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3812 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3823 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3835 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3851 if (WidthA < MulWidth)
3853 if (WidthB < MulWidth)
3856 Intrinsic::umul_with_overflow, MulType);
3866 if (U == &I || U == OtherVal)
3868 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
3869 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
3877 APInt ShortMask = CI->getValue().
trunc(MulWidth);
3889 if (isa<Instruction>(OtherVal))
3896 case ICmpInst::ICMP_NE:
3967 const Value * Op1) {
3979 int GlobalSwapBenefits = 0;
3982 if (!BinOp || BinOp->
getOpcode() != Instruction::Sub)
3986 int LocalSwapBenefits = -1;
3987 unsigned Op1Idx = 1;
3990 LocalSwapBenefits = 1;
3994 GlobalSwapBenefits += LocalSwapBenefits;
3996 return GlobalSwapBenefits > 0;
4012 assert(DI && UI &&
"Instruction not defined\n");
4023 auto *Usr = cast<Instruction>(U);
4024 if (Usr != UI && !DT.dominates(DB, Usr->
getParent()))
4035 auto *BI = dyn_cast_or_null<BranchInst>(BB->
getTerminator());
4036 if (!BI || BI->getNumSuccessors() != 2)
4039 if (!IC || (IC->getOperand(0) != SI && IC->
getOperand(1) != SI))
4086 const unsigned SIOpd) {
4087 assert((SIOpd == 1 || SIOpd == 2) &&
"Invalid select operand!");
4127 bool IsSignBit =
false;
4137 if (SimplifyDemandedBits(&I, 0,
4149 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4150 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4162 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
4164 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
4173 case ICmpInst::ICMP_NE: {
4174 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4183 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
4184 if (Op1Known.isZero()) {
4186 Value *LHS =
nullptr;
4189 *LHSC != Op0KnownZeroInverted)
4194 APInt ValToCheck = Op0KnownZeroInverted;
4201 return new ICmpInst(NewPred, X, CmpC);
4202 }
else if ((++ValToCheck).isPowerOf2()) {
4208 return new ICmpInst(NewPred, X, CmpC);
4226 if (Op0Max.ult(Op1Min))
4228 if (Op0Min.uge(Op1Max))
4230 if (Op1Min == Op0Max)
4231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4236 if (Op1Max == Op0Min + 1) {
4244 if (Op0Min.ugt(Op1Max))
4247 if (Op0Max.ule(Op1Min))
4250 if (Op1Max == Op0Min)
4251 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4256 if (*CmpC == Op0Max - 1)
4263 if (Op0Max.slt(Op1Min))
4265 if (Op0Min.sge(Op1Max))
4267 if (Op1Min == Op0Max)
4268 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4269 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4270 if (Op1Max == Op0Min + 1)
4272 Builder.getInt(CI->getValue() - 1));
4276 if (Op0Min.sgt(Op1Max))
4278 if (Op0Max.sle(Op1Min))
4281 if (Op1Max == Op0Min)
4282 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4283 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4284 if (Op1Min == Op0Max - 1)
4286 Builder.getInt(CI->getValue() + 1));
4290 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SGE with ConstantInt not folded!");
4291 if (Op0Min.sge(Op1Max))
4293 if (Op0Max.slt(Op1Min))
4297 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SLE with ConstantInt not folded!");
4298 if (Op0Max.sle(Op1Min))
4300 if (Op0Min.sgt(Op1Max))
4304 assert(!isa<ConstantInt>(Op1) &&
"ICMP_UGE with ConstantInt not folded!");
4305 if (Op0Min.uge(Op1Max))
4307 if (Op0Max.ult(Op1Min))
4311 assert(!isa<ConstantInt>(Op1) &&
"ICMP_ULE with ConstantInt not folded!");
4312 if (Op0Max.ule(Op1Min))
4314 if (Op0Min.ugt(Op1Max))
4322 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
4323 (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
4360 for (
unsigned i = 0; i != NumElts; ++i) {
4365 if (isa<UndefValue>(Elt))
4423 case ICmpInst::ICMP_NE:
4425 return BinaryOperator::CreateXor(A, B);
4433 return BinaryOperator::CreateAnd(Builder.
CreateNot(A),
B);
4441 return BinaryOperator::CreateAnd(Builder.
CreateNot(B),
A);
4449 return BinaryOperator::CreateOr(Builder.
CreateNot(A),
B);
4457 return BinaryOperator::CreateOr(Builder.
CreateNot(B),
A);
4462 bool Changed =
false;
4470 if (Op0Cplxity < Op1Cplxity ||
4478 SQ.getWithInstruction(&I)))
4479 return replaceInstUsesWith(I, V);
4484 Value *Cond, *SelectTrue, *SelectFalse;
4487 if (
Value *V = dyn_castNegVal(SelectTrue)) {
4488 if (V == SelectFalse)
4491 else if (
Value *V = dyn_castNegVal(SelectFalse)) {
4492 if (V == SelectTrue)
4545 if (
Instruction *Res = foldICmpInstWithConstant(I))
4548 if (
Instruction *Res = foldICmpInstWithConstantNotInt(I))
4552 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
4555 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
4562 assert(Op1->getType()->isPointerTy() &&
"Comparing pointer with non-pointer?");
4564 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op1))
4567 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op0))
4574 if (
BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4576 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
4579 Op0 = CI->getOperand(0);
4583 if (
BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4587 if (Op0->
getType() != Op1->getType()) {
4588 if (
Constant *Op1C = dyn_cast<Constant>(Op1)) {
4592 Op1 = Builder.CreateBitCast(Op1, Op0->
getType());
4599 if (isa<CastInst>(Op0)) {
4606 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
4643 isa<IntegerType>(A->
getType())) {
4648 replaceInstUsesWith(*AddI, Result);
4649 return replaceInstUsesWith(I, Overflow);
4677 if (
auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4678 if (
auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4679 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4687 return foldICmpAddOpConst(I, X, Cst, I.
getPredicate());
4693 return Changed ? &I :
nullptr;
4699 if (!isa<ConstantFP>(RHSC))
return nullptr;
4700 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4705 if (MantissaWidth == -1)
return nullptr;
4709 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
4713 bool IsExact =
false;
4725 return replaceInstUsesWith(I, Builder.getFalse());
4728 return replaceInstUsesWith(I, Builder.getTrue());
4744 if ((
int)InputSize > MantissaWidth) {
4749 if (MaxExponent < (
int)InputSize - !LHSUnsigned)
4755 if (MantissaWidth <= Exp && Exp <= (
int)InputSize - !LHSUnsigned)
4764 assert(!RHS.
isNaN() &&
"NaN comparison not already folded!");
4794 return replaceInstUsesWith(I, Builder.getTrue());
4796 return replaceInstUsesWith(I, Builder.getFalse());
4814 return replaceInstUsesWith(I, Builder.getTrue());
4815 return replaceInstUsesWith(I, Builder.getFalse());
4826 return replaceInstUsesWith(I, Builder.getTrue());
4827 return replaceInstUsesWith(I, Builder.getFalse());
4839 return replaceInstUsesWith(I, Builder.getTrue());
4840 return replaceInstUsesWith(I, Builder.getFalse());
4850 return replaceInstUsesWith(I, Builder.getTrue());
4851 return replaceInstUsesWith(I, Builder.getFalse());
4863 bool Equal = LHSUnsigned
4872 case ICmpInst::ICMP_NE:
4873 return replaceInstUsesWith(I, Builder.getTrue());
4875 return replaceInstUsesWith(I, Builder.getFalse());
4880 return replaceInstUsesWith(I, Builder.getFalse());
4892 return replaceInstUsesWith(I, Builder.getFalse());
4905 return replaceInstUsesWith(I, Builder.getTrue());
4917 return replaceInstUsesWith(I, Builder.getTrue());
4936 bool Changed =
false;
4950 SQ.getWithInstruction(&I)))
4951 return replaceInstUsesWith(I, V);
4991 if (
Constant *RHSC = dyn_cast<Constant>(Op1)) {
4992 if (
Instruction *LHSI = dyn_cast<Instruction>(Op0))
4994 case Instruction::FPExt: {
4996 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
5034 case Instruction::PHI:
5039 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
5042 case Instruction::SIToFP:
5043 case Instruction::UIToFP:
5047 case Instruction::FSub: {
5057 dyn_cast<GetElementPtrInst>(LHSI->
getOperand(0))) {
5061 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
5069 CallInst *CI = cast<CallInst>(LHSI);
5071 if (IID != Intrinsic::fabs)
5108 if (
FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
5109 if (
FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
5110 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
5112 RHSExt->getOperand(0));
5114 return Changed ? &I :
nullptr;
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
bool isArithmeticShift() const
Return true if this is an arithmetic shift right.
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)
Value * SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
static const fltSemantics & IEEEquad() LLVM_READNONE
void push_back(const T &Elt)
static bool isEquality(Predicate Pred)
A parsed version of the target data layout string in and methods for querying it. ...
Type * getIndexedType() const
static ConstantInt * getFalse(LLVMContext &Context)
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
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)
Return true if the given value is known to have exactly one bit set when defined. ...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
void setSignBit()
Set the sign bit to 1.
This class is the base class for the comparison instructions.
iterator_range< use_iterator > uses()
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.
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
DiagnosticInfoOptimizationBase::Argument NV
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Value * SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
STATISTIC(NumFunctions,"Total number of functions")
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
m_Intrinsic_Ty< Opnd0 >::Ty m_BitReverse(const Opnd0 &Op0)
bool isOneValue() const
Determine if this is a value of 1.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
match_zero m_Zero()
Match an arbitrary zero/null constant.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
This class represents zero extension of integer types.
unsigned getNumOperands() const
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
This class represents a function call, abstracting a target machine's calling convention.
static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth, bool isSignCheck)
When performing a comparison against a constant, it is possible that not all the bits in the LHS are ...
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isSigned() const
Determine if this instruction is using a signed comparison.
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
0 1 0 0 True if ordered and less than
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
static Constant * getNUWShl(Constant *C1, Constant *C2)
1 1 1 0 True if unordered or not equal
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
int getFPMantissaWidth() const
Return the width of the mantissa of this type.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
const Function * getParent() const
Return the enclosing method, or null if none.
static bool subWithOverflow(Constant *&Result, Constant *In1, Constant *In2, bool IsSigned=false)
Compute Result = In1-In2, returning true if the result overflowed for this type.
const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers...
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
static Constant * getTrue(Type *Ty)
For a boolean type or a vector of boolean type, return true or a vector with every element true...
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
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.
fneg_match< LHS > m_FNeg(const LHS &L)
Match a floating point negate.
static ConstantInt * extractElement(Constant *V, Constant *Idx)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
static bool addWithOverflow(Constant *&Result, Constant *In1, Constant *In2, bool IsSigned=false)
Compute Result = In1+In2, returning true if the result overflowed for this type.
size_type size() const
Determine the number of elements in the SetVector.
unsigned getNumIndices() const
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Type * getPointerElementType() const
uint64_t getArrayNumElements() const
static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit...
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
Intrinsic::ID getIntrinsicForCallSite(ImmutableCallSite ICS, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
Value * CreateNot(Value *V, const Twine &Name="")
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
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.
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
bool isNegative() const
Determine sign of this APInt.
1 0 0 1 True if unordered or equal
bool match(Val *V, const Pattern &P)
StructType * getStructTypeOrNull() const
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
static bool hasSubOverflow(ConstantInt *Result, ConstantInt *In1, ConstantInt *In2, bool IsSigned)
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)
This class represents the LLVM 'select' instruction.
OverflowCheckFlavor
Specific patterns of overflow check idioms that we match.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
Type * getArrayElementType() const
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.
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
The core instruction combiner logic.
static Constant * AddOne(Constant *C)
Add one to a Constant.
0 1 0 1 True if ordered and less than or equal
unsigned ComputeNumSignBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
zlib-gnu style compression
not_match< LHS > m_Not(const LHS &L)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
LLVM_NODISCARD bool empty() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
APInt shl(unsigned shiftAmt) const
Left-shift function.
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.
A constant value that is initialized with an expression using other constant values.
bool insert(const value_type &X)
Insert a new element into the SetVector.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
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.
This instruction compares its operands according to the predicate given to the constructor.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
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...
bool sgt(const APInt &RHS) const
Signed greather than comparison.
This class represents a no-op cast from one type to another.
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.
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Get a value with upper bits starting at loBit set.
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
SelectClass_match< Cond, LHS, RHS > m_Select(const Cond &C, const LHS &L, const RHS &R)
static const fltSemantics & IEEEdouble() LLVM_READNONE
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power of 2.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
unsigned getBitWidth() const
Get the bit width of this value.
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
void takeName(Value *V)
Transfer the name from V to this value.
static bool isChainSelectCmpBranch(const SelectInst *SI)
Return true when the instruction sequence within a block is select-cmp-br.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
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...
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
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...
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
iterator find(const_arg_type_t< KeyT > Val)
uint64_t getElementOffset(unsigned Idx) const
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty, true > m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
OneUse_match< T > m_OneUse(const T &SubPattern)
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
static Constant * getFNeg(Constant *C)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
bool eq(const APInt &RHS) const
Equality comparison.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
APInt trunc(unsigned width) const
Truncate to new width.
LLVM Basic Block Representation.
bool isExact() const
Determine whether the exact flag is set.
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)
Conditional or Unconditional Branch instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isEquality() const
Return true if this predicate is either EQ or NE.
This is an important base class in LLVM.
bool isMaxSignedValue() const
Determine if this is the largest signed value.
const Value * getCondition() const
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
unsigned countLeadingOnes() const
Count the number of leading one bits.
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.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static Constant * getAnd(Constant *C1, Constant *C2)
static ManagedStatic< OptionRegistry > OR
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
ConstantFP - Floating Point Values [float, double].
static Constant * getSExtOrBitCast(Constant *C, Type *Ty)
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static const unsigned End
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Instruction * visitICmpInst(ICmpInst &I)
bool isMaxValue() const
Determine if this is the largest unsigned value.
Value * getOperand(unsigned i) const
0 1 1 1 True if ordered (no nans)
bool isCommutative() const
Return true if the instruction is commutative:
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...
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
unsigned getIntegerBitWidth() const
Class to represent integer types.
Type * getSrcTy() const
Return the source type, as a convenience.
Predicate getPredicate() const
Return the predicate for this instruction.
static Constant * getNot(Constant *C)
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
void clearSignBit()
Set the sign bit to 0.
static Constant * getAllOnesValue(Type *Ty)
Get the all ones value.
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
bool isEmptySet() const
Return true if this set contains no members.
ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
bool isFP128Ty() const
Return true if this is 'fp128'.
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
void swapOperands()
Exchange the two operands to this instruction in such a way that it does not modify the semantics of ...
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
LLVMContext & getContext() const
All values hold a context through their type.
static wasm::ValType getType(const TargetRegisterClass *RC)
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
const Value * getTrueValue() const
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...
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
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...
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
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.
neg_match< LHS > m_Neg(const LHS &L)
Match an integer negate.
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 ugt(const APInt &RHS) const
Unsigned greather than comparison.
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...
0 0 1 0 True if ordered and greater than
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
static Constant * getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
BinaryOps getOpcode() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
static const fltSemantics & IEEEsingle() LLVM_READNONE
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...
This is the shared class of boolean and integer constants.
static const fltSemantics & IEEEhalf() LLVM_READNONE
SelectPatternFlavor Flavor
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
static Constant * getSDiv(Constant *C1, Constant *C2, bool isExact=false)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
unsigned logBase2() const
1 1 0 0 True if unordered or less than
Type * getType() const
All values are typed, get the type of this value.
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
bool isTrueWhenEqual() const
This is just a convenience.
LLVM_NODISCARD T pop_back_val()
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
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.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
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.
int32_t exactLogBase2() const
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 isNullValue() const
Return true if this is the value that would be returned by getNullValue.
static ConstantInt * getTrue(LLVMContext &Context)
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Class to represent vector types.
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...
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 isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
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()
unsigned getVectorNumElements() const
static Constant * getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static Instruction * foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, const APInt *C)
Fold icmp (shl 1, Y), C.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
bool isMinValue() const
Determine if this is the smallest unsigned value.
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...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
bool isAllOnesValue() const
Determine if all bits are set.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
APInt udiv(const APInt &RHS) const
Unsigned division operation.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
unsigned greater or equal
match_one m_One()
Match an integer 1 or a vector with all elements equal to 1.
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 Constant * getOr(Constant *C1, Constant *C2)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
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 ...
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
0 1 1 0 True if ordered and operands are unequal
unsigned countTrailingOnes() const
Count the number of trailing one bits.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
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.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
bool isUnsigned() const
Determine if this instruction is using an unsigned comparison.
const APInt & getUpper() const
Return the upper value for this range.
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 operand in an ICmpInst should be swapped.
match_all_ones m_AllOnes()
Match an integer or vector with all bits set to true.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
0 0 0 1 True if ordered and equal
LLVM Value Representation.
This file provides internal interfaces used to implement the InstCombine.
1 0 1 1 True if unordered, greater than, or equal
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
#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.
bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Returns true if the given value is known be positive (i.e.
static Constant * getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
cmpResult compare(const APFloat &RHS) const
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
Instruction * visitFCmpInst(FCmpInst &I)
const Value * getFalseValue() const
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
bool dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const
True when DB dominates all uses of DI except UI.
APInt zext(unsigned width) const
Zero extend to a new width.
bool isNullValue() const
Determine if all bits are clear.
void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
static bool isVolatile(Instruction *Inst)
APInt abs() const
Get the absolute value;.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
This class represents an extension of floating point types.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
static bool hasAddOverflow(ConstantInt *Result, ConstantInt *In1, ConstantInt *In2, bool IsSigned)
0 0 1 1 True if ordered and greater than or equal
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.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
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)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
const fltSemantics & getSemantics() const
const BasicBlock * getParent() const
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.
int ilogb(const IEEEFloat &Arg)
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.
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)
static Constant * getXor(Constant *C1, Constant *C2)
gep_type_iterator gep_type_begin(const User *GEP)
bool slt(const APInt &RHS) const
Signed less than comparison.