110 using namespace llvm;
113 #define DEBUG_TYPE "instcombine" 115 STATISTIC(NumCombined ,
"Number of insts combined");
116 STATISTIC(NumConstProp,
"Number of constant folds");
117 STATISTIC(NumDeadInst ,
"Number of dead inst eliminated");
118 STATISTIC(NumSunkInst ,
"Number of instructions sunk");
119 STATISTIC(NumExpand,
"Number of expansions");
120 STATISTIC(NumFactor ,
"Number of factorizations");
121 STATISTIC(NumReassoc ,
"Number of reassociations");
123 "Controls which instructions are visited");
134 cl::desc(
"Enable expensive instruction combines"));
137 "instcombine-max-iterations",
138 cl::desc(
"Limit the maximum number of instruction combining iterations"),
142 "instcombine-infinite-loop-threshold",
143 cl::desc(
"Number of instruction combining iterations considered an " 149 cl::desc(
"Maximum array size considered when doing a combine"));
174 bool InstCombiner::shouldChangeType(
unsigned FromWidth,
175 unsigned ToWidth)
const {
176 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
177 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
181 if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32))
186 if (FromLegal && !ToLegal)
191 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
202 bool InstCombiner::shouldChangeType(
Type *
From,
Type *To)
const {
210 return shouldChangeType(FromWidth, ToWidth);
220 if (!OBO || !OBO->hasNoSignedWrap())
228 const APInt *BVal, *CVal;
232 bool Overflow =
false;
234 (void)BVal->
sadd_ov(*CVal, Overflow);
236 (
void)BVal->
ssub_ov(*CVal, Overflow);
272 if (!Cast || !Cast->hasOneUse())
277 if (CastOpcode != Instruction::ZExt)
286 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
303 Cast->setOperand(0, BinOp2->getOperand(0));
328 bool InstCombiner::SimplifyAssociativeOrCommutative(
BinaryOperator &
I) {
330 bool Changed =
false;
378 if (Op1 && Op1->getOpcode() == Opcode) {
380 Value *
B = Op1->getOperand(0);
426 if (Op1 && Op1->getOpcode() == Opcode) {
428 Value *
B = Op1->getOperand(0);
450 Op0->
getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
460 if (isa<FPMathOperator>(NewBO)) {
463 Flags &= Op1->getFastMathFlags();
466 InsertNewInstWith(NewBO, I);
492 if (LOp == Instruction::And)
493 return ROp == Instruction::Or || ROp == Instruction::Xor;
496 if (LOp == Instruction::Or)
497 return ROp == Instruction::And;
501 if (LOp == Instruction::Mul)
525 if (isa<Constant>(V))
539 assert(Op &&
"Expected a binary operator");
547 return Instruction::Mul;
559 assert(A && B && C && D &&
"All values must be provided");
562 Value *SimplifiedInst =
nullptr;
573 if (A == C || (InnerCommutative && A == D)) {
578 V =
SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
581 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
582 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->
getName());
584 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V);
592 if (B == D || (InnerCommutative && B == C)) {
597 V =
SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
601 if (!V && LHS->
hasOneUse() && RHS->hasOneUse())
602 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->
getName());
604 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B);
608 if (SimplifiedInst) {
613 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
614 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
617 if (isa<OverflowingBinaryOperator>(&I)) {
622 if (
auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {
623 HasNSW &= LOBO->hasNoSignedWrap();
624 HasNUW &= LOBO->hasNoUnsignedWrap();
627 if (
auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {
628 HasNSW &= ROBO->hasNoSignedWrap();
629 HasNUW &= ROBO->hasNoUnsignedWrap();
633 InnerOpcode == Instruction::Mul) {
644 BO->setHasNoSignedWrap(HasNSW);
648 BO->setHasNoUnsignedWrap(HasNUW);
653 return SimplifiedInst;
678 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
679 if (
Value *V = tryFactorization(I, LHSOpcode, A, B, C, D))
686 if (
Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident))
693 if (
Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D))
711 C = Builder.CreateBinOp(InnerOpcode, L, R);
720 C = Builder.CreateBinOp(TopLevelOpcode, B, C);
729 C = Builder.CreateBinOp(TopLevelOpcode, A, C);
738 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
748 A = Builder.CreateBinOp(InnerOpcode, L, R);
757 A = Builder.CreateBinOp(TopLevelOpcode, A, C);
766 A = Builder.CreateBinOp(TopLevelOpcode, A, B);
772 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
780 if (!LHSIsSelect && !RHSIsSelect)
785 if (isa<FPMathOperator>(&I)) {
787 Builder.setFastMathFlags(FMF);
793 Value *Cond, *True =
nullptr, *False =
nullptr;
794 if (LHSIsSelect && RHSIsSelect && A == D) {
802 True = Builder.CreateBinOp(Opcode, B, E);
803 else if (True && !False)
804 False = Builder.CreateBinOp(Opcode, C, F);
806 }
else if (LHSIsSelect && LHS->
hasOneUse()) {
811 }
else if (RHSIsSelect && RHS->
hasOneUse()) {
821 Value *
SI = Builder.CreateSelect(Cond, True, False);
828 Value *InstCombiner::dyn_castNegVal(
Value *V)
const {
842 for (
unsigned i = 0,
e = CV->getNumOperands(); i !=
e; ++i) {
847 if (isa<UndefValue>(Elt))
850 if (!isa<ConstantInt>(Elt))
861 if (
auto *Cast = dyn_cast<CastInst>(&I))
867 bool ConstIsRHS = isa<Constant>(I.
getOperand(1));
870 if (
auto *SOC = dyn_cast<Constant>(SO)) {
876 Value *Op0 = SO, *Op1 = ConstOperand;
880 auto *BO = cast<BinaryOperator>(&
I);
884 if (FPInst && isa<FPMathOperator>(FPInst))
896 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
905 if (
auto *BC = dyn_cast<BitCastInst>(&Op)) {
910 if ((SrcTy ==
nullptr) != (DestTy ==
nullptr))
926 if (CI->hasOneUse()) {
927 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
941 bool ConstIsRHS = isa<Constant>(I->
getOperand(1));
944 if (
auto *InC = dyn_cast<Constant>(InV)) {
950 Value *Op0 = InV, *Op1 =
C;
956 if (FPInst && isa<FPMathOperator>(FPInst))
963 if (NumPHIValues == 0)
985 for (
unsigned i = 0; i != NumPHIValues; ++i) {
987 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
990 if (isa<PHINode>(InVal))
return nullptr;
991 if (NonConstBB)
return nullptr;
997 if (isa<InvokeInst>(InVal))
998 if (cast<Instruction>(InVal)->
getParent() == NonConstBB)
1012 if (NonConstBB !=
nullptr) {
1019 InsertNewInstBefore(NewPN, *PN);
1028 if (
SelectInst *SI = dyn_cast<SelectInst>(&I)) {
1034 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1038 Value *InV =
nullptr;
1046 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
1047 InV = InC->
isNullValue() ? FalseVInPred : TrueVInPred;
1059 FalseVInPred,
"phitmp");
1063 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(&I)) {
1065 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1066 Value *InV =
nullptr;
1069 else if (isa<ICmpInst>(CI))
1077 }
else if (
auto *BO = dyn_cast<BinaryOperator>(&I)) {
1078 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1086 for (
unsigned i = 0; i != NumPHIValues; ++i) {
1099 if (User == &I)
continue;
1100 replaceInstUsesWith(*User, NewPN);
1101 eraseInstFromFunction(*User);
1103 return replaceInstUsesWith(I, NewPN);
1110 if (
auto *Sel = dyn_cast<SelectInst>(I.
getOperand(0))) {
1111 if (
Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1113 }
else if (
auto *PN = dyn_cast<PHINode>(I.
getOperand(0))) {
1133 Type *IndexTy = DL.getIndexType(PtrTy);
1134 int64_t FirstIdx = 0;
1135 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1136 FirstIdx = Offset/TySize;
1137 Offset -= FirstIdx*TySize;
1145 assert((uint64_t)Offset < (uint64_t)TySize &&
"Out of range offset");
1153 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1156 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
1159 "Offset must stay within the indexed type");
1166 Ty = STy->getElementType(Elt);
1167 }
else if (
ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1168 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1169 assert(EltSize &&
"Cannot index into a zero-sized array");
1172 Ty = AT->getElementType();
1194 Value *InstCombiner::Descale(
Value *Val,
APInt Scale,
bool &NoSignedWrap) {
1195 assert(isa<IntegerType>(Val->
getType()) &&
"Can only descale integers!");
1197 Scale.
getBitWidth() &&
"Scale not compatible with value!");
1201 NoSignedWrap =
true;
1233 std::pair<Instruction *, unsigned> Parent;
1237 bool RequireNoSignedWrap =
false;
1242 for (;; Op = Parent.first->getOperand(Parent.second)) {
1243 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1245 APInt Quotient(Scale), Remainder(Scale);
1252 NoSignedWrap =
true;
1257 if (BO->getOpcode() == Instruction::Mul) {
1259 NoSignedWrap = BO->hasNoSignedWrap();
1260 if (RequireNoSignedWrap && !NoSignedWrap)
1266 Value *LHS = BO->getOperand(0);
1267 Value *RHS = BO->getOperand(1);
1269 if (
ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1271 if (CI->getValue() == Scale) {
1282 Parent = std::make_pair(BO, 1);
1291 Parent = std::make_pair(BO, 0);
1295 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1296 isa<ConstantInt>(BO->getOperand(1))) {
1298 NoSignedWrap = BO->hasNoSignedWrap();
1299 if (RequireNoSignedWrap && !NoSignedWrap)
1302 Value *LHS = BO->getOperand(0);
1303 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1307 if (Amt == logScale) {
1318 Parent = std::make_pair(BO, 1);
1327 if (
CastInst *Cast = dyn_cast<CastInst>(Op)) {
1328 if (Cast->getOpcode() == Instruction::SExt) {
1330 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1342 RequireNoSignedWrap =
true;
1345 Parent = std::make_pair(Cast, 0);
1350 if (Cast->getOpcode() == Instruction::Trunc) {
1357 if (RequireNoSignedWrap)
1361 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1362 Parent = std::make_pair(Cast, 0);
1363 Scale = Scale.
sext(LargeSize);
1364 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1377 NoSignedWrap =
true;
1391 assert(Parent.first->hasOneUse() &&
"Drilled down when more than one use!");
1392 assert(Op != Parent.first->getOperand(Parent.second) &&
1393 "Descaling was a no-op?");
1394 Parent.first->setOperand(Parent.second, Op);
1395 Worklist.Add(Parent.first);
1410 NoSignedWrap &= OpNoSignedWrap;
1411 if (NoSignedWrap != OpNoSignedWrap) {
1412 BO->setHasNoSignedWrap(NoSignedWrap);
1413 Worklist.Add(Ancestor);
1415 }
else if (Ancestor->
getOpcode() == Instruction::Trunc) {
1419 NoSignedWrap =
false;
1421 assert((Ancestor->
getOpcode() != Instruction::SExt || NoSignedWrap) &&
1422 "Failed to keep proper track of nsw flags while drilling down?");
1424 if (Ancestor == Val)
1429 assert(Ancestor->
hasOneUse() &&
"Drilled down when more than one use!");
1438 unsigned NumElts = cast<VectorType>(Inst.
getType())->getNumElements();
1440 assert(cast<VectorType>(LHS->
getType())->getNumElements() == NumElts);
1441 assert(cast<VectorType>(RHS->
getType())->getNumElements() == NumElts);
1446 Value *L0, *L1, *R0, *R1;
1451 cast<ShuffleVectorInst>(LHS)->isConcat() &&
1452 cast<ShuffleVectorInst>(RHS)->isConcat()) {
1458 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
1459 if (
auto *BO = dyn_cast<BinaryOperator>(NewBO0))
1460 BO->copyIRFlags(&Inst);
1461 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
1462 if (
auto *BO = dyn_cast<BinaryOperator>(NewBO1))
1463 BO->copyIRFlags(&Inst);
1474 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
1475 if (
auto *BO = dyn_cast<BinaryOperator>(XY))
1476 BO->copyIRFlags(&Inst);
1488 return createBinOpShuffle(V1, V2, Mask);
1497 auto *LShuf = cast<ShuffleVectorInst>(LHS);
1498 auto *RShuf = cast<ShuffleVectorInst>(RHS);
1503 if (LShuf->isSelect() && !LShuf->getMask()->containsUndefElement() &&
1504 RShuf->isSelect() && !RShuf->getMask()->containsUndefElement()) {
1526 "Shuffle should not change scalar type");
1533 bool ConstOp1 = isa<Constant>(RHS);
1539 bool MayChange =
true;
1540 for (
unsigned I = 0; I < NumElts; ++
I) {
1542 if (ShMask[I] >= 0) {
1543 assert(ShMask[I] < (
int)NumElts &&
"Not expecting narrowing shuffle");
1551 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) ||
1552 I >= SrcVecNumElts) {
1556 NewVecC[ShMask[
I]] = CElt;
1567 if (I >= SrcVecNumElts || ShMask[I] < 0) {
1571 if (!isa<UndefValue>(MaybeUndef)) {
1587 Value *NewLHS = ConstOp1 ? V1 : NewC;
1588 Value *NewRHS = ConstOp1 ? NewC : V1;
1589 return createBinOpShuffle(NewLHS, NewRHS, Mask);
1618 cast<Operator>(Op1)->
getOpcode() == CastOpc &&
1619 (Op0->
hasOneUse() || Op1->hasOneUse()))) {
1642 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(),
X,
Y,
"narrow");
1643 if (
auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
1645 NewBinOp->setHasNoSignedWrap();
1647 NewBinOp->setHasNoUnsignedWrap();
1666 return replaceInstUsesWith(GEP, V);
1671 APInt UndefElts(VWidth, 0);
1673 if (
Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
1676 return replaceInstUsesWith(GEP, V);
1689 bool MadeChange =
false;
1693 Type *NewScalarIndexTy =
1703 Type *IndexTy = (*I)->getType();
1704 Type *NewIndexType =
1712 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1713 if (!isa<Constant>(*I) || !
match(I->get(),
m_Zero())) {
1718 if (IndexTy != NewIndexType) {
1722 *I = Builder.CreateIntCast(*I, NewIndexType,
true);
1730 if (
auto *PN = dyn_cast<PHINode>(PtrOp)) {
1748 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1756 Type *CurTy =
nullptr;
1758 for (
unsigned J = 0,
F = Op1->getNumOperands(); J !=
F; ++J) {
1759 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1762 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1771 assert(CurTy &&
"No current type?");
1791 CurTy = Op1->getSourceElementType();
1792 }
else if (
auto *CT = dyn_cast<CompositeType>(CurTy)) {
1793 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1807 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1820 Builder.SetInsertPoint(PN);
1821 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1826 NewPN->
addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1829 NewGEP->setOperand(DI, NewPN);
1832 NewGEP->setOperand(DI, NewPN);
1842 if (
auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
1847 if (LI && Src->getNumOperands() == 2 && GEP.
getNumOperands() == 2 &&
1851 Value *SO1 = Src->getOperand(1);
1855 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
1873 auto *SO0 = Src->getOperand(0);
1875 if (!isa<VectorType>(GEPType) ||
1876 isa<VectorType>(SO0Ty)) {
1877 Src->setOperand(1, GO1);
1884 Builder.SetInsertPoint(cast<Instruction>(PtrOp));
1885 auto *NewSrc = cast<GetElementPtrInst>(
1886 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->
getName()));
1887 NewSrc->setIsInBounds(Src->isInBounds());
1899 if (
auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
1906 bool EndsWithSequential =
false;
1909 EndsWithSequential = I.isSequential();
1912 if (EndsWithSequential) {
1915 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1933 if (Src->getNumOperands() == 2) {
1939 Indices.
append(Src->op_begin()+1, Src->op_end()-1);
1942 }
else if (isa<Constant>(*GEP.
idx_begin()) &&
1943 cast<Constant>(*GEP.
idx_begin())->isNullValue() &&
1944 Src->getNumOperands() != 1) {
1946 Indices.
append(Src->op_begin()+1, Src->op_end());
1950 if (!Indices.
empty())
1953 Src->getSourceElementType(), Src->getOperand(0), Indices,
1956 Src->getOperand(0), Indices,
1963 DL.getIndexSizeInBits(AS)) {
1964 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType);
1966 bool Matched =
false;
1969 if (TyAllocSize == 1) {
1974 if (TyAllocSize == 1ULL << C)
1978 if (TyAllocSize == C)
1989 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->
getType());
2004 if (GEPType->isVectorTy())
2011 if (StrippedPtr != PtrOp) {
2012 bool HasZeroPointerIndex =
false;
2015 if (
auto *C = dyn_cast<ConstantInt>(GEP.
getOperand(1)))
2016 HasZeroPointerIndex = C->isZero();
2025 if (HasZeroPointerIndex) {
2026 if (
auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
2028 if (CATy->getElementType() == StrippedPtrEltTy) {
2032 StrippedPtrEltTy, StrippedPtr, Idx, GEP.
getName());
2045 if (
auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) {
2047 if (CATy->getElementType() == XATy->getElementType()) {
2070 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2072 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2084 DL.getTypeAllocSize(GEPEltType)) {
2085 Type *IdxType = DL.getIndexType(GEPType);
2089 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2091 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2105 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
2106 uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy);
2107 if (ResSize && SrcSize % ResSize == 0) {
2110 uint64_t Scale = SrcSize / ResSize;
2116 "Index type does not match the Data Layout preferences");
2119 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
2125 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2127 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx,
2145 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
2146 uint64_t ArrayEltSize =
2148 if (ResSize && ArrayEltSize % ResSize == 0) {
2151 uint64_t Scale = ArrayEltSize / ResSize;
2157 "Index type does not match the Data Layout preferences");
2160 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
2164 Type *IndTy = DL.getIndexType(GEPType);
2169 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2171 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off,
2185 Value *ASCStrippedPtrOp = PtrOp;
2186 if (
auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2191 if (
auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2192 ASCStrippedPtrOp = BC;
2195 if (
auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
2197 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2204 auto areMatchingArrayAndVecTypes = [](
Type *ArrTy,
Type *VecTy,
2208 DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy);
2211 ((GEPEltType->
isArrayTy() && SrcEltType->isVectorTy() &&
2212 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) ||
2213 (GEPEltType->
isVectorTy() && SrcEltType->isArrayTy() &&
2214 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) {
2222 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]})
2223 : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]});
2230 return replaceInstUsesWith(GEP, NGEP);
2238 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
2251 BCI->getParent()->getInstList().insert(BCI->getIterator(),
I);
2252 replaceInstUsesWith(*BCI, I);
2267 if (FindElementAtOffset(SrcType, Offset.
getSExtValue(), NewIndices)) {
2270 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices)
2271 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices);
2273 if (NGEP->
getType() == GEPType)
2274 return replaceInstUsesWith(GEP, NGEP);
2287 APInt BasePtrOffset(IdxWidth, 0);
2288 Value *UnderlyingPtrOp =
2291 if (
auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2294 APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
2295 if (BasePtrOffset.
ule(AllocSize)) {
2309 if (isa<ConstantPointerNull>(V))
2311 if (
auto *LI = dyn_cast<LoadInst>(V))
2312 return isa<GlobalVariable>(LI->getPointerOperand());
2336 case Instruction::AddrSpaceCast:
2337 case Instruction::BitCast:
2338 case Instruction::GetElementPtr:
2343 case Instruction::ICmp: {
2350 unsigned OtherIndex = (ICI->
getOperand(0) == PI) ? 1 : 0;
2360 switch (II->getIntrinsicID()) {
2364 case Intrinsic::memmove:
2365 case Intrinsic::memcpy:
2366 case Intrinsic::memset: {
2372 case Intrinsic::invariant_start:
2373 case Intrinsic::invariant_end:
2374 case Intrinsic::lifetime_start:
2375 case Intrinsic::lifetime_end:
2376 case Intrinsic::objectsize:
2398 }
while (!Worklist.
empty());
2418 std::unique_ptr<DIBuilder> DIB;
2419 if (isa<AllocaInst>(MI)) {
2425 for (
unsigned i = 0,
e = Users.
size(); i !=
e; ++i) {
2434 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2437 replaceInstUsesWith(*I, Result);
2438 eraseInstFromFunction(*I);
2443 for (
unsigned i = 0,
e = Users.
size(); i !=
e; ++i) {
2449 if (
ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2450 replaceInstUsesWith(*C,
2452 C->isFalseWhenEqual()));
2453 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
2454 for (
auto *DII : DIIs)
2461 eraseInstFromFunction(*I);
2464 if (
InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2466 Module *M = II->getModule();
2469 None,
"", II->getParent());
2472 for (
auto *DII : DIIs)
2473 eraseInstFromFunction(*DII);
2475 return eraseInstFromFunction(MI);
2519 if (FreeInstrBB->
size() != 2) {
2521 if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
2524 if (!Cast || !Cast->isNoopCast(DL))
2545 "Broken CFG: missing edge from predecessor to successor");
2552 if (&Instr == FreeInstrBBTerminator)
2557 "Only the branch instruction should remain");
2565 if (isa<UndefValue>(Op)) {
2567 CreateNonTerminatorUnreachable(&FI);
2568 return eraseInstFromFunction(FI);
2573 if (isa<ConstantPointerNull>(Op))
2574 return eraseInstFromFunction(FI);
2611 !isa<Constant>(X)) {
2648 for (
auto Case : SI.
cases()) {
2650 assert(isa<ConstantInt>(NewCase) &&
2651 "Result of expression should be constant");
2652 Case.setValue(cast<ConstantInt>(NewCase));
2664 for (
auto &C : SI.
cases()) {
2665 LeadingKnownZeros = std::min(
2666 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2667 LeadingKnownOnes = std::min(
2668 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2677 if (NewWidth > 0 && NewWidth < Known.
getBitWidth() &&
2678 shouldChangeType(Known.
getBitWidth(), NewWidth)) {
2680 Builder.SetInsertPoint(&SI);
2681 Value *NewCond = Builder.CreateTrunc(Cond, Ty,
"trunc");
2684 for (
auto Case : SI.
cases()) {
2685 APInt TruncatedCase = Case.getCaseValue()->getValue().
trunc(NewWidth);
2698 return replaceInstUsesWith(EV, Agg);
2701 SQ.getWithInstruction(&EV)))
2702 return replaceInstUsesWith(EV, V);
2706 const unsigned *exti, *exte, *insi, *inse;
2707 for (exti = EV.
idx_begin(), insi = IV->idx_begin(),
2708 exte = EV.
idx_end(), inse = IV->idx_end();
2709 exti != exte && insi != inse;
2723 if (exti == exte && insi == inse)
2728 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2738 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2759 if (WO->hasOneUse()) {
2764 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
2766 eraseInstFromFunction(*WO);
2773 if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2774 if (
ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS()))
2779 if (
LoadInst *L = dyn_cast<LoadInst>(Agg))
2785 if (L->isSimple() && L->hasOneUse()) {
2792 Indices.
push_back(Builder.getInt32(*I));
2796 Builder.SetInsertPoint(L);
2797 Value *
GEP = Builder.CreateInBoundsGEP(L->getType(),
2798 L->getPointerOperand(), Indices);
2803 L->getAAMetadata(Nodes);
2807 return replaceInstUsesWith(EV, NL);
2822 switch (Personality) {
2850 cast<ArrayType>(LHS->
getType())->getNumElements()
2852 cast<ArrayType>(RHS->
getType())->getNumElements();
2864 bool MakeNewInstruction =
false;
2870 bool isLastClause = i + 1 ==
e;
2878 if (AlreadyCaught.
insert(TypeInfo).second) {
2883 MakeNewInstruction =
true;
2890 MakeNewInstruction =
true;
2891 CleanupFlag =
false;
2904 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2910 if (!NumTypeInfos) {
2913 MakeNewInstruction =
true;
2914 CleanupFlag =
false;
2918 bool MakeNewFilter =
false;
2920 if (isa<ConstantAggregateZero>(FilterClause)) {
2922 assert(NumTypeInfos > 0 &&
"Should have handled empty filter already!");
2928 MakeNewInstruction =
true;
2935 if (NumTypeInfos > 1)
2936 MakeNewFilter =
true;
2940 NewFilterElts.
reserve(NumTypeInfos);
2945 bool SawCatchAll =
false;
2946 for (
unsigned j = 0; j != NumTypeInfos; ++j) {
2974 if (SeenInFilter.insert(TypeInfo).second)
2975 NewFilterElts.
push_back(cast<Constant>(Elt));
2980 MakeNewInstruction =
true;
2985 if (NewFilterElts.
size() < NumTypeInfos)
2986 MakeNewFilter =
true;
2988 if (MakeNewFilter) {
2990 NewFilterElts.
size());
2992 MakeNewInstruction =
true;
3001 if (MakeNewFilter && !NewFilterElts.
size()) {
3002 assert(MakeNewInstruction &&
"New filter but not a new instruction!");
3003 CleanupFlag =
false;
3014 for (
unsigned i = 0,
e = NewClauses.
size(); i + 1 <
e; ) {
3017 for (j = i; j !=
e; ++j)
3018 if (!isa<ArrayType>(NewClauses[j]->
getType()))
3024 for (
unsigned k = i; k + 1 < j; ++k)
3030 MakeNewInstruction =
true;
3049 for (
unsigned i = 0; i + 1 < NewClauses.
size(); ++i) {
3059 for (
unsigned j = NewClauses.
size() - 1; j != i; --j) {
3060 Value *LFilter = NewClauses[j];
3071 NewClauses.
erase(J);
3072 MakeNewInstruction =
true;
3082 if (isa<ConstantAggregateZero>(LFilter)) {
3085 if (isa<ConstantAggregateZero>(Filter)) {
3086 assert(FElts <= LElts &&
"Should have handled this case earlier!");
3088 NewClauses.
erase(J);
3089 MakeNewInstruction =
true;
3095 if (isa<ConstantAggregateZero>(Filter)) {
3098 assert(FElts > 0 &&
"Should have eliminated the empty filter earlier!");
3099 for (
unsigned l = 0; l != LElts; ++l)
3102 NewClauses.
erase(J);
3103 MakeNewInstruction =
true;
3114 bool AllFound =
true;
3115 for (
unsigned f = 0; f != FElts; ++f) {
3118 for (
unsigned l = 0; l != LElts; ++l) {
3120 if (LTypeInfo == FTypeInfo) {
3130 NewClauses.
erase(J);
3131 MakeNewInstruction =
true;
3139 if (MakeNewInstruction) {
3142 for (
unsigned i = 0, e = NewClauses.
size(); i !=
e; ++i)
3147 if (NewClauses.
empty())
3156 assert(!CleanupFlag &&
"Adding a cleanup, not removing one?!");
3168 return replaceInstUsesWith(I, V);
3190 if (isa<AllocaInst>(I))
3198 if (
auto *CI = dyn_cast<CallInst>(I)) {
3199 if (CI->isConvergent())
3208 if (Scan->mayWriteToMemory())
3222 for (
auto *DII :
reverse(DbgUsers)) {
3223 if (DII->getParent() == SrcBlock) {
3224 if (isa<DbgDeclareInst>(DII)) {
3230 if (!isa<CastInst>(I))
3243 cast<DbgVariableIntrinsic>(DII->clone())};
3249 TmpUser[0]->insertBefore(&*InsertPos);
3257 TmpUser[0]->insertBefore(DII);
3258 DII->moveBefore(&*InsertPos);
3266 while (!Worklist.isEmpty()) {
3268 if (I ==
nullptr)
continue;
3273 eraseInstFromFunction(*I);
3275 MadeIRChange =
true;
3286 LLVM_DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: " << *I
3290 replaceInstUsesWith(*I, C);
3293 eraseInstFromFunction(*I);
3294 MadeIRChange =
true;
3307 <<
" from: " << *I <<
'\n');
3310 replaceInstUsesWith(*I, C);
3313 eraseInstFromFunction(*I);
3314 MadeIRChange =
true;
3326 if (
PHINode *PN = dyn_cast<PHINode>(UserInst))
3331 if (UserParent != BB) {
3332 bool UserIsSuccessor =
false;
3335 if (*SI == UserParent) {
3336 UserIsSuccessor =
true;
3343 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3347 MadeIRChange =
true;
3352 if (
Instruction *OpI = dyn_cast<Instruction>(U.get()))
3360 Builder.SetInsertPoint(I);
3361 Builder.SetCurrentDebugLocation(I->
getDebugLoc());
3374 <<
" New = " << *Result <<
'\n');
3382 Result->takeName(I);
3390 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3396 Worklist.AddUsersToWorkList(*Result);
3397 Worklist.Add(Result);
3399 eraseInstFromFunction(*I);
3402 <<
" New = " << *I <<
'\n');
3407 eraseInstFromFunction(*I);
3409 Worklist.AddUsersToWorkList(*I);
3413 MadeIRChange =
true;
3418 return MadeIRChange;
3433 bool MadeIRChange =
false;
3444 if (!Visited.
insert(BB).second)
3456 MadeIRChange =
true;
3464 LLVM_DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: " << *Inst
3470 MadeIRChange =
true;
3476 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3479 auto *C = cast<Constant>(U);
3480 Constant *&FoldRes = FoldedConstants[
C];
3488 <<
"\n Old = " << *C
3489 <<
"\n New = " << *FoldRes <<
'\n');
3491 MadeIRChange =
true;
3497 if (!isa<DbgInfoIntrinsic>(Inst))
3498 InstrsForInstCombineWorklist.
push_back(Inst);
3504 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3505 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3506 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3507 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3511 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3513 Worklist.
push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3520 }
while (!Worklist.
empty());
3529 return MadeIRChange;
3540 bool MadeIRChange =
false;
3553 if (Visited.count(&BB))
3557 MadeIRChange |= NumDeadInstInBB > 0;
3558 NumDeadInst += NumDeadInstInBB;
3561 return MadeIRChange;
3581 if (
match(I, m_Intrinsic<Intrinsic::assume>()))
3587 bool MadeIRChange =
false;
3592 unsigned Iteration = 0;
3598 "Instruction Combining seems stuck in an infinite loop after " +
3602 if (Iteration > MaxIterations) {
3603 LLVM_DEBUG(
dbgs() <<
"\n\n[IC] Iteration limit #" << MaxIterations
3605 <<
" reached; stopping before reaching a fixpoint\n");
3609 LLVM_DEBUG(
dbgs() <<
"\n\nINSTCOMBINE ITERATION #" << Iteration <<
" on " 3615 AC, TLI, DT, ORE,
BFI, PSI, DL, LI);
3621 MadeIRChange =
true;
3624 return MadeIRChange;
3631 : ExpensiveCombines(ExpensiveCombines), MaxIterations(MaxIterations) {}
3651 PSI, ExpensiveCombines, MaxIterations,
3681 if (skipFunction(F))
3685 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3686 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3687 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
3688 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3689 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3692 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3693 auto *LI = LIWP ? &LIWP->getLoopInfo() :
nullptr;
3695 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3698 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
3702 PSI, ExpensiveCombines, MaxIterations,
3715 unsigned MaxIterations)
3717 MaxIterations(MaxIterations) {
3722 "Combine redundant instructions",
false,
false)
3748 unsigned MaxIterations) {
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.
Type * getVectorElementType() const
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.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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. ...
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...
static ConstantInt * getFalse(LLVMContext &Context)
reference emplace_back(ArgTypes &&... Args)
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.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
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.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
APInt sext(unsigned width) const
Sign extend to a new width.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void LLVMInitializeInstCombine(LLVMPassRegistryRef R)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
SimplifyQuery getWithInstruction(Instruction *I) const
BinaryOps getOpcode() const
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.
Represents an op.with.overflow intrinsic.
A Module instance is used to store all the information related to an LLVM module. ...
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static Value * foldOperationIntoPhiValue(BinaryOperator *I, Value *InV, InstCombiner::BuilderTy &Builder)
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock *> *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
static void ClearSubclassDataAfterReassociation(BinaryOperator &I)
Conservatively clears subclassOptionalData after a reassociation or commutation.
void push_back(const T &Elt)
Analysis providing profile information.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
br_match m_UnconditionalBr(BasicBlock *&Succ)
A global registry used in conjunction with static constructors to make pluggable components (like tar...
void findDbgUsers(SmallVectorImpl< DbgVariableIntrinsic *> &DbgInsts, Value *V)
Finds the debug info intrinsics describing a value.
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
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)
const Value * getTrueValue() const
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
A cache of @llvm.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)
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
struct LLVMOpaquePassRegistry * LLVMPassRegistryRef
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
BasicBlock * getSuccessor(unsigned i) const
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
APInt trunc(unsigned width) const
Truncate to new width.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
ThreeOps_match< V1_t, V2_t, Mask_t, Instruction::ShuffleVector > m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m)
Matches ShuffleVectorInst.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
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.
Value * getCondition() const
static bool combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, bool ExpensiveCombines, unsigned MaxIterations, LoopInfo *LI)
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
iv Induction Variable Users
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This defines the Use class.
void reserve(size_type N)
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
unsigned getBitWidth() const
Get the bit width of this value.
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
static cl::opt< unsigned > LimitMaxIterations("instcombine-max-iterations", cl::desc("Limit the maximum number of instruction combining iterations"), cl::init(InstCombineDefaultMaxIterations))
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...
unsigned getBitWidth() const
Return the number of bits in the APInt.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
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.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
bool swapOperands()
Exchange the two operands to this instruction.
Value * getArgOperand(unsigned i) const
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
static Instruction * tryToMoveFreeBeforeNullTest(CallInst &FI, const DataLayout &DL)
Move the call to free before a NULL test.
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)
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.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Attribute unwrap(LLVMAttributeRef Attr)
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
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.
'undef' values are things that do not have specified contents.
uint64_t getArrayNumElements() const
Class to represent struct types.
Value * SimplifyGEPInst(Type *SrcTy, ArrayRef< Value *> Ops, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
A Use represents the edge between a Value definition and its users.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
bool isIntegerTy() const
True if this is an instance of IntegerType.
The core instruction combiner logic.
static cl::opt< bool > EnableExpensiveCombines("expensive-combines", cl::desc("Enable expensive instruction combines"))
Analysis pass that exposes the LoopInfo for a function.
This file provides an implementation of debug counters.
static bool shorter_filter(const Value *LHS, const Value *RHS)
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Type * getSourceElementType() const
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
This file implements a class to represent arbitrary precision integral constant values and operations...
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
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)
Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool isBitwiseLogicOp() const
Return true if this is and/or/xor.
unsigned getNumIndices() const
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
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 *...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
int64_t getSExtValue() const
Get sign extended value.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, Instruction *AI)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
Class to represent array types.
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
InstructionCombiningPass(bool ExpensiveCombines=true)
void salvageDebugInfoOrMarkUndef(Instruction &I)
Salvage all debug users of the instruction I or mark it as undef if it cannot be salvaged.
int32_t exactLogBase2() 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.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
TargetFolder - Create constants with target dependent folding.
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
An instruction for storing to memory.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static bool hasNoSignedWrap(BinaryOperator &I)
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...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
static Instruction::BinaryOps getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, Value *&LHS, Value *&RHS)
This function predicates factorization using distributive laws.
Class to represent pointers.
static cl::opt< unsigned > MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4))
Interval::succ_iterator succ_end(Interval *I)
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool hasProfileSummary()
Returns true if profile summary is available.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
OneUse_match< T > m_OneUse(const T &SubPattern)
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
initializer< Ty > init(const Ty &Val)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
bool run()
Run the combiner over the entire worklist until it is empty.
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo)
Return 'true' if the given typeinfo will match anything.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
const APInt & getConstant() const
Returns the value when all bits have a known value.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static BinaryOperator * CreateNUW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
A manager for alias analyses.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
void AddInitialGroup(ArrayRef< Instruction *> List)
AddInitialGroup - Add the specified batch of stuff in reverse order.
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.
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Represent the analysis usage information of a pass.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool isConstant() const
Returns true if we know the value of all bits.
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 operators which may exhibit overflow - Add, Sub, Mul, and Shl...
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, CastClass_match< OpTy, Instruction::SExt > > m_ZExtOrSExt(const OpTy &Op)
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.
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.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C)
static bool shouldExecute(unsigned CounterName)
Class to represent integer types.
Constant Vector Declarations.
The legacy pass manager's instcombine pass.
Instruction * visitFreeze(FreezeInst &I)
static Constant * getNot(Constant *C)
void setSourceElementType(Type *Ty)
static cl::opt< unsigned > MaxArraySize("instcombine-maxarray-size", cl::init(1024), cl::desc("Maximum array size considered when doing a combine"))
const Value * getCondition() const
static bool hasNoUnsignedWrap(BinaryOperator &I)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Type * getPointerOperandType() const
Method to return the pointer operand as a PointerType.
Type * getIndexedType() const
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.
const Constant * stripPointerCasts() const
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
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...
static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2)
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool LowerDbgDeclare(Function &F)
Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
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...
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
A function analysis which provides an AssumptionCache.
const InstListType & getInstList() const
Return the underlying instruction list container.
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...
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
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...
TinyPtrVector< DbgVariableIntrinsic * > FindDbgAddrUses(Value *V)
Finds all intrinsics declaring local variables as living in the memory that 'V' points to...
BlockVerifier::State From
static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold
Align max(MaybeAlign Lhs, Align Rhs)
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
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...
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.
static cl::opt< bool > EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"), cl::init(true))
This class represents a freeze function that returns random concrete value if an operand is either a ...
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
static constexpr unsigned InstCombineDefaultMaxIterations
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
Instruction * visitFree(CallInst &FI)
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool isConditional() const
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:
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...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool isCommutative() const
Return true if the instruction is commutative:
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.
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.
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getVectorNumElements() const
struct LLVMOpaquePassManager * LLVMPassManagerRef
static Value * foldOperationIntoSelectOperand(Instruction &I, Value *SO, InstCombiner::BuilderTy &Builder)
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
ConstantArray - Constant Array Declarations.
Class for arbitrary precision integers.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
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()
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
Instruction * visitSwitchInst(SwitchInst &SI)
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.
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
const Value * getFalseValue() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
static cl::opt< unsigned > InfiniteLoopDetectionThreshold("instcombine-infinite-loop-threshold", cl::desc("Number of instruction combining iterations considered an " "infinite loop"), cl::init(InstCombineDefaultInfiniteLoopThreshold), cl::Hidden)
Instruction * visitLandingPadInst(LandingPadInst &LI)
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Analysis pass providing a never-invalidated alias analysis result.
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)".
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 ...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
bool isVolatile() const
Return true if this is a store to a volatile memory location.
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
uint64_t getElementOffset(unsigned Idx) const
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS)
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void preserveSet()
Mark an analysis set as preserved.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
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...
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
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)
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
void preserve()
Mark an analysis as preserved.
DEBUG_COUNTER(VisitCounter, "instcombine-visit", "Controls which instructions are visited")
bool isUnconditional() const
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
void initializeInstructionCombiningPassPass(PassRegistry &)
static cl::opt< unsigned > ShouldLowerDbgDeclare("instcombine-lower-dbg-declare", cl::Hidden, cl::init(true))
bool isMinValue() const
Determine if this is the smallest unsigned value.
void setCondition(Value *V)
Value * SimplifyFreezeInst(Value *Op, const SimplifyQuery &Q)
Given an operand for a Freeze, see if we can fold the result.
Analysis pass providing the TargetLibraryInfo.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
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.
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", "Combine redundant instructions", false, false) INITIALIZE_PASS_END(InstructionCombiningPass
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
SmallVector< int, 16 > getShuffleMask() 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 ...
void stable_sort(R &&Range)
A raw_ostream that writes to an std::string.
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
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.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
This file provides internal interfaces used to implement the InstCombine.
void clearSubclassOptionalData()
Clear the optional flags contained in this value.
succ_range successors(Instruction *I)
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
InstCombinePass(bool ExpensiveCombines=true)
void ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII, StoreInst *SI, DIBuilder &Builder)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
Instruction * visitGetElementPtrInst(GetElementPtrInst &GEP)
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Type * getElementType() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
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.
Type * getArrayElementType() const
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
This header defines various interfaces for pass management in LLVM.
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src)
Value * getPointerOperand()
Instruction * visitAllocSite(Instruction &FI)
Value * getRawDest() const
static Constant * get(ArrayRef< Constant *> V)
Type * getElementType() const
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)".
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
bool isStructTy() const
True if this is an instance of StructType.
bool isArrayTy() const
True if this is an instance of ArrayType.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
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)
bool salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableIntrinsic *> Insns)
Implementation of salvageDebugInfo, applying only to instructions in Insns, rather than all debug use...
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property...