70 using namespace llvm::PatternMatch;
72 #define DEBUG_TYPE "instcombine"
74 STATISTIC(NumCombined ,
"Number of insts combined");
75 STATISTIC(NumConstProp,
"Number of constant folds");
76 STATISTIC(NumDeadInst ,
"Number of dead inst eliminated");
77 STATISTIC(NumSunkInst ,
"Number of instructions sunk");
78 STATISTIC(NumExpand,
"Number of expansions");
79 STATISTIC(NumFactor ,
"Number of factorizations");
80 STATISTIC(NumReassoc ,
"Number of reassociations");
84 cl::desc(
"Enable expensive instruction combines"));
88 cl::desc(
"Maximum array size considered when doing a combine"));
100 bool InstCombiner::shouldChangeType(
unsigned FromWidth,
101 unsigned ToWidth)
const {
107 if (FromLegal && !ToLegal)
112 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
123 bool InstCombiner::shouldChangeType(
Type *From,
Type *To)
const {
128 return shouldChangeType(FromWidth, ToWidth);
146 const APInt *BVal, *CVal;
150 bool Overflow =
false;
152 (void)BVal->
sadd_ov(*CVal, Overflow);
154 (
void)BVal->
ssub_ov(*CVal, Overflow);
180 if (!Cast || !Cast->hasOneUse())
185 if (CastOpcode != Instruction::ZExt)
194 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
211 Cast->setOperand(0, BinOp2->getOperand(0));
236 bool InstCombiner::SimplifyAssociativeOrCommutative(
BinaryOperator &
I) {
238 bool Changed =
false;
282 if (Op1 && Op1->getOpcode() == Opcode) {
284 Value *B = Op1->getOperand(0);
285 Value *C = Op1->getOperand(1);
330 if (Op1 && Op1->getOpcode() == Opcode) {
332 Value *B = Op1->getOperand(0);
333 Value *C = Op1->getOperand(1);
352 Op0->
getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
354 isa<Constant>(Op1->getOperand(1)) &&
358 Value *B = Op1->getOperand(0);
359 Constant *C2 = cast<Constant>(Op1->getOperand(1));
363 if (isa<FPMathOperator>(New)) {
366 Flags &= Op1->getFastMathFlags();
369 InsertNewInstWith(New, I);
395 case Instruction::And:
400 case Instruction::Or:
401 case Instruction::Xor:
405 case Instruction::Mul:
411 case Instruction::Sub:
415 case Instruction::Or:
420 case Instruction::And:
439 case Instruction::And:
440 case Instruction::Or:
441 case Instruction::Xor:
445 case Instruction::Shl:
446 case Instruction::LShr:
447 case Instruction::AShr:
460 if (isa<Constant>(V))
475 assert(Op &&
"Expected a binary operator");
480 switch (TopLevelOpcode) {
485 case Instruction::Sub:
486 if (Op->
getOpcode() == Instruction::Shl) {
490 return Instruction::Mul;
504 assert(A && B && C && D &&
"All values must be provided");
507 Value *SimplifiedInst =
nullptr;
518 if (A == C || (InnerCommutative && A == D)) {
523 V =
SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
526 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
527 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->
getName());
529 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V);
537 if (B == D || (InnerCommutative && B == C)) {
542 V =
SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
546 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
547 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->
getName());
549 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B);
553 if (SimplifiedInst) {
559 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
560 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
562 if (isa<OverflowingBinaryOperator>(&I))
565 if (
auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS))
566 HasNSW &= LOBO->hasNoSignedWrap();
568 if (
auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS))
569 HasNSW &= ROBO->hasNoSignedWrap();
580 InnerOpcode == Instruction::Mul)
582 BO->setHasNoSignedWrap(HasNSW);
586 return SimplifiedInst;
611 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
612 if (
Value *V = tryFactorization(I, LHSOpcode, A, B, C, D))
620 tryFactorization(I, LHSOpcode, A, B, RHS, Ident))
628 tryFactorization(I, RHSOpcode, LHS, Ident, C, D))
646 C = Builder.CreateBinOp(InnerOpcode, L, R);
655 C = Builder.CreateBinOp(TopLevelOpcode, B, C);
664 C = Builder.CreateBinOp(TopLevelOpcode, A, C);
673 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
683 A = Builder.CreateBinOp(InnerOpcode, L, R);
692 A = Builder.CreateBinOp(TopLevelOpcode, A, C);
701 A = Builder.CreateBinOp(TopLevelOpcode, A, B);
709 if (
auto *SI0 = dyn_cast<SelectInst>(LHS)) {
710 if (
auto *SI1 = dyn_cast<SelectInst>(RHS)) {
711 if (SI0->getCondition() == SI1->getCondition()) {
715 SI1->getFalseValue(), SQ.getWithInstruction(&I)))
716 SI = Builder.CreateSelect(SI0->getCondition(),
717 Builder.CreateBinOp(TopLevelOpcode,
719 SI1->getTrueValue()),
723 SI1->getTrueValue(), SQ.getWithInstruction(&I)))
724 SI = Builder.CreateSelect(
725 SI0->getCondition(), V,
726 Builder.CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
727 SI1->getFalseValue()));
741 Value *InstCombiner::dyn_castNegVal(
Value *V)
const {
754 for (
unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
759 if (isa<UndefValue>(Elt))
762 if (!isa<ConstantInt>(Elt))
773 Value *InstCombiner::dyn_castFNegVal(
Value *V,
bool IgnoreZeroSign)
const {
790 if (
auto *Cast = dyn_cast<CastInst>(&I))
796 bool ConstIsRHS = isa<Constant>(I.
getOperand(1));
799 if (
auto *SOC = dyn_cast<Constant>(SO)) {
805 Value *Op0 = SO, *Op1 = ConstOperand;
809 auto *BO = cast<BinaryOperator>(&
I);
813 if (FPInst && isa<FPMathOperator>(FPInst))
825 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
834 if (
auto *BC = dyn_cast<BitCastInst>(&Op)) {
839 if ((SrcTy ==
nullptr) != (DestTy ==
nullptr))
855 if (CI->hasOneUse()) {
870 bool ConstIsRHS = isa<Constant>(I->
getOperand(1));
873 if (
auto *InC = dyn_cast<Constant>(InV)) {
879 Value *Op0 = InV, *Op1 =
C;
885 if (FPInst && isa<FPMathOperator>(FPInst))
892 if (NumPHIValues == 0)
914 for (
unsigned i = 0; i != NumPHIValues; ++i) {
916 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
919 if (isa<PHINode>(InVal))
return nullptr;
920 if (NonConstBB)
return nullptr;
926 if (
InvokeInst *II = dyn_cast<InvokeInst>(InVal))
927 if (II->getParent() == NonConstBB)
941 if (NonConstBB !=
nullptr) {
948 InsertNewInstBefore(NewPN, *PN);
957 if (
SelectInst *SI = dyn_cast<SelectInst>(&I)) {
963 for (
unsigned i = 0; i != NumPHIValues; ++i) {
967 Value *InV =
nullptr;
975 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
976 InV = InC->
isNullValue() ? FalseVInPred : TrueVInPred;
988 FalseVInPred,
"phitmp");
992 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(&I)) {
994 for (
unsigned i = 0; i != NumPHIValues; ++i) {
995 Value *InV =
nullptr;
998 else if (isa<ICmpInst>(CI))
1006 }
else if (
auto *BO = dyn_cast<BinaryOperator>(&I)) {
1007 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1015 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1028 if (User == &I)
continue;
1029 replaceInstUsesWith(*User, NewPN);
1030 eraseInstFromFunction(*User);
1032 return replaceInstUsesWith(I, NewPN);
1038 if (
auto *Sel = dyn_cast<SelectInst>(I.
getOperand(0))) {
1039 if (
Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1041 }
else if (
auto *PN = dyn_cast<PHINode>(I.
getOperand(0))) {
1062 int64_t FirstIdx = 0;
1064 FirstIdx = Offset/TySize;
1065 Offset -= FirstIdx*TySize;
1073 assert((uint64_t)Offset < (uint64_t)TySize &&
"Out of range offset");
1084 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
1087 "Offset must stay within the indexed type");
1094 Ty = STy->getElementType(Elt);
1095 }
else if (
ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1097 assert(EltSize &&
"Cannot index into a zero-sized array");
1100 Ty = AT->getElementType();
1122 Value *InstCombiner::Descale(
Value *Val,
APInt Scale,
bool &NoSignedWrap) {
1123 assert(isa<IntegerType>(Val->
getType()) &&
"Can only descale integers!");
1125 Scale.
getBitWidth() &&
"Scale not compatible with value!");
1129 NoSignedWrap =
true;
1161 std::pair<Instruction*, unsigned> Parent;
1165 bool RequireNoSignedWrap =
false;
1170 for (;; Op = Parent.first->getOperand(Parent.second)) {
1172 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1174 APInt Quotient(Scale), Remainder(Scale);
1176 if (!Remainder.isMinValue())
1181 NoSignedWrap =
true;
1187 if (BO->getOpcode() == Instruction::Mul) {
1189 NoSignedWrap = BO->hasNoSignedWrap();
1190 if (RequireNoSignedWrap && !NoSignedWrap)
1196 Value *LHS = BO->getOperand(0);
1197 Value *RHS = BO->getOperand(1);
1199 if (
ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1201 if (CI->getValue() == Scale) {
1212 Parent = std::make_pair(BO, 1);
1221 Parent = std::make_pair(BO, 0);
1225 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1226 isa<ConstantInt>(BO->getOperand(1))) {
1228 NoSignedWrap = BO->hasNoSignedWrap();
1229 if (RequireNoSignedWrap && !NoSignedWrap)
1232 Value *LHS = BO->getOperand(0);
1233 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1237 if (Amt == logScale) {
1243 if (Amt < logScale || !Op->hasOneUse())
1248 Parent = std::make_pair(BO, 1);
1257 if (
CastInst *Cast = dyn_cast<CastInst>(Op)) {
1258 if (Cast->getOpcode() == Instruction::SExt) {
1260 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1272 RequireNoSignedWrap =
true;
1275 Parent = std::make_pair(Cast, 0);
1280 if (Cast->getOpcode() == Instruction::Trunc) {
1287 if (RequireNoSignedWrap)
1291 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1292 Parent = std::make_pair(Cast, 0);
1293 Scale = Scale.
sext(LargeSize);
1294 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1307 NoSignedWrap =
true;
1321 assert(Parent.first->hasOneUse() &&
"Drilled down when more than one use!");
1322 assert(Op != Parent.first->getOperand(Parent.second) &&
1323 "Descaling was a no-op?");
1324 Parent.first->setOperand(Parent.second, Op);
1325 Worklist.Add(Parent.first);
1340 NoSignedWrap &= OpNoSignedWrap;
1341 if (NoSignedWrap != OpNoSignedWrap) {
1342 BO->setHasNoSignedWrap(NoSignedWrap);
1343 Worklist.Add(Ancestor);
1345 }
else if (Ancestor->
getOpcode() == Instruction::Trunc) {
1349 NoSignedWrap =
false;
1351 assert((Ancestor->
getOpcode() != Instruction::SExt || NoSignedWrap) &&
1352 "Failed to keep proper track of nsw flags while drilling down?");
1354 if (Ancestor == Val)
1359 assert(Ancestor->
hasOneUse() &&
"Drilled down when more than one use!");
1371 NewBO->copyIRFlags(&Inst);
1388 unsigned VWidth = cast<VectorType>(Inst.
getType())->getNumElements();
1390 assert(cast<VectorType>(LHS->
getType())->getNumElements() == VWidth);
1391 assert(cast<VectorType>(RHS->
getType())->getNumElements() == VWidth);
1398 if (LShuf && RShuf && LShuf->getMask() == RShuf->getMask() &&
1399 isa<UndefValue>(LShuf->getOperand(1)) &&
1400 isa<UndefValue>(RShuf->getOperand(1)) &&
1401 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType()) {
1403 RShuf->getOperand(0), Builder);
1404 return Builder.CreateShuffleVector(
1412 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1413 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1414 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1415 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1416 if (Shuffle && C1 &&
1417 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1427 bool MayChange =
true;
1428 for (
unsigned I = 0; I < VWidth; ++
I) {
1429 if (ShMask[I] >= 0) {
1430 assert(ShMask[I] < (
int)VWidth);
1431 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1443 return Builder.CreateShuffleVector(NewBO,
1455 SQ.getWithInstruction(&GEP)))
1456 return replaceInstUsesWith(GEP, V);
1462 bool MadeChange =
false;
1474 Type *IndexTy = (*I)->getType();
1482 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1487 if (IndexTy != NewIndexType) {
1491 *I = Builder.CreateIntCast(*I, NewIndexType,
true);
1499 if (
PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1525 Type *CurTy =
nullptr;
1558 }
else if (
CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1559 CurTy = CT->getTypeAtIndex(Op1->
getOperand(J));
1586 Builder.SetInsertPoint(PN);
1592 NewPN->
addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1609 if (
GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1617 dyn_cast<GEPOperator>(Src->getOperand(0)))
1624 bool EndsWithSequential =
false;
1627 EndsWithSequential = I.isSequential();
1630 if (EndsWithSequential) {
1634 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1652 if (Src->getNumOperands() == 2) {
1657 Indices.
append(Src->op_begin()+1, Src->op_end()-1);
1660 }
else if (isa<Constant>(*GEP.
idx_begin()) &&
1661 cast<Constant>(*GEP.
idx_begin())->isNullValue() &&
1662 Src->getNumOperands() != 1) {
1664 Indices.
append(Src->op_begin()+1, Src->op_end());
1668 if (!Indices.
empty())
1671 Src->getSourceElementType(), Src->getOperand(0), Indices,
1674 Src->getOperand(0), Indices,
1685 bool Matched =
false;
1688 if (TyAllocSize == 1) {
1693 if (TyAllocSize == 1ULL << C)
1697 if (TyAllocSize == C)
1707 Operator *Index = cast<Operator>(V);
1708 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->
getType());
1732 if (StrippedPtr != PtrOp) {
1733 bool HasZeroPointerIndex =
false;
1735 HasZeroPointerIndex = C->isZero();
1744 if (HasZeroPointerIndex) {
1768 if (CATy->getElementType() == XATy->getElementType()) {
1790 ? Builder.CreateInBoundsGEP(
1791 nullptr, StrippedPtr, Idx, GEP.
getName())
1792 : Builder.CreateGEP(
nullptr, StrippedPtr, Idx,
1811 ? Builder.CreateInBoundsGEP(
nullptr, StrippedPtr, Idx,
1813 : Builder.CreateGEP(
nullptr, StrippedPtr, Idx, GEP.
getName());
1829 if (ResSize && SrcSize % ResSize == 0) {
1832 uint64_t Scale = SrcSize / ResSize;
1837 "Index not cast to pointer width?");
1840 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1846 ? Builder.CreateInBoundsGEP(
nullptr, StrippedPtr, NewIdx,
1848 : Builder.CreateGEP(
nullptr, StrippedPtr, NewIdx,
1866 uint64_t ArrayEltSize =
1868 if (ResSize && ArrayEltSize % ResSize == 0) {
1871 uint64_t Scale = ArrayEltSize / ResSize;
1876 "Index not cast to pointer width?");
1879 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1888 ? Builder.CreateInBoundsGEP(
1889 SrcElTy, StrippedPtr, Off, GEP.
getName())
1890 : Builder.CreateGEP(SrcElTy, StrippedPtr, Off,
1909 if (
BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1918 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1919 Value *Operand = BCI->getOperand(0);
1923 if (!isa<BitCastInst>(Operand) &&
1936 BCI->getParent()->getInstList().insert(BCI->getIterator(),
I);
1937 replaceInstUsesWith(*BCI, I);
1952 if (FindElementAtOffset(OpType, Offset.
getSExtValue(), NewIndices)) {
1955 ? Builder.CreateInBoundsGEP(
nullptr, Operand, NewIndices)
1956 : Builder.CreateGEP(
nullptr, Operand, NewIndices);
1959 return replaceInstUsesWith(GEP, NGEP);
1972 APInt BasePtrOffset(PtrWidth, 0);
1973 Value *UnderlyingPtrOp =
1976 if (
auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
1980 if (BasePtrOffset.
ule(AllocSize)) {
1993 if (isa<ConstantPointerNull>(V))
1995 if (
auto *LI = dyn_cast<LoadInst>(V))
1996 return isa<GlobalVariable>(LI->getPointerOperand());
2020 case Instruction::AddrSpaceCast:
2021 case Instruction::BitCast:
2022 case Instruction::GetElementPtr:
2027 case Instruction::ICmp: {
2034 unsigned OtherIndex = (ICI->
getOperand(0) == PI) ? 1 : 0;
2044 switch (II->getIntrinsicID()) {
2048 case Intrinsic::memmove:
2049 case Intrinsic::memcpy:
2050 case Intrinsic::memset: {
2056 case Intrinsic::dbg_declare:
2057 case Intrinsic::dbg_value:
2058 case Intrinsic::invariant_start:
2059 case Intrinsic::invariant_end:
2060 case Intrinsic::lifetime_start:
2061 case Intrinsic::lifetime_end:
2062 case Intrinsic::objectsize:
2084 }
while (!Worklist.
empty());
2094 for (
unsigned i = 0, e = Users.
size(); i != e; ++i) {
2103 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2106 replaceInstUsesWith(*I, Result);
2107 eraseInstFromFunction(*I);
2112 for (
unsigned i = 0, e = Users.
size(); i != e; ++i) {
2118 if (
ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2119 replaceInstUsesWith(*C,
2121 C->isFalseWhenEqual()));
2122 }
else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2123 isa<AddrSpaceCastInst>(I)) {
2126 eraseInstFromFunction(*I);
2129 if (
InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2131 Module *M = II->getModule();
2134 None,
"", II->getParent());
2136 return eraseInstFromFunction(MI);
2173 if (FreeInstrBB->
size() != 2)
2192 "Broken CFG: missing edge from predecessor to successor");
2203 if (isa<UndefValue>(Op)) {
2207 return eraseInstFromFunction(FI);
2212 if (isa<ConstantPointerNull>(Op))
2213 return eraseInstFromFunction(FI);
2252 !isa<Constant>(X)) {
2290 for (
auto Case : SI.
cases()) {
2292 assert(isa<ConstantInt>(NewCase) &&
2293 "Result of expression should be constant");
2294 Case.setValue(cast<ConstantInt>(NewCase));
2306 for (
auto &C : SI.
cases()) {
2308 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2310 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2318 if (NewWidth > 0 && NewWidth < Known.
getBitWidth()) {
2320 Builder.SetInsertPoint(&SI);
2321 Value *NewCond = Builder.CreateTrunc(Cond, Ty,
"trunc");
2324 for (
auto Case : SI.
cases()) {
2325 APInt TruncatedCase = Case.getCaseValue()->getValue().
trunc(NewWidth);
2338 return replaceInstUsesWith(EV, Agg);
2341 SQ.getWithInstruction(&EV)))
2342 return replaceInstUsesWith(EV, V);
2346 const unsigned *exti, *exte, *insi, *inse;
2347 for (exti = EV.
idx_begin(), insi = IV->idx_begin(),
2348 exte = EV.
idx_end(), inse = IV->idx_end();
2349 exti != exte && insi != inse;
2363 if (exti == exte && insi == inse)
2368 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2378 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2399 if (II->hasOneUse()) {
2403 switch (II->getIntrinsicID()) {
2404 case Intrinsic::uadd_with_overflow:
2405 case Intrinsic::sadd_with_overflow:
2407 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2409 eraseInstFromFunction(*II);
2416 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2417 if (
ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2421 case Intrinsic::usub_with_overflow:
2422 case Intrinsic::ssub_with_overflow:
2424 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2426 eraseInstFromFunction(*II);
2427 return BinaryOperator::CreateSub(LHS, RHS);
2430 case Intrinsic::umul_with_overflow:
2431 case Intrinsic::smul_with_overflow:
2433 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2435 eraseInstFromFunction(*II);
2444 if (
LoadInst *L = dyn_cast<LoadInst>(Agg))
2457 Indices.
push_back(Builder.getInt32(*I));
2461 Builder.SetInsertPoint(L);
2463 L->getPointerOperand(), Indices);
2468 L->getAAMetadata(Nodes);
2472 return replaceInstUsesWith(EV, NL);
2487 switch (Personality) {
2514 cast<ArrayType>(LHS->
getType())->getNumElements()
2516 cast<ArrayType>(RHS->
getType())->getNumElements();
2528 bool MakeNewInstruction =
false;
2534 bool isLastClause = i + 1 == e;
2542 if (AlreadyCaught.
insert(TypeInfo).second) {
2547 MakeNewInstruction =
true;
2554 MakeNewInstruction =
true;
2555 CleanupFlag =
false;
2568 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2574 if (!NumTypeInfos) {
2577 MakeNewInstruction =
true;
2578 CleanupFlag =
false;
2582 bool MakeNewFilter =
false;
2584 if (isa<ConstantAggregateZero>(FilterClause)) {
2586 assert(NumTypeInfos > 0 &&
"Should have handled empty filter already!");
2592 MakeNewInstruction =
true;
2599 if (NumTypeInfos > 1)
2600 MakeNewFilter =
true;
2604 NewFilterElts.
reserve(NumTypeInfos);
2609 bool SawCatchAll =
false;
2610 for (
unsigned j = 0; j != NumTypeInfos; ++j) {
2638 if (SeenInFilter.insert(TypeInfo).second)
2639 NewFilterElts.
push_back(cast<Constant>(Elt));
2644 MakeNewInstruction =
true;
2649 if (NewFilterElts.
size() < NumTypeInfos)
2650 MakeNewFilter =
true;
2652 if (MakeNewFilter) {
2654 NewFilterElts.
size());
2656 MakeNewInstruction =
true;
2665 if (MakeNewFilter && !NewFilterElts.
size()) {
2666 assert(MakeNewInstruction &&
"New filter but not a new instruction!");
2667 CleanupFlag =
false;
2678 for (
unsigned i = 0, e = NewClauses.
size(); i + 1 < e; ) {
2681 for (j = i; j != e; ++j)
2682 if (!isa<ArrayType>(NewClauses[j]->
getType()))
2688 for (
unsigned k = i; k + 1 < j; ++k)
2692 std::stable_sort(NewClauses.
begin() + i, NewClauses.
begin() + j,
2694 MakeNewInstruction =
true;
2713 for (
unsigned i = 0; i + 1 < NewClauses.
size(); ++i) {
2723 for (
unsigned j = NewClauses.
size() - 1; j != i; --j) {
2724 Value *LFilter = NewClauses[j];
2735 NewClauses.
erase(J);
2736 MakeNewInstruction =
true;
2746 if (isa<ConstantAggregateZero>(LFilter)) {
2749 if (isa<ConstantAggregateZero>(Filter)) {
2750 assert(FElts <= LElts &&
"Should have handled this case earlier!");
2752 NewClauses.
erase(J);
2753 MakeNewInstruction =
true;
2759 if (isa<ConstantAggregateZero>(Filter)) {
2762 assert(FElts > 0 &&
"Should have eliminated the empty filter earlier!");
2763 for (
unsigned l = 0; l != LElts; ++l)
2766 NewClauses.
erase(J);
2767 MakeNewInstruction =
true;
2778 bool AllFound =
true;
2779 for (
unsigned f = 0; f != FElts; ++f) {
2782 for (
unsigned l = 0; l != LElts; ++l) {
2784 if (LTypeInfo == FTypeInfo) {
2794 NewClauses.
erase(J);
2795 MakeNewInstruction =
true;
2803 if (MakeNewInstruction) {
2806 for (
unsigned i = 0, e = NewClauses.
size(); i != e; ++i)
2811 if (NewClauses.
empty())
2820 assert(!CleanupFlag &&
"Adding a cleanup, not removing one?!");
2837 isa<TerminatorInst>(
I))
2841 if (isa<AllocaInst>(I) && I->
getParent() ==
2850 if (
auto *CI = dyn_cast<CallInst>(I)) {
2851 if (CI->isConvergent())
2860 if (Scan->mayWriteToMemory())
2871 while (!Worklist.isEmpty()) {
2873 if (I ==
nullptr)
continue;
2877 DEBUG(
dbgs() <<
"IC: DCE: " << *I <<
'\n');
2878 eraseInstFromFunction(*I);
2880 MadeIRChange =
true;
2888 DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: " << *I <<
'\n');
2891 replaceInstUsesWith(*I, C);
2894 eraseInstFromFunction(*I);
2895 MadeIRChange =
true;
2907 DEBUG(
dbgs() <<
"IC: ConstFold (all bits known) to: " << *C <<
2908 " from: " << *I <<
'\n');
2911 replaceInstUsesWith(*I, C);
2914 eraseInstFromFunction(*I);
2915 MadeIRChange =
true;
2927 if (
PHINode *PN = dyn_cast<PHINode>(UserInst))
2932 if (UserParent != BB) {
2933 bool UserIsSuccessor =
false;
2936 if (*SI == UserParent) {
2937 UserIsSuccessor =
true;
2944 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
2947 DEBUG(
dbgs() <<
"IC: Sink: " << *I <<
'\n');
2948 MadeIRChange =
true;
2953 if (
Instruction *OpI = dyn_cast<Instruction>(U.get()))
2961 Builder.SetInsertPoint(I);
2962 Builder.SetCurrentDebugLocation(I->
getDebugLoc());
2968 DEBUG(
dbgs() <<
"IC: Visiting: " << OrigI <<
'\n');
2974 DEBUG(
dbgs() <<
"IC: Old = " << *I <<
'\n'
2975 <<
" New = " << *Result <<
'\n');
2983 Result->takeName(I);
2986 Worklist.AddUsersToWorkList(*Result);
2987 Worklist.Add(Result);
2995 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3000 eraseInstFromFunction(*I);
3002 DEBUG(
dbgs() <<
"IC: Mod = " << OrigI <<
'\n'
3003 <<
" New = " << *I <<
'\n');
3008 eraseInstFromFunction(*I);
3010 Worklist.AddUsersToWorkList(*I);
3014 MadeIRChange =
true;
3019 return MadeIRChange;
3035 bool MadeIRChange =
false;
3046 if (!Visited.
insert(BB).second)
3055 DEBUG(
dbgs() <<
"IC: DCE: " << *Inst <<
'\n');
3057 MadeIRChange =
true;
3065 DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: "
3071 MadeIRChange =
true;
3077 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3080 auto *C = cast<Constant>(U);
3081 Constant *&FoldRes = FoldedConstants[
C];
3088 DEBUG(
dbgs() <<
"IC: ConstFold operand of: " << *Inst
3089 <<
"\n Old = " << *C
3090 <<
"\n New = " << *FoldRes <<
'\n');
3092 MadeIRChange =
true;
3098 if (!isa<DbgInfoIntrinsic>(Inst))
3099 InstrsForInstCombineWorklist.
push_back(Inst);
3105 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3107 bool CondVal = cast<ConstantInt>(BI->
getCondition())->getZExtValue();
3112 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3114 Worklist.
push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3121 }
while (!Worklist.
empty());
3130 return MadeIRChange;
3141 bool MadeIRChange =
false;
3154 if (Visited.count(&BB))
3158 MadeIRChange |= NumDeadInstInBB > 0;
3159 NumDeadInst += NumDeadInstInBB;
3162 return MadeIRChange;
3169 bool ExpensiveCombines =
true,
3181 using namespace llvm::PatternMatch;
3182 if (
match(I, m_Intrinsic<Intrinsic::assume>()))
3194 DEBUG(
dbgs() <<
"\n\nINSTCOMBINE ITERATION #" << Iteration <<
" on "
3200 AA, AC, TLI, DT,
DL, LI);
3207 return MadeIRChange || Iteration > 1;
3220 ExpensiveCombines, LI))
3245 if (skipFunction(F))
3249 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3250 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3251 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3252 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3255 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3256 auto *LI = LIWP ? &LIWP->getLoopInfo() :
nullptr;
3259 ExpensiveCombines, LI);
3264 "Combine redundant instructions",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (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...
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
A parsed version of the target data layout string in and methods for querying it. ...
Type * getIndexedType() const
static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, TargetLibraryInfo *TLI, InstCombineWorklist &ICWorklist)
Populate the IC worklist from a function, and prune any dead basic blocks discovered in the process...
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
static const Value * getFNegArgument(const Value *BinOp)
Type * getSourceElementType() const
void LLVMInitializeInstCombine(LLVMPassRegistryRef R)
STATISTIC(NumFunctions,"Total number of functions")
bool isVolatile() const
Return true if this is a store to a volatile memory location.
void swapSuccessors()
Swap the successors of this branch instruction.
static bool isAllocSiteRemovable(Instruction *AI, SmallVectorImpl< WeakTrackingVH > &Users, const TargetLibraryInfo *TLI)
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
static Value * foldOperationIntoPhiValue(BinaryOperator *I, Value *InV, InstCombiner::BuilderTy &Builder)
static void ClearSubclassDataAfterReassociation(BinaryOperator &I)
Conservatively clears subclassOptionalData after a reassociation or commutation.
match_zero m_Zero()
Match an arbitrary zero/null constant.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
This file provides the primary interface to the instcombine pass.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
INITIALIZE_PASS_BEGIN(InstructionCombiningPass,"instcombine","Combine redundant instructions", false, false) INITIALIZE_PASS_END(InstructionCombiningPass
unsigned getNumOperands() const
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
br_match m_UnconditionalBr(BasicBlock *&Succ)
A global registry used in conjunction with static constructors to make pluggable components (like tar...
This class represents a function call, abstracting a target machine's calling convention.
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty)
Return the identity for the given binary operation, i.e.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
An immutable pass that tracks lazily created AssumptionCache objects.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
static bool isCanonicalPredicate(CmpInst::Predicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
gep_type_iterator gep_type_end(const User *GEP)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
A cache of .assume calls within a function.
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
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)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
struct LLVMOpaquePassRegistry * LLVMPassRegistryRef
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
static bool RightDistributesOverLeft(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
Return whether "(X LOp Y) ROp Z" is always equal to "(X ROp Z) LOp (Y ROp Z)".
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.
Analysis pass which computes a DominatorTree.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
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)
iv Induction Variable Users
Type * getElementType() const
void reserve(size_type N)
static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C)
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
unsigned getNumIndices() const
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
bool optForMinSize() const
Optimize this function for minimum size (-Oz).
Constant * getMask() const
const APInt & getConstant() const
Returns the value when all bits have a known value.
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
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.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool swapOperands()
Exchange the two operands to this instruction.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
Value * SimplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
static const Value * getNegArgument(const Value *BinOp)
Helper functions to extract the unary argument of a NEG, FNEG or NOT operation implemented via Sub...
bool isUnconditional() const
This class represents a conversion between pointers from one address space to another.
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
This class represents the LLVM 'select' instruction.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Attribute unwrap(LLVMAttributeRef Attr)
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.
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Class to represent struct types.
const Constant * stripPointerCasts() const
Type * getArrayElementType() const
A Use represents the edge between a Value definition and its users.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
static Constant * get(ArrayRef< Constant * > V)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
The core instruction combiner logic.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
static cl::opt< bool > EnableExpensiveCombines("expensive-combines", cl::desc("Enable expensive instruction combines"))
Analysis pass that exposes the LoopInfo for a function.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
static bool shorter_filter(const Value *LHS, const Value *RHS)
Type * getPointerOperandType() const
Method to return the pointer operand as a PointerType.
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
Instruction * visitReturnInst(ReturnInst &RI)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Instruction * visitBranchInst(BranchInst &BI)
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
static Value * getIdentityValue(Instruction::BinaryOps Opcode, Value *V)
This function returns identity value for given opcode, which can be used to factor patterns like (X *...
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, Instruction *AI)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Class to represent array types.
BasicBlock * getSuccessor(unsigned i) const
This class represents a no-op cast from one type to another.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
TargetFolder - Create constants with target dependent folding.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
True if this is an instance of ArrayType.
static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL, SmallPtrSetImpl< BasicBlock * > &Visited, InstCombineWorklist &ICWorklist, const TargetLibraryInfo *TLI)
Walk the function in depth-first order, adding all reachable code to the worklist.
unsigned getBitWidth() const
Get the bit width of this value.
FunctionPass * createInstructionCombiningPass(bool ExpensiveCombines=true)
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Type * getElementType() const
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
Class to represent pointers.
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
uint64_t getElementOffset(unsigned Idx) const
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
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)
initializer< Ty > init(const Ty &Val)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
static Instruction::BinaryOps getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode, BinaryOperator *Op, Value *&LHS, Value *&RHS)
This function factors binary ops which can be combined using distributive laws.
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
bool run()
Run the combiner over the entire worklist until it is empty.
APInt trunc(unsigned width) const
Truncate to new width.
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
ConstantInt * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to .objectsize into an integer value of the given Type.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo)
Return 'true' if the given typeinfo will match anything.
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
This is an important base class in LLVM.
const Value * getCondition() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
int64_t getSExtValue() const
Get sign extended value.
static bool LeftDistributesOverRight(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
Return whether "X LOp (Y ROp Z)" is always equal to "(X LOp Y) ROp (X LOp Z)".
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
A manager for alias analyses.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
Value * getRawDest() const
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
APInt sext(unsigned width) const
Sign extend to a new width.
bool isConstant() const
Returns true if we know the value of all bits.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Value * SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const InstListType & getInstList() const
Return the underlying instruction list container.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
This instruction compares its operands according to the predicate given to the constructor.
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer arithmetic operators which may exhibit overflow - Add, Sub, and Mul.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
uint64_t getNumElements() const
void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static CastInst * CreatePointerBitCastOrAddrSpaceCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast or an AddrSpaceCast cast instruction.
bool isCommutative() const
Return true if the instruction is commutative:
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction 'To' is reachable from 'From', returning true if uncertain.
self_iterator getIterator()
Class to represent integer types.
Constant Vector Declarations.
The legacy pass manager's instcombine pass.
static Constant * getNot(Constant *C)
void setSourceElementType(Type *Ty)
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
static cl::opt< unsigned > MaxArraySize("instcombine-maxarray-size", cl::init(1024), cl::desc("Maximum array size considered when doing a combine"))
InstCombineWorklist - This is the worklist management logic for InstCombine.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
LLVMContext & getContext() const
All values hold a context through their type.
static wasm::ValType getType(const TargetRegisterClass *RC)
bool LowerDbgDeclare(Function &F)
Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
const Value * getTrueValue() const
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
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...
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
neg_match< LHS > m_Neg(const LHS &L)
Match an integer negate.
bool isConditional() const
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
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...
A function analysis which provides an AssumptionCache.
BinaryOps getOpcode() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
This is the shared class of boolean and integer constants.
static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1)
Combine constant operands of associative operations either before or after a cast to eliminate one of...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Utility class for floating point operations which can have information about relaxed accuracy require...
This is a utility class that provides an abstraction for the common functionality between Instruction...
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
static Value * CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS, InstCombiner::BuilderTy &B)
Creates node of binary operation with the same attributes as the specified one but with other operand...
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
Instruction * visitFree(CallInst &FI)
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.
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...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
int32_t exactLogBase2() const
const BasicBlock & getEntryBlock() const
void initializeInstCombine(PassRegistry &)
Initialize all passes linked into the InstCombine library.
unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than it's terminator and any present EH pad instruct...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
static ConstantInt * getTrue(LLVMContext &Context)
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)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
static Value * foldOperationIntoSelectOperand(Instruction &I, Value *SO, InstCombiner::BuilderTy &Builder)
Class to represent vector types.
static bool isNeg(const Value *V)
Check if the given Value is a NEG, FNeg, or NOT instruction.
ConstantArray - Constant Array Declarations.
Class for arbitrary precision integers.
static bool combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, bool ExpensiveCombines=true, LoopInfo *LI=nullptr)
bool isIntegerTy() const
True if this is an instance of IntegerType.
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.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
Instruction * visitSwitchInst(SwitchInst &SI)
unsigned getVectorNumElements() const
void AddInitialGroup(ArrayRef< Instruction * > List)
AddInitialGroup - Add the specified batch of stuff in reverse order.
static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock)
Try to move the specified instruction from its current block into the beginning of DestBlock...
Instruction * visitExtractValueInst(ExtractValueInst &EV)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Represents analyses that only rely on functions' control flow.
Value * getCondition() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
bool isMinValue() const
Determine if this is the smallest unsigned value.
Common super class of ArrayType, StructType and VectorType.
llvm_unreachable("Unknown RegBank!")
bool isStructTy() const
True if this is an instance of StructType.
Instruction * visitLandingPadInst(LandingPadInst &LI)
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Value * SimplifyGEPInst(Type *SrcTy, ArrayRef< Value * > Ops, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
static std::vector< std::string > Flags
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Value * getCondition() const
iterator insert(iterator where, pointer New)
void emplace_back(ArgTypes &&...Args)
void registerAssumption(CallInst *CI)
Add an .assume intrinsic to this function's cache.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
static bool isFNeg(const Value *V, bool IgnoreZeroSign=false)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void preserveSet()
Mark an analysis set as preserved.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
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 Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
VectorType * getType() const
Overload to return most specific vector type.
void preserve()
Mark an analysis as preserved.
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
void initializeInstructionCombiningPassPass(PassRegistry &)
void setCondition(Value *V)
Analysis pass providing the TargetLibraryInfo.
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
A raw_ostream that writes to an std::string.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
This file provides internal interfaces used to implement the InstCombine.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void clearSubclassOptionalData()
Clear the optional flags contained in this value.
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.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
static Instruction * tryToMoveFreeBeforeNullTest(CallInst &FI)
Move the call to free before a NULL test.
Instruction * visitGetElementPtrInst(GetElementPtrInst &GEP)
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
const Value * getFalseValue() const
Convenience struct for specifying and reasoning about fast-math flags.
This is the interface for LLVM's primary stateless and local alias analysis.
inst_range instructions(Function *F)
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
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 BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src)
static void getShuffleMask(Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Value * getPointerOperand()
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...
Instruction * visitAllocSite(Instruction &FI)
const BasicBlock * getParent() const
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
Accumulate offsets from stripInBoundsConstantOffsets().
A wrapper class for inspecting calls to intrinsic functions.
This instruction inserts a struct field of array element value into an aggregate value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
Legacy wrapper pass to provide the BasicAAResult object.
gep_type_iterator gep_type_begin(const User *GEP)