112#define DEBUG_TYPE "instcombine"
120 "Number of instruction combining iterations performed");
121STATISTIC(NumOneIteration,
"Number of functions with one iteration");
122STATISTIC(NumTwoIterations,
"Number of functions with two iterations");
123STATISTIC(NumThreeIterations,
"Number of functions with three iterations");
125 "Number of functions with four or more iterations");
129STATISTIC(NumDeadInst ,
"Number of dead inst eliminated");
135 "Controls which instructions are visited");
137void InstCombiner::IRBuilderInstCombineInserter::InsertHelper(
142 IC.AC.registerAssumption(Assume);
143 if (IC.AnnotationMetadataSource)
144 I->copyMetadata(*IC.AnnotationMetadataSource, LLVMContext::MD_annotation);
147std::optional<Instruction *>
150 if (
II.getCalledFunction()->isTargetIntrinsic()) {
151 return TTIForTargetIntrinsicsOnly.instCombineIntrinsic(*
this,
II);
158 bool &KnownBitsComputed) {
160 if (
II.getCalledFunction()->isTargetIntrinsic()) {
161 return TTIForTargetIntrinsicsOnly.simplifyDemandedUseBitsIntrinsic(
162 *
this,
II, DemandedMask,
Known, KnownBitsComputed);
173 if (
II.getCalledFunction()->isTargetIntrinsic()) {
174 return TTIForTargetIntrinsicsOnly.simplifyDemandedVectorEltsIntrinsic(
175 *
this,
II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
185 return TTIForTargetIntrinsicsOnly.isValidAddrSpaceCast(FromAS, ToAS);
195 Builder.SetInsertPoint(Inst);
199 if (Inst && !
GEP->hasAllConstantIndices() &&
200 !
GEP->getSourceElementType()->isIntegerTy(8)) {
202 *Inst, Builder.CreateGEP(Builder.getInt8Ty(),
GEP->getPointerOperand(),
220 Value *Sum =
nullptr;
221 Value *OneUseSum =
nullptr;
222 Value *OneUseBase =
nullptr;
229 IRBuilderBase::InsertPointGuard Guard(
Builder);
231 if (RewriteGEPs && Inst)
235 if (
Offset->getType() != IdxTy)
238 if (
GEP->hasOneUse()) {
243 OneUseBase =
GEP->getPointerOperand();
252 if (RewriteGEPs && Inst &&
253 Offset->getType()->isVectorTy() ==
GEP->getType()->isVectorTy() &&
254 !(
GEP->getSourceElementType()->isIntegerTy(8) &&
259 OneUseBase ? OneUseBase :
GEP->getPointerOperand(),
Offset,
"",
266 OneUseSum = OneUseBase =
nullptr;
270 Sum =
Add(Sum, OneUseSum);
281bool InstCombinerImpl::isDesirableIntType(
unsigned BitWidth)
const {
300bool InstCombinerImpl::shouldChangeType(
unsigned FromWidth,
301 unsigned ToWidth)
const {
302 bool FromLegal = FromWidth == 1 ||
DL.isLegalInteger(FromWidth);
303 bool ToLegal = ToWidth == 1 ||
DL.isLegalInteger(ToWidth);
307 if (ToWidth < FromWidth && isDesirableIntType(ToWidth))
312 if ((FromLegal || isDesirableIntType(FromWidth)) && !ToLegal)
317 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
328bool InstCombinerImpl::shouldChangeType(
Type *From,
Type *To)
const {
336 return shouldChangeType(FromWidth, ToWidth);
346 if (!OBO || !OBO->hasNoSignedWrap())
349 const APInt *BVal, *CVal;
354 bool Overflow =
false;
355 switch (
I.getOpcode()) {
356 case Instruction::Add:
357 (void)BVal->
sadd_ov(*CVal, Overflow);
359 case Instruction::Sub:
360 (void)BVal->
ssub_ov(*CVal, Overflow);
362 case Instruction::Mul:
363 (void)BVal->
smul_ov(*CVal, Overflow);
374 return OBO && OBO->hasNoUnsignedWrap();
379 return OBO && OBO->hasNoSignedWrap();
389 if (!Cast || !Cast->hasOneUse())
393 auto CastOpcode = Cast->getOpcode();
394 if (CastOpcode != Instruction::ZExt)
403 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
418 Type *DestTy =
C1->getType();
429 Cast->dropPoisonGeneratingFlags();
435Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(
Value *Val) {
437 if (IntToPtr &&
DL.getTypeSizeInBits(IntToPtr->getDestTy()) ==
438 DL.getTypeSizeInBits(IntToPtr->getSrcTy())) {
440 Type *CastTy = IntToPtr->getDestTy();
443 PtrToInt->getSrcTy()->getPointerAddressSpace() &&
444 DL.getTypeSizeInBits(PtrToInt->getSrcTy()) ==
445 DL.getTypeSizeInBits(PtrToInt->getDestTy()))
446 return PtrToInt->getOperand(0);
483 if (
I.isCommutative()) {
484 if (
auto Pair = matchSymmetricPair(
I.getOperand(0),
I.getOperand(1))) {
494 if (
I.isAssociative()) {
520 PDI->setIsDisjoint(
false);
525 I.setHasNoUnsignedWrap(IsNUW);
526 I.setHasNoSignedWrap(IsNSW);
556 I.dropPoisonGeneratingFlags();
564 if (
I.isAssociative() &&
I.isCommutative()) {
591 I.dropPoisonGeneratingFlags();
618 I.dropPoisonGeneratingFlags();
654 I.dropPoisonGeneratingFlags();
656 I.setHasNoUnsignedWrap(
true);
674 if (LOp == Instruction::And)
675 return ROp == Instruction::Or || ROp == Instruction::Xor;
678 if (LOp == Instruction::Or)
679 return ROp == Instruction::And;
683 if (LOp == Instruction::Mul)
684 return ROp == Instruction::Add || ROp == Instruction::Sub;
721 assert(
Op &&
"Expected a binary operator");
722 LHS =
Op->getOperand(0);
723 RHS =
Op->getOperand(1);
724 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
729 Instruction::Shl, ConstantInt::get(
Op->getType(), 1),
C);
730 assert(
RHS &&
"Constant folding of immediate constants failed");
731 return Instruction::Mul;
736 if (OtherOp && OtherOp->
getOpcode() == Instruction::AShr &&
739 return Instruction::AShr;
742 return Op->getOpcode();
751 assert(
A &&
B &&
C &&
D &&
"All values must be provided");
754 Value *RetVal =
nullptr;
765 if (
A ==
C || (InnerCommutative &&
A ==
D)) {
774 if (!
V && (
LHS->hasOneUse() ||
RHS->hasOneUse()))
775 V = Builder.CreateBinOp(TopLevelOpcode,
B,
D,
RHS->getName());
777 RetVal = Builder.CreateBinOp(InnerOpcode,
A,
V);
785 if (
B ==
D || (InnerCommutative &&
B ==
C)) {
794 if (!
V && (
LHS->hasOneUse() ||
RHS->hasOneUse()))
795 V = Builder.CreateBinOp(TopLevelOpcode,
A,
C,
LHS->getName());
797 RetVal = Builder.CreateBinOp(InnerOpcode,
V,
B);
812 HasNSW =
I.hasNoSignedWrap();
813 HasNUW =
I.hasNoUnsignedWrap();
816 HasNSW &= LOBO->hasNoSignedWrap();
817 HasNUW &= LOBO->hasNoUnsignedWrap();
821 HasNSW &= ROBO->hasNoSignedWrap();
822 HasNUW &= ROBO->hasNoUnsignedWrap();
825 if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) {
853 unsigned Opc =
I->getOpcode();
854 unsigned ConstIdx = 1;
861 case Instruction::Sub:
864 case Instruction::ICmp:
871 case Instruction::Or:
875 case Instruction::Add:
890 Constant *BitWidthC = ConstantInt::get(Ty, Ty->getScalarSizeInBits());
896 if (!Cmp || !Cmp->isNullValue())
901 bool Consumes =
false;
905 assert(NotOp !=
nullptr &&
906 "Desync between isFreeToInvert and getFreelyInverted");
908 Value *CtpopOfNotOp =
Builder.CreateIntrinsic(Ty, Intrinsic::ctpop, NotOp);
915 case Instruction::Sub:
918 case Instruction::Or:
919 case Instruction::Add:
922 case Instruction::ICmp:
958 auto IsValidBinOpc = [](
unsigned Opc) {
962 case Instruction::And:
963 case Instruction::Or:
964 case Instruction::Xor:
965 case Instruction::Add:
974 auto IsCompletelyDistributable = [](
unsigned BinOpc1,
unsigned BinOpc2,
976 assert(ShOpc != Instruction::AShr);
977 return (BinOpc1 != Instruction::Add && BinOpc2 != Instruction::Add) ||
978 ShOpc == Instruction::Shl;
981 auto GetInvShift = [](
unsigned ShOpc) {
982 assert(ShOpc != Instruction::AShr);
983 return ShOpc == Instruction::LShr ? Instruction::Shl : Instruction::LShr;
986 auto CanDistributeBinops = [&](
unsigned BinOpc1,
unsigned BinOpc2,
990 if (BinOpc1 == Instruction::And)
995 if (!IsCompletelyDistributable(BinOpc1, BinOpc2, ShOpc))
1001 if (BinOpc2 == Instruction::And)
1012 auto MatchBinOp = [&](
unsigned ShOpnum) ->
Instruction * {
1014 Value *
X, *
Y, *ShiftedX, *Mask, *Shift;
1015 if (!
match(
I.getOperand(ShOpnum),
1019 I.getOperand(1 - ShOpnum),
1032 unsigned ShOpc = IY->getOpcode();
1033 if (ShOpc != IX->getOpcode())
1041 unsigned BinOpc = BO2->getOpcode();
1043 if (!IsValidBinOpc(
I.getOpcode()) || !IsValidBinOpc(BinOpc))
1046 if (ShOpc == Instruction::AShr) {
1060 if (BinOpc ==
I.getOpcode() &&
1061 IsCompletelyDistributable(
I.getOpcode(), BinOpc, ShOpc)) {
1076 if (!CanDistributeBinops(
I.getOpcode(), BinOpc, ShOpc, CMask, CShift))
1083 Value *NewBinOp1 =
Builder.CreateBinOp(
I.getOpcode(),
Y, NewBinOp2);
1090 return MatchBinOp(1);
1107 Value *LHS =
I.getOperand(0), *RHS =
I.getOperand(1);
1108 Value *
A, *CondVal, *TrueVal, *FalseVal;
1110 Constant *CastTrueVal, *CastFalseVal;
1112 auto MatchSelectAndCast = [&](
Value *CastOp,
Value *SelectOp) {
1121 if (MatchSelectAndCast(LHS, RHS))
1123 else if (MatchSelectAndCast(RHS, LHS))
1130 auto NewFoldedConst = [&](
bool IsTrueArm,
Value *V) {
1131 bool IsCastOpRHS = (CastOp == RHS);
1132 Value *CastVal = IsTrueArm ? CastFalseVal : CastTrueVal;
1134 return IsCastOpRHS ?
Builder.CreateBinOp(
Opc, V, CastVal)
1141 Value *NewTrueVal = NewFoldedConst(
false, TrueVal);
1143 NewFoldedConst(
true, FalseVal),
"",
nullptr,
SI);
1146 Value *NewTrueVal = NewFoldedConst(
true, TrueVal);
1148 NewFoldedConst(
false, FalseVal),
"",
nullptr,
SI);
1155 Value *LHS =
I.getOperand(0), *RHS =
I.getOperand(1);
1169 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
1198 Value *LHS =
I.getOperand(0), *RHS =
I.getOperand(1);
1215 auto SQDistributive =
SQ.getWithInstruction(&
I).getWithoutUndef();
1223 C =
Builder.CreateBinOp(InnerOpcode, L, R);
1232 C =
Builder.CreateBinOp(TopLevelOpcode,
B,
C);
1241 C =
Builder.CreateBinOp(TopLevelOpcode,
A,
C);
1254 auto SQDistributive =
SQ.getWithInstruction(&
I).getWithoutUndef();
1262 A =
Builder.CreateBinOp(InnerOpcode, L, R);
1271 A =
Builder.CreateBinOp(TopLevelOpcode,
A,
C);
1280 A =
Builder.CreateBinOp(TopLevelOpcode,
A,
B);
1289static std::optional<std::pair<Value *, Value *>>
1291 if (
LHS->getParent() !=
RHS->getParent())
1292 return std::nullopt;
1294 if (
LHS->getNumIncomingValues() < 2)
1295 return std::nullopt;
1298 return std::nullopt;
1300 Value *L0 =
LHS->getIncomingValue(0);
1301 Value *R0 =
RHS->getIncomingValue(0);
1303 for (
unsigned I = 1,
E =
LHS->getNumIncomingValues();
I !=
E; ++
I) {
1307 if ((L0 == L1 && R0 == R1) || (L0 == R1 && R0 == L1))
1310 return std::nullopt;
1313 return std::optional(std::pair(L0, R0));
1316std::optional<std::pair<Value *, Value *>>
1321 return std::nullopt;
1323 case Instruction::PHI:
1325 case Instruction::Select: {
1331 return std::pair(TrueVal, FalseVal);
1332 return std::nullopt;
1334 case Instruction::Call: {
1338 if (LHSMinMax && RHSMinMax &&
1345 return std::pair(LHSMinMax->
getLHS(), LHSMinMax->
getRHS());
1346 return std::nullopt;
1349 return std::nullopt;
1357 "OuterOp must be commutative and associative");
1359 "OuterOp and InnerOp must have same opcode");
1363 unsigned OuterValIdx = OuterOp.
getOperand(0) == OuterVal ? 0 : 1;
1365 "OuterVal must be an operand of OuterOp");
1367 auto Pair = matchSymmetricPair(InnerVal1, OuterVal);
1398 bool CondIsTrue) ->
Value * {
1400 if (!InnerSI ||
Cond->getType() != InnerSI->getCondition()->getType())
1411 Value *OtherT = SimplifySelectWithImpliedCond(
Other,
Cond,
true);
1412 Value *OtherF = SimplifySelectWithImpliedCond(
Other,
Cond,
false);
1413 Value *LHSTrueArm = TVal, *RHSTrueArm = OtherT;
1414 Value *LHSFalseArm = FVal, *RHSFalseArm = OtherF;
1423 if (!
Other->hasOneUse())
1438 if (!LHSIsSelect && !RHSIsSelect)
1446 FMF = FPOp->getFastMathFlags();
1447 Builder.setFastMathFlags(FMF);
1475 if (LHSIsSelect && RHSIsSelect &&
A ==
D) {
1481 if (LHS->hasOneUse() && RHS->hasOneUse()) {
1489 if (LHSIsSelect && LHS->hasOneUse()) {
1493 if (
Value *NewSel = foldAddNegate(
B,
C, RHS))
1498 if (!
Folded && RHSIsSelect && RHS->hasOneUse()) {
1504 if (
Value *NewSel = foldAddNegate(E,
F, LHS))
1522 if (U == IgnoredUser)
1525 case Instruction::Select: {
1528 SI->swapProfMetadata();
1531 case Instruction::CondBr: {
1538 case Instruction::Xor:
1545 "canFreelyInvertAllUsersOf() ?");
1555 for (
unsigned Idx = 0,
End = DbgVal->getNumVariableLocationOps();
1557 if (DbgVal->getVariableLocationOp(Idx) ==
I)
1558 DbgVal->setExpression(
1565Value *InstCombinerImpl::dyn_castNegVal(
Value *V)
const {
1575 if (
C->getType()->getElementType()->isIntegerTy())
1579 for (
unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1595 if (CV->getType()->isVectorTy() &&
1596 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
1609Instruction *InstCombinerImpl::foldFBinOpOfIntCastsFromSign(
1610 BinaryOperator &BO,
bool OpsFromSigned, std::array<Value *, 2> IntOps,
1614 Type *IntTy = IntOps[0]->getType();
1619 unsigned MaxRepresentableBits =
1624 unsigned NumUsedLeadingBits[2] = {IntSz, IntSz};
1628 auto IsNonZero = [&](
unsigned OpNo) ->
bool {
1629 if (OpsKnown[OpNo].hasKnownBits() &&
1630 OpsKnown[OpNo].getKnownBits(
SQ).isNonZero())
1635 auto IsNonNeg = [&](
unsigned OpNo) ->
bool {
1639 return OpsKnown[OpNo].getKnownBits(
SQ).isNonNegative();
1643 auto IsValidPromotion = [&](
unsigned OpNo) ->
bool {
1654 if (MaxRepresentableBits < IntSz) {
1664 NumUsedLeadingBits[OpNo] =
1665 IntSz - OpsKnown[OpNo].getKnownBits(
SQ).countMinLeadingZeros();
1673 if (MaxRepresentableBits < NumUsedLeadingBits[OpNo])
1676 return !OpsFromSigned || BO.
getOpcode() != Instruction::FMul ||
1681 if (Op1FpC !=
nullptr) {
1683 if (OpsFromSigned && BO.
getOpcode() == Instruction::FMul &&
1688 OpsFromSigned ? Instruction::FPToSI : Instruction::FPToUI, Op1FpC,
1690 if (Op1IntC ==
nullptr)
1693 : Instruction::UIToFP,
1694 Op1IntC, FPTy,
DL) != Op1FpC)
1698 IntOps[1] = Op1IntC;
1702 if (IntTy != IntOps[1]->
getType())
1705 if (Op1FpC ==
nullptr) {
1706 if (!IsValidPromotion(1))
1709 if (!IsValidPromotion(0))
1715 bool NeedsOverflowCheck =
true;
1718 unsigned OverflowMaxOutputBits = OpsFromSigned ? 2 : 1;
1719 unsigned OverflowMaxCurBits =
1720 std::max(NumUsedLeadingBits[0], NumUsedLeadingBits[1]);
1721 bool OutputSigned = OpsFromSigned;
1723 case Instruction::FAdd:
1724 IntOpc = Instruction::Add;
1725 OverflowMaxOutputBits += OverflowMaxCurBits;
1727 case Instruction::FSub:
1728 IntOpc = Instruction::Sub;
1729 OverflowMaxOutputBits += OverflowMaxCurBits;
1731 case Instruction::FMul:
1732 IntOpc = Instruction::Mul;
1733 OverflowMaxOutputBits += OverflowMaxCurBits * 2;
1739 if (OverflowMaxOutputBits < IntSz) {
1740 NeedsOverflowCheck =
false;
1743 if (IntOpc == Instruction::Sub)
1744 OutputSigned =
true;
1750 if (NeedsOverflowCheck &&
1751 !willNotOverflow(IntOpc, IntOps[0], IntOps[1], BO, OutputSigned))
1754 Value *IntBinOp =
Builder.CreateBinOp(IntOpc, IntOps[0], IntOps[1]);
1756 IntBO->setHasNoSignedWrap(OutputSigned);
1757 IntBO->setHasNoUnsignedWrap(!OutputSigned);
1760 return new SIToFPInst(IntBinOp, FPTy);
1761 return new UIToFPInst(IntBinOp, FPTy);
1775 std::array<Value *, 2> IntOps = {
nullptr,
nullptr};
1793 if (Instruction *R = foldFBinOpOfIntCastsFromSign(BO,
false,
1794 IntOps, Op1FpC, OpsKnown))
1796 return foldFBinOpOfIntCastsFromSign(BO,
true, IntOps,
1812 !
X->getType()->isIntOrIntVectorTy(1))
1820 return createSelectInstWithUnknownProfile(
X, TVal, FVal);
1829 V = IsTrueArm ?
SI->getTrueValue() :
SI->getFalseValue();
1830 }
else if (
match(
SI->getCondition(),
1837 V = IsTrueArm ? ConstantInt::get(
Op->getType(), 1)
1858 bool FoldWithMultiUse,
1859 bool SimplifyBothArms) {
1861 if (!
SI->hasOneUser() && !FoldWithMultiUse)
1864 Value *TV =
SI->getTrueValue();
1865 Value *FV =
SI->getFalseValue();
1868 if (
SI->getType()->isIntOrIntVectorTy(1))
1874 for (
Value *IntrinOp :
Op.operands())
1876 for (
Value *PhiOp : PN->operands())
1888 if (CI->hasOneUse()) {
1889 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1890 if (((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1)) &&
1891 !CI->isCommutative())
1900 if (!NewTV && !NewFV)
1903 if (SimplifyBothArms && !(NewTV && NewFV))
1917 {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
1918 LLVMContext::MD_dbg});
1932 Ops.push_back(InValue);
1972 assert(
Op.isAssociative() &&
"The operation must be associative!");
1978 !
Op.hasOneUse() || !
SI->hasOneUse())
1981 Value *TV =
SI->getTrueValue();
1982 Value *FV =
SI->getFalseValue();
2000 if (!NewTV || !NewFV)
2003 Value *NewSI =
Builder.CreateSelect(
SI->getCondition(), NewTV, NewFV,
"",
SI);
2008 bool AllowMultipleUses) {
2010 if (NumPHIValues == 0)
2017 bool IdenticalUsers =
false;
2018 if (!AllowMultipleUses && !OneUse) {
2022 if (UI != &
I && !
I.isIdenticalTo(UI))
2026 IdenticalUsers =
true;
2056 bool SeenNonSimplifiedInVal =
false;
2057 for (
unsigned i = 0; i != NumPHIValues; ++i) {
2068 auto WillFold = [&]() {
2073 const APInt *Ignored;
2094 if (!OneUse && !IdenticalUsers)
2097 if (SeenNonSimplifiedInVal)
2099 SeenNonSimplifiedInVal =
true;
2107 if (!BI || !
DT.isReachableFromEntry(InBB))
2123 for (
auto OpIndex : OpsToMoveUseToIncomingBB) {
2134 U = U->DoPHITranslation(PN->
getParent(), OpBB);
2137 Clones.
insert({OpBB, Clone});
2142 NewPhiValues[OpIndex] = Clone;
2151 for (
unsigned i = 0; i != NumPHIValues; ++i)
2154 if (IdenticalUsers) {
2185 BO0->getOpcode() !=
Opc || BO1->getOpcode() !=
Opc ||
2186 !BO0->isAssociative() || !BO1->isAssociative() ||
2187 BO0->getParent() != BO1->getParent())
2191 "Expected commutative instructions!");
2195 Value *Start0, *Step0, *Start1, *Step1;
2202 "Expected PHIs with two incoming values!");
2209 if (!Init0 || !Init1 || !
C0 || !
C1)
2224 if (
Opc == Instruction::FAdd ||
Opc == Instruction::FMul) {
2228 NewBO->setFastMathFlags(Intersect);
2232 Flags.AllKnownNonZero =
false;
2233 Flags.mergeFlags(*BO0);
2234 Flags.mergeFlags(*BO1);
2235 Flags.mergeFlags(BO);
2236 Flags.applyFlags(*NewBO);
2238 NewBO->takeName(&BO);
2248 "Invalid incoming block!");
2249 NewPN->addIncoming(
Init, BB);
2250 }
else if (V == BO0) {
2255 "Invalid incoming block!");
2256 NewPN->addIncoming(NewBO, BB);
2262 <<
"\n with " << *PN1 <<
"\n " << *BO1
2289 if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||
2290 Phi0->getNumOperands() != Phi1->getNumOperands())
2294 if (BO.
getParent() != Phi0->getParent() ||
2311 auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &>
T) {
2312 auto &Phi0Use = std::get<0>(
T);
2313 auto &Phi1Use = std::get<1>(
T);
2314 if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use))
2316 Value *Phi0UseV = Phi0Use.get();
2317 Value *Phi1UseV = Phi1Use.get();
2320 else if (Phi1UseV ==
C)
2327 if (
all_of(
zip(Phi0->operands(), Phi1->operands()),
2328 CanFoldIncomingValuePair)) {
2331 assert(NewIncomingValues.
size() == Phi0->getNumOperands() &&
2332 "The number of collected incoming values should equal the number "
2333 "of the original PHINode operands!");
2334 for (
unsigned I = 0;
I < Phi0->getNumOperands();
I++)
2335 NewPhi->
addIncoming(NewIncomingValues[
I], Phi0->getIncomingBlock(
I));
2340 if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)
2347 ConstBB = Phi0->getIncomingBlock(0);
2348 OtherBB = Phi0->getIncomingBlock(1);
2350 ConstBB = Phi0->getIncomingBlock(1);
2351 OtherBB = Phi0->getIncomingBlock(0);
2362 if (!PredBlockBranch || !
DT.isReachableFromEntry(OtherBB))
2368 for (
auto BBIter = BO.
getParent()->begin(); &*BBIter != &BO; ++BBIter)
2379 Builder.SetInsertPoint(PredBlockBranch);
2381 Phi0->getIncomingValueForBlock(OtherBB),
2382 Phi1->getIncomingValueForBlock(OtherBB));
2384 NotFoldedNewBO->copyIRFlags(&BO);
2394 auto TryFoldOperand = [&](
unsigned OpIdx,
2413 if (
GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
2444 for (
unsigned I = 0;
I < NumElts; ++
I) {
2446 if (ShMask[
I] >= 0) {
2447 int MaskElt = ShMask[
I];
2448 if (MaskElt >= (
int)NewCNumElts)
2451 Constant *NewCElt = NewVecC[MaskElt];
2461 NewVecC[MaskElt] = CElt;
2479template <Intrinsic::ID SpliceID>
2498 (
LHS->hasOneUse() ||
RHS->hasOneUse() ||
2500 return CreateBinOpSplice(
V1, V2,
Offset);
2512 return CreateBinOpSplice(
LHS, V2,
Offset);
2532 auto foldConstantsThroughSubVectorInsertSplat =
2533 [&](
Value *MaybeSubVector,
Value *MaybeSplat,
2538 !
match(MaybeSubVector,
2545 if (!SubVector || !Dest)
2547 auto *InsertVector =
2548 Builder.CreateInsertVector(Dest->
getType(), Dest, SubVector, Idx);
2569 M, Intrinsic::vector_reverse, V->getType());
2580 (LHS->hasOneUse() || RHS->hasOneUse() ||
2581 (LHS == RHS && LHS->hasNUses(2))))
2582 return createBinOpReverse(
V1, V2);
2586 return createBinOpReverse(
V1, RHS);
2590 return createBinOpReverse(LHS, V2);
2601 M, Intrinsic::experimental_vp_reverse, V->getType());
2611 (LHS->hasOneUse() || RHS->hasOneUse() ||
2612 (LHS == RHS && LHS->hasNUses(2))))
2613 return createBinOpVPReverse(
V1, V2, EVL);
2617 return createBinOpVPReverse(
V1, RHS, EVL);
2623 return createBinOpVPReverse(LHS, V2, EVL);
2651 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
2653 return createBinOpShuffle(
V1, V2, Mask);
2668 if (LShuf->isSelect() &&
2670 RShuf->isSelect() &&
2692 "Shuffle should not change scalar type");
2704 Value *NewLHS = ConstOp1 ?
V1 : NewC;
2705 Value *NewRHS = ConstOp1 ? NewC :
V1;
2706 return createBinOpShuffle(NewLHS, NewRHS, Mask);
2741 Value *NewSplat =
Builder.CreateShuffleVector(NewBO, NewMask);
2747 R->copyFastMathFlags(&Inst);
2751 NewInstBO->copyIRFlags(R);
2781 (Op0->
hasOneUse() || Op1->hasOneUse()))) {
2799 if (!willNotOverflow(BO.
getOpcode(),
X,
Y, BO, IsSext))
2807 NewBinOp->setHasNoSignedWrap();
2809 NewBinOp->setHasNoUnsignedWrap();
2825 if (!
GEP.hasAllConstantIndices())
2841 Type *Ty =
GEP.getSourceElementType();
2842 Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC,
"", NW);
2843 Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC,
"", NW);
2853 if (
GEP.getNumIndices() != 1)
2863 unsigned IndexSizeInBits =
DL.getIndexTypeSizeInBits(PtrTy);
2873 if (NewOffset.
isZero() ||
2874 (Src->hasOneUse() &&
GEP.getOperand(1)->hasOneUse())) {
2876 if (
GEP.hasNoUnsignedWrap() &&
2896 if (!
GEP.hasAllConstantIndices())
2907 if (InnerGEP->hasAllConstantIndices())
2910 if (!InnerGEP->hasOneUse())
2913 Skipped.push_back(InnerGEP);
2919 if (Skipped.empty())
2924 if (!InnerGEP->hasOneUse())
2929 if (InnerGEP->getType() != Ty)
2935 !InnerGEP->accumulateConstantOffset(
DL,
Offset))
2938 IC.
replaceOperand(*Skipped.back(), 0, InnerGEP->getPointerOperand());
2940 SkippedGEP->setNoWrapFlags(NW);
2962 if (Src->getResultElementType() !=
GEP.getSourceElementType())
2968 if (Src->hasOneUse() &&
GEP.getNumIndices() == 1 &&
2969 Src->getNumIndices() == 1) {
2970 Value *SrcIdx = *Src->idx_begin();
2972 const APInt *ConstOffset, *TrueVal, *FalseVal;
2985 if (!
Select->hasOneUse())
2988 if (TrueVal->getBitWidth() != ConstOffset->
getBitWidth() ||
2989 FalseVal->getBitWidth() != ConstOffset->
getBitWidth())
2992 APInt NewTrueVal = *ConstOffset + *TrueVal;
2993 APInt NewFalseVal = *ConstOffset + *FalseVal;
2994 Constant *NewTrue = ConstantInt::get(
Select->getType(), NewTrueVal);
2995 Constant *NewFalse = ConstantInt::get(
Select->getType(), NewFalseVal);
3002 Builder.CreateGEP(
GEP.getResultElementType(),
3003 Src->getPointerOperand(),
3004 NewSelect,
"", Flags));
3009 bool EndsWithSequential =
false;
3012 EndsWithSequential =
I.isSequential();
3013 if (!EndsWithSequential)
3018 Value *SO1 = Src->getOperand(Src->getNumOperands() - 1);
3036 Indices.
append(Src->op_begin() + 1, Src->op_end() - 1);
3041 unsigned NumNonZeroIndices =
count_if(Indices, [](
Value *Idx) {
3043 return !
C || !
C->isNullValue();
3045 if (NumNonZeroIndices > 1)
3050 Src->getSourceElementType(), Src->getOperand(0), Indices,
"",
3056 bool &DoesConsume,
unsigned Depth) {
3075 if (!WillInvertAllUses)
3082 return Builder->CreateCmp(
I->getInversePredicate(),
I->getOperand(0),
3091 DoesConsume,
Depth))
3094 DoesConsume,
Depth))
3103 DoesConsume,
Depth))
3106 DoesConsume,
Depth))
3115 DoesConsume,
Depth))
3124 DoesConsume,
Depth))
3136 bool LocalDoesConsume = DoesConsume;
3138 LocalDoesConsume,
Depth))
3141 LocalDoesConsume,
Depth)) {
3142 DoesConsume = LocalDoesConsume;
3145 DoesConsume,
Depth);
3146 assert(NotB !=
nullptr &&
3147 "Unable to build inverted value for known freely invertable op");
3149 return Builder->CreateBinaryIntrinsic(
3151 return Builder->CreateSelect(
Cond, NotA, NotB,
"",
3159 bool LocalDoesConsume = DoesConsume;
3161 for (
Use &U : PN->operands()) {
3162 BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
3166 if (NewIncomingVal ==
nullptr)
3169 if (NewIncomingVal == V)
3172 IncomingValues.
emplace_back(NewIncomingVal, IncomingBlock);
3175 DoesConsume = LocalDoesConsume;
3180 Builder->CreatePHI(PN->getType(), PN->getNumIncomingValues());
3181 for (
auto [Val, Pred] : IncomingValues)
3190 DoesConsume,
Depth))
3191 return Builder ?
Builder->CreateSExt(AV, V->getType()) : NonNull;
3197 DoesConsume,
Depth))
3198 return Builder ?
Builder->CreateTrunc(AV, V->getType()) : NonNull;
3206 bool IsLogical,
Value *
A,
3208 bool LocalDoesConsume = DoesConsume;
3210 LocalDoesConsume,
Depth))
3213 LocalDoesConsume,
Depth)) {
3215 LocalDoesConsume,
Depth);
3216 DoesConsume = LocalDoesConsume;
3221 Opcode, NotA, NotB,
"",
3224 SI->swapProfMetadata();
3225 return InvertedLogicalOp;
3227 return Builder->CreateBinOp(Opcode, NotA, NotB);
3234 return TryInvertAndOrUsingDeMorgan(Instruction::And,
false,
A,
3238 return TryInvertAndOrUsingDeMorgan(Instruction::Or,
false,
A,
3242 return TryInvertAndOrUsingDeMorgan(Instruction::And,
true,
A,
3246 return TryInvertAndOrUsingDeMorgan(Instruction::Or,
true,
A,
3255 Type *GEPEltType =
GEP.getSourceElementType();
3266 if (
GEP.getNumIndices() == 1 &&
3275 return PtrOpGep && PtrOpGep->hasAllConstantIndices() &&
3278 return match(V, m_APInt(C)) && !C->isZero();
3302 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||
3303 Op1->getSourceElementType() != Op2->getSourceElementType())
3311 Type *CurTy =
nullptr;
3313 for (
unsigned J = 0,
F = Op1->getNumOperands(); J !=
F; ++J) {
3314 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
3317 if (Op1->getOperand(J) != Op2->getOperand(J)) {
3326 assert(CurTy &&
"No current type?");
3346 CurTy = Op1->getSourceElementType();
3354 NW &= Op2->getNoWrapFlags();
3364 NewGEP->setNoWrapFlags(NW);
3376 Builder.SetInsertPoint(PN);
3377 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
3385 NewGEP->setOperand(DI, NewPN);
3388 NewGEP->insertBefore(*
GEP.getParent(),
GEP.getParent()->getFirstInsertionPt());
3395 Type *GEPType =
GEP.getType();
3396 Type *GEPEltType =
GEP.getSourceElementType();
3399 SQ.getWithInstruction(&
GEP)))
3406 auto VWidth = GEPFVTy->getNumElements();
3407 APInt PoisonElts(VWidth, 0);
3419 bool MadeChange =
false;
3423 Type *NewScalarIndexTy =
3424 DL.getIndexType(
GEP.getPointerOperandType()->getScalarType());
3433 Type *IndexTy = (*I)->getType();
3434 Type *NewIndexType =
3443 if (EltTy->
isSized() &&
DL.getTypeAllocSize(EltTy).isZero())
3449 if (IndexTy != NewIndexType) {
3455 if (
GEP.hasNoUnsignedWrap() &&
GEP.hasNoUnsignedSignedWrap())
3456 *
I =
Builder.CreateZExt(*
I, NewIndexType,
"",
true);
3458 *
I =
Builder.CreateSExt(*
I, NewIndexType);
3460 *
I =
Builder.CreateTrunc(*
I, NewIndexType,
"",
GEP.hasNoUnsignedWrap(),
3461 GEP.hasNoUnsignedSignedWrap());
3470 if (!GEPEltType->
isIntegerTy(8) &&
GEP.hasAllConstantIndices()) {
3475 GEP.getNoWrapFlags()));
3487 auto IsCanonicalType = [](
Type *Ty) {
3489 Ty = AT->getElementType();
3490 return Ty->isIntegerTy(8);
3492 if (!IsCanonicalType(GEPEltType) || Indices.
size() != 1)
3494 Builder.CreateGEP(GEPEltType, PtrOp, Indices,
"",
3495 GEP.getNoWrapFlags()));
3501 return Op->getType()->isVectorTy() && getSplatValue(Op);
3504 for (
auto &
Op :
GEP.operands()) {
3505 if (
Op->getType()->isVectorTy())
3515 GEP.getNoWrapFlags());
3518 Res =
Builder.CreateVectorSplat(EC, Res);
3533 if (
GEP.getNumIndices() == 1) {
3534 unsigned AS =
GEP.getPointerAddressSpace();
3535 if (
GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
3536 DL.getIndexSizeInBits(AS)) {
3537 uint64_t TyAllocSize =
DL.getTypeAllocSize(GEPEltType).getFixedValue();
3539 if (TyAllocSize == 1) {
3548 GEPType ==
Y->getType()) {
3549 bool HasNonAddressBits =
3550 DL.getAddressSizeInBits(AS) !=
DL.getPointerSizeInBits(AS);
3557 }
else if (
auto *ExactIns =
3561 if (ExactIns->isExact()) {
3569 GEP.getPointerOperand(), V,
3570 GEP.getNoWrapFlags());
3573 if (ExactIns->isExact() && ExactIns->hasOneUse()) {
3579 std::optional<APInt> NewC;
3599 if (NewC.has_value()) {
3602 ConstantInt::get(V->getType(), *NewC),
true);
3604 GEP.getPointerOperand(), NewOp,
3605 GEP.getNoWrapFlags());
3615 if (!
GEP.isInBounds()) {
3618 APInt BasePtrOffset(IdxWidth, 0);
3619 Value *UnderlyingPtrOp =
3623 DL, CanBeNull,
nullptr);
3626 if (!CanBeNull && DerefBytes != 0) {
3627 if (
GEP.accumulateConstantOffset(
DL, BasePtrOffset) &&
3629 APInt AllocSize(IdxWidth, DerefBytes);
3630 if (BasePtrOffset.
ule(AllocSize)) {
3632 GEP.getSourceElementType(), PtrOp, Indices,
GEP.getName());
3639 if (
GEP.hasNoUnsignedSignedWrap() && !
GEP.hasNoUnsignedWrap() &&
3641 return isKnownNonNegative(Idx, SQ.getWithInstruction(&GEP));
3649 if (
GEP.getNumIndices() == 1) {
3652 auto GetPreservedNoWrapFlags = [&](
bool AddIsNUW) {
3655 if (
GEP.hasNoUnsignedWrap() && AddIsNUW)
3656 return GEP.getNoWrapFlags();
3672 Builder.CreateGEP(
GEP.getSourceElementType(),
GEP.getPointerOperand(),
3675 Builder.CreateGEP(
GEP.getSourceElementType(),
3676 NewPtr, Idx2,
"", NWFlags));
3687 bool NUW =
match(
GEP.getOperand(1),
3690 auto *NewPtr =
Builder.CreateGEP(
3691 GEP.getSourceElementType(),
GEP.getPointerOperand(),
3692 Builder.CreateSExt(Idx1,
GEP.getOperand(1)->getType()),
"", NWFlags);
3695 Builder.CreateGEP(
GEP.getSourceElementType(), NewPtr,
3696 Builder.CreateSExt(
C,
GEP.getOperand(1)->getType()),
3705 if (Indices.
size() == 1 &&
GEP.isInBounds() &&
GEP.hasNoUnsignedWrap()) {
3719 GEP.getNoWrapFlags());
3755 return Dest && Dest->Ptr == UsedV;
3758static std::optional<ModRefInfo>
3761 unsigned MaxUsers) {
3771 if (
Users.size() >= MaxUsers)
3772 return std::nullopt;
3773 switch (
I->getOpcode()) {
3776 return std::nullopt;
3778 case Instruction::AddrSpaceCast:
3779 case Instruction::BitCast:
3780 case Instruction::GetElementPtr:
3785 case Instruction::ICmp: {
3791 return std::nullopt;
3792 unsigned OtherIndex = (ICI->
getOperand(0) == PI) ? 1 : 0;
3794 return std::nullopt;
3799 auto AlignmentAndSizeKnownValid = [](
CallBase *CB) {
3803 const APInt *Alignment;
3805 return match(CB->getArgOperand(0),
m_APInt(Alignment)) &&
3807 Alignment->isPowerOf2() &&
Size->urem(*Alignment).isZero();
3811 TLI.getLibFunc(*CB->getCalledFunction()) == LibFunc_aligned_alloc &&
3812 TLI.has(LibFunc_aligned_alloc) && !AlignmentAndSizeKnownValid(CB))
3813 return std::nullopt;
3818 case Instruction::Call:
3821 switch (
II->getIntrinsicID()) {
3823 return std::nullopt;
3825 case Intrinsic::memmove:
3826 case Intrinsic::memcpy:
3827 case Intrinsic::memset: {
3829 if (
MI->isVolatile())
3830 return std::nullopt;
3836 return std::nullopt;
3840 case Intrinsic::assume:
3841 case Intrinsic::invariant_start:
3842 case Intrinsic::invariant_end:
3843 case Intrinsic::lifetime_start:
3844 case Intrinsic::lifetime_end:
3845 case Intrinsic::objectsize:
3848 case Intrinsic::launder_invariant_group:
3875 return std::nullopt;
3877 case Instruction::Store: {
3879 if (
SI->isVolatile() ||
SI->getPointerOperand() != PI)
3880 return std::nullopt;
3882 return std::nullopt;
3888 case Instruction::Load: {
3891 return std::nullopt;
3893 return std::nullopt;
3901 }
while (!Worklist.
empty());
3929 std::unique_ptr<DIBuilder> DIB;
3937 bool KnowInitUndef =
false;
3938 bool KnowInitZero =
false;
3943 KnowInitUndef =
true;
3944 else if (
Init->isNullValue())
3945 KnowInitZero =
true;
3949 auto &
F = *
MI.getFunction();
3950 if (
F.hasFnAttribute(Attribute::SanitizeMemory) ||
3951 F.hasFnAttribute(Attribute::SanitizeAddress))
3952 KnowInitUndef =
false;
3956 CLOpts.max_allocsite_removable_users);
3968 if (
II->getIntrinsicID() == Intrinsic::objectsize) {
3971 II,
DL, &
TLI,
AA,
true, &InsertedInstructions);
3972 for (
Instruction *Inserted : InsertedInstructions)
3980 if (KnowInitZero &&
isRefSet(*Removable)) {
3983 auto *M =
Builder.CreateMemSet(
3986 MTI->getLength(), MTI->getDestAlign());
3987 M->copyMetadata(*MTI);
4000 *
C, ConstantInt::get(
C->getType(),
C->isFalseWhenEqual()));
4002 for (
auto *DVR : DVRs)
4003 if (DVR->isAddressOfVariable())
4010 assert(KnowInitZero || KnowInitUndef);
4025 F,
II->getNormalDest(),
II->getUnwindDest(), {},
"",
II->getParent());
4026 NewII->setDebugLoc(
II->getDebugLoc());
4054 for (
auto *DVR : DVRs)
4055 if (DVR->isAddressOfVariable() || DVR->getExpression()->startsWithDeref())
4056 DVR->eraseFromParent();
4102 if (FreeInstrBB->
size() != 2) {
4104 if (&Inst == &FI || &Inst == FreeInstrBBTerminator ||
4108 if (!Cast || !Cast->isNoopCast(
DL))
4129 "Broken CFG: missing edge from predecessor to successor");
4134 if (&Instr == FreeInstrBBTerminator)
4139 "Only the branch instruction should remain");
4150 Attrs = Attrs.removeParamAttribute(FI.
getContext(), 0, Attribute::NonNull);
4151 Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable);
4152 if (Dereferenceable.
isValid()) {
4154 Attrs = Attrs.removeParamAttribute(FI.
getContext(), 0,
4155 Attribute::Dereferenceable);
4156 Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.
getContext(), 0, Bytes);
4194 if (
TLI.getLibFunc(FI) == LibFunc_free &&
TLI.has(LibFunc_free))
4210 bool UseProvenance =
4211 F->getAttributes().getRetDereferenceableBytes() > 0 &&
4213 if (
F->hasRetAttribute(Attribute::NonNull) || UseProvenance) {
4214 if (
Value *V = simplifyNonNullOperand(RetVal, UseProvenance))
4219 if (!AttributeFuncs::isNoFPClassCompatibleType(RetTy))
4222 FPClassTest ReturnClass =
F->getAttributes().getRetNoFPClass();
4223 if (ReturnClass ==
fcNone)
4228 SQ.getWithInstruction(&RI)))
4245 if (Prev->isEHPad())
4275 if (BBI != FirstInstr)
4291 if (!
DeadEdges.insert({From, To}).second)
4296 for (
Use &U : PN.incoming_values())
4313 std::next(
I->getReverseIterator())))) {
4314 if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) {
4318 if (Inst.isEHPad() || Inst.getType()->isTokenTy())
4321 Inst.dropDbgRecords();
4343 return DeadEdges.contains({Pred, BB}) ||
DT.dominates(BB, Pred);
4356 if (Succ == LiveSucc)
4392 assert(Weights.
size() == 2 &&
"Unexpected number of branch weights!");
4439 if (
DT.dominates(Edge0, U)) {
4445 if (
DT.dominates(Edge1, U)) {
4452 DC.registerBranch(&BI);
4462 unsigned CstOpIdx = IsTrueArm ? 1 : 2;
4467 BasicBlock *CstBB =
SI.findCaseValue(
C)->getCaseSuccessor();
4468 if (CstBB !=
SI.getDefaultDest())
4481 for (
auto Case :
SI.cases())
4482 if (!CR.
contains(Case.getCaseValue()->getValue()))
4491 const APInt *CondOpC;
4494 auto MaybeInvertible = [&](
Value *
Cond) -> InvertFn {
4497 return [](
const APInt &Case,
const APInt &
C) {
return Case -
C; };
4501 return [](
const APInt &Case,
const APInt &
C) {
return C - Case; };
4507 return [](
const APInt &Case,
const APInt &
C) {
return Case ^
C; };
4514 if (
auto InvertFn = MaybeInvertible(
Cond); InvertFn &&
Cond->hasOneUse()) {
4515 for (
auto &Case :
SI.cases()) {
4516 const APInt &New = InvertFn(Case.getCaseValue()->getValue(), *CondOpC);
4517 Case.setValue(ConstantInt::get(
SI.getContext(), New));
4525 all_of(
SI.cases(), [&](
const auto &Case) {
4526 return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt;
4532 Value *NewCond = Op0;
4539 for (
auto Case :
SI.cases()) {
4540 const APInt &CaseVal = Case.getCaseValue()->getValue();
4542 : CaseVal.
lshr(ShiftAmt);
4543 Case.setValue(ConstantInt::get(
SI.getContext(), ShiftedCase));
4555 if (
all_of(
SI.cases(), [&](
const auto &Case) {
4556 const APInt &CaseVal = Case.getCaseValue()->getValue();
4557 return IsZExt ? CaseVal.isIntN(NewWidth)
4558 : CaseVal.isSignedIntN(NewWidth);
4560 for (
auto &Case :
SI.cases()) {
4561 APInt TruncatedCase = Case.getCaseValue()->getValue().
trunc(NewWidth);
4562 Case.setValue(ConstantInt::get(
SI.getContext(), TruncatedCase));
4579 unsigned LeadingKnownZeros =
Known.countMinLeadingZeros();
4580 unsigned LeadingKnownOnes =
Known.countMinLeadingOnes();
4584 for (
const auto &
C :
SI.cases()) {
4586 std::min(LeadingKnownZeros,
C.getCaseValue()->getValue().countl_zero());
4588 std::min(LeadingKnownOnes,
C.getCaseValue()->getValue().countl_one());
4591 unsigned NewWidth =
Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
4597 if (NewWidth > 0 && NewWidth <
Known.getBitWidth() &&
4598 shouldChangeType(
Known.getBitWidth(), NewWidth)) {
4603 for (
auto Case :
SI.cases()) {
4604 APInt TruncatedCase = Case.getCaseValue()->getValue().
trunc(NewWidth);
4605 Case.setValue(ConstantInt::get(
SI.getContext(), TruncatedCase));
4616 SI.findCaseValue(CI)->getCaseSuccessor());
4630 const APInt *
C =
nullptr;
4632 if (*EV.
idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||
4633 OvID == Intrinsic::umul_with_overflow)) {
4638 if (
C->isPowerOf2()) {
4639 return BinaryOperator::CreateShl(
4641 ConstantInt::get(WO->getLHS()->getType(),
C->logBase2()));
4649 if (!WO->hasOneUse())
4663 assert(*EV.
idx_begin() == 1 &&
"Unexpected extract index for overflow inst");
4666 if (OvID == Intrinsic::usub_with_overflow)
4671 if (OvID == Intrinsic::smul_with_overflow &&
4672 WO->getLHS()->getType()->isIntOrIntVectorTy(1))
4673 return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS());
4676 if (OvID == Intrinsic::umul_with_overflow && WO->getLHS() == WO->getRHS()) {
4677 unsigned BitWidth = WO->getLHS()->getType()->getScalarSizeInBits();
4680 return new ICmpInst(
4682 ConstantInt::get(WO->getLHS()->getType(),
4693 WO->getBinaryOp(), *
C, WO->getNoWrapKind());
4698 auto *OpTy = WO->getRHS()->getType();
4699 auto *NewLHS = WO->getLHS();
4701 NewLHS =
Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy,
Offset));
4703 ConstantInt::get(OpTy, NewRHSC));
4720 const APFloat *ConstVal =
nullptr;
4721 Value *VarOp =
nullptr;
4722 bool ConstIsTrue =
false;
4729 ConstIsTrue =
false;
4734 Builder.SetInsertPoint(&EV);
4740 Value *NewEV = Builder.CreateExtractValue(NewFrexp, 0,
"mantissa");
4745 Constant *ConstantMantissa = ConstantFP::get(TrueVal->getType(), Mantissa);
4747 Value *NewSel = Builder.CreateSelectFMF(
4748 Cond, ConstIsTrue ? ConstantMantissa : NewEV,
4749 ConstIsTrue ? NewEV : ConstantMantissa,
SelectInst,
"select.frexp",
4760 SQ.getWithInstruction(&EV)))
4774 const unsigned *exti, *exte, *insi, *inse;
4775 for (exti = EV.
idx_begin(), insi =
IV->idx_begin(),
4776 exte = EV.
idx_end(), inse =
IV->idx_end();
4777 exti != exte && insi != inse;
4791 if (exti == exte && insi == inse)
4806 Value *NewEV =
Builder.CreateExtractValue(
IV->getAggregateOperand(),
4824 if (
Instruction *R = foldExtractOfOverflowIntrinsic(EV))
4830 STy && STy->isScalableTy())
4838 if (L->isSimple() && L->hasOneUse()) {
4843 for (
unsigned Idx : EV.
indices())
4850 L->getPointerOperand(), Indices);
4892 DL.getTypeSizeInBits(
Base->getType()))
4902 SQ.getWithInstruction(&BE)))
4907 DL.getTypeSizeInBits(Src->getType()))
4915 switch (Personality) {
4960 bool MakeNewInstruction =
false;
4966 bool isLastClause = i + 1 == e;
4974 if (AlreadyCaught.
insert(TypeInfo).second) {
4979 MakeNewInstruction =
true;
4986 MakeNewInstruction =
true;
4987 CleanupFlag =
false;
5006 if (!NumTypeInfos) {
5009 MakeNewInstruction =
true;
5010 CleanupFlag =
false;
5014 bool MakeNewFilter =
false;
5018 assert(NumTypeInfos > 0 &&
"Should have handled empty filter already!");
5024 MakeNewInstruction =
true;
5031 if (NumTypeInfos > 1)
5032 MakeNewFilter =
true;
5036 NewFilterElts.
reserve(NumTypeInfos);
5041 bool SawCatchAll =
false;
5042 for (
unsigned j = 0; j != NumTypeInfos; ++j) {
5070 if (SeenInFilter.
insert(TypeInfo).second)
5076 MakeNewInstruction =
true;
5081 if (NewFilterElts.
size() < NumTypeInfos)
5082 MakeNewFilter =
true;
5084 if (MakeNewFilter) {
5086 NewFilterElts.
size());
5088 MakeNewInstruction =
true;
5097 if (MakeNewFilter && !NewFilterElts.
size()) {
5098 assert(MakeNewInstruction &&
"New filter but not a new instruction!");
5099 CleanupFlag =
false;
5110 for (
unsigned i = 0, e = NewClauses.
size(); i + 1 < e; ) {
5113 for (j = i; j != e; ++j)
5120 for (
unsigned k = i; k + 1 < j; ++k)
5124 std::stable_sort(NewClauses.
begin() + i, NewClauses.
begin() + j,
5126 MakeNewInstruction =
true;
5145 for (
unsigned i = 0; i + 1 < NewClauses.
size(); ++i) {
5155 for (
unsigned j = NewClauses.
size() - 1; j != i; --j) {
5156 Value *LFilter = NewClauses[j];
5167 NewClauses.
erase(J);
5168 MakeNewInstruction =
true;
5172 unsigned LElts = LTy->getNumElements();
5182 assert(FElts <= LElts &&
"Should have handled this case earlier!");
5184 NewClauses.
erase(J);
5185 MakeNewInstruction =
true;
5194 assert(FElts > 0 &&
"Should have eliminated the empty filter earlier!");
5195 for (
unsigned l = 0; l != LElts; ++l)
5198 NewClauses.
erase(J);
5199 MakeNewInstruction =
true;
5210 bool AllFound =
true;
5211 for (
unsigned f = 0; f != FElts; ++f) {
5214 for (
unsigned l = 0; l != LElts; ++l) {
5216 if (LTypeInfo == FTypeInfo) {
5226 NewClauses.
erase(J);
5227 MakeNewInstruction =
true;
5235 if (MakeNewInstruction) {
5243 if (NewClauses.empty())
5252 assert(!CleanupFlag &&
"Adding a cleanup, not removing one?!");
5282 if (!OrigOpInst || !OrigOpInst->hasOneUse() ||
isa<PHINode>(OrigOp))
5296 Value *MaybePoisonOperand =
nullptr;
5297 for (
Value *V : OrigOpInst->operands()) {
5300 (MaybePoisonOperand && MaybePoisonOperand == V))
5302 if (!MaybePoisonOperand)
5303 MaybePoisonOperand = V;
5308 OrigOpInst->dropPoisonGeneratingAnnotations();
5311 if (!MaybePoisonOperand)
5314 Builder.SetInsertPoint(OrigOpInst);
5315 Value *FrozenMaybePoisonOperand =
Builder.CreateFreeze(
5316 MaybePoisonOperand, MaybePoisonOperand->
getName() +
".fr");
5318 OrigOpInst->replaceUsesOfWith(MaybePoisonOperand, FrozenMaybePoisonOperand);
5329 Use *StartU =
nullptr;
5347 Value *StartV = StartU->get();
5359 if (!Visited.
insert(V).second)
5362 if (Visited.
size() > 32)
5379 I->dropPoisonGeneratingAnnotations();
5381 if (StartNeedsFreeze) {
5408 MoveBefore = *MoveBeforeOpt;
5412 MoveBefore.setHeadBit(
false);
5415 if (&FI != &*MoveBefore) {
5416 FI.
moveBefore(*MoveBefore->getParent(), MoveBefore);
5421 Changed |=
Op->replaceUsesWithIf(&FI, [&](
Use &U) ->
bool {
5422 if (!
DT.dominates(&FI, U))
5425 Users.push_back(U.getUser());
5429 for (
auto *U :
Users) {
5443 for (
auto *U :
V->users()) {
5453 Value *Op0 =
I.getOperand(0);
5483 auto getUndefReplacement = [&](
Type *Ty) {
5484 auto pickCommonConstantFromPHI = [](
PHINode &PN) ->
Value * {
5488 for (
Value *V : PN.incoming_values()) {
5499 if (BestValue && BestValue !=
C)
5508 Value *BestValue =
nullptr;
5509 for (
auto *U :
I.users()) {
5510 Value *V = NullValue;
5519 if (
Value *MaybeV = pickCommonConstantFromPHI(*
PHI))
5525 else if (BestValue != V)
5526 BestValue = NullValue;
5528 assert(BestValue &&
"Must have at least one use");
5529 assert(BestValue != &
I &&
"Cannot replace with itself");
5543 Type *Ty =
C->getType();
5556 !
C->containsConstantExpression()) {
5557 if (
Constant *Repl = getFreezeVectorReplacement(
C))
5591 for (
const User *U :
I.users()) {
5592 if (Visited.
insert(U).second)
5597 while (!AllocaUsers.
empty()) {
5620 if (
isa<PHINode>(
I) ||
I->isEHPad() ||
I->mayThrow() || !
I->willReturn() ||
5637 if (CI->isConvergent())
5643 if (
I->mayWriteToMemory()) {
5650 if (
I->mayReadFromMemory() &&
5651 !
I->hasMetadata(LLVMContext::MD_invariant_load)) {
5658 E =
I->getParent()->end();
5665 I->dropDroppableUses([&](
const Use *U) {
5667 if (
User &&
User->getParent() != DestBlock) {
5669 Assume && Assume->getParent() == SrcBlock) {
5680 I->moveBefore(*DestBlock, InsertPos);
5686 Assume->moveAfter(
I);
5695 if (!DbgVariableRecords.
empty())
5697 DbgVariableRecords);
5720 for (
auto &DVR : DbgVariableRecords)
5721 if (DVR->getParent() != DestBlock)
5722 DbgVariableRecordsToSalvage.
push_back(DVR);
5728 if (DVR->getParent() == SrcBlock)
5729 DbgVariableRecordsToSink.
push_back(DVR);
5736 return B->getInstruction()->comesBefore(
A->getInstruction());
5743 using InstVarPair = std::pair<const Instruction *, DebugVariable>;
5745 if (DbgVariableRecordsToSink.
size() > 1) {
5751 DVR->getDebugLoc()->getInlinedAt());
5752 CountMap[std::make_pair(DVR->getInstruction(), DbgUserVariable)] += 1;
5758 for (
auto It : CountMap) {
5759 if (It.second > 1) {
5760 FilterOutMap[It.first] =
nullptr;
5761 DupSet.
insert(It.first.first);
5772 DVR.getDebugLoc()->getInlinedAt());
5774 FilterOutMap.
find(std::make_pair(Inst, DbgUserVariable));
5775 if (FilterIt == FilterOutMap.
end())
5777 if (FilterIt->second !=
nullptr)
5779 FilterIt->second = &DVR;
5794 DVR->getDebugLoc()->getInlinedAt());
5798 if (!FilterOutMap.
empty()) {
5799 InstVarPair IVP = std::make_pair(DVR->getInstruction(), DbgUserVariable);
5800 auto It = FilterOutMap.
find(IVP);
5803 if (It != FilterOutMap.
end() && It->second != DVR)
5807 if (!SunkVariables.
insert(DbgUserVariable).second)
5810 if (DVR->isDbgAssign())
5818 if (DVRClones.
empty())
5832 assert(InsertPos.getHeadBit());
5834 InsertPos->getParent()->insertDbgRecordBefore(DVRClone, InsertPos);
5858 if (
I ==
nullptr)
continue;
5873 auto getOptionalSinkBlockForInst =
5874 [
this](
Instruction *
I) -> std::optional<BasicBlock *> {
5875 if (!
CLOpts.code_sinking)
5876 return std::nullopt;
5880 unsigned NumUsers = 0;
5882 for (
Use &U :
I->uses()) {
5888 if (
II->getIntrinsicID() != Intrinsic::assume ||
5889 !
II->hasOperandBundle(LLVMContext::OB_Dereferenceable))
5893 if (NumUsers >
CLOpts.max_sink_users)
5894 return std::nullopt;
5900 UserBB = PN->getIncomingBlock(U);
5904 if (UserParent && UserParent != UserBB)
5905 return std::nullopt;
5906 UserParent = UserBB;
5910 if (NumUsers == 0) {
5913 if (UserParent == BB || !
DT.isReachableFromEntry(UserParent))
5914 return std::nullopt;
5926 return std::nullopt;
5928 assert(
DT.dominates(BB, UserParent) &&
"Dominance relation broken?");
5936 return std::nullopt;
5941 auto OptBB = getOptionalSinkBlockForInst(
I);
5943 auto *UserParent = *OptBB;
5951 for (
Use &U :
I->operands())
5959 Builder.SetCurrentDebugLocation(
I->getDebugLoc());
5974 <<
" New = " << *Result <<
'\n');
5979 Result->setDebugLoc(Result->getDebugLoc().orElse(
I->getDebugLoc()));
5981 Result->copyMetadata(*
I, LLVMContext::MD_annotation);
5983 I->replaceAllUsesWith(Result);
5986 Result->takeName(
I);
6001 Result->insertInto(InstParent, InsertPos);
6005 AC.registerAssumption(Assume);
6008 Worklist.pushUsersToWorkList(*Result);
6014 <<
" New = " << *
I <<
'\n');
6046 CommonScopesOfDisjointDomain;
6050 void recordDisjointDomainScopes(
const MDNode *ScopeList) {
6059 for (
auto &[
Domain, Scopes] : UsedScopes) {
6060 auto [It, Inserted] =
6061 CommonScopesOfDisjointDomain.try_emplace(
Domain, Scopes);
6070 bool isImplicitlyNoAlias(
const MDNode *Scope)
const {
6073 return It != CommonScopesOfDisjointDomain.end() &&
6074 !It->second.contains(Scope);
6080 if (!
I->hasMetadataOtherThanDebugLoc())
6083 auto Track = [](
Metadata *ScopeList,
auto &Container) ->
const MDNode * {
6085 if (!MDScopeList || !Container.insert(MDScopeList).second)
6087 for (
const auto &
MDOperand : MDScopeList->operands())
6089 Container.insert(MDScope);
6093 if (
const MDNode *AliasScopeList =
6094 Track(
I->getMetadata(LLVMContext::MD_alias_scope),
6095 UsedAliasScopesAndLists))
6096 recordDisjointDomainScopes(AliasScopeList);
6097 Track(
I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);
6106 "llvm.experimental.noalias.scope.decl in use ?");
6109 "llvm.experimental.noalias.scope should refer to a single scope");
6115 return !UsedAliasScopesAndLists.contains(MD) ||
6116 (!UsedNoAliasScopesAndLists.contains(MD) &&
6117 !isImplicitlyNoAlias(MD));
6141 if (Succ != LiveSucc &&
DeadEdges.insert({BB, Succ}).second)
6142 for (
PHINode &PN : Succ->phis())
6143 for (
Use &U : PN.incoming_values())
6152 return DeadEdges.contains({Pred, BB}) ||
DT.dominates(BB, Pred);
6154 HandleOnlyLiveSuccessor(BB,
nullptr);
6161 if (!Inst.use_empty() &&
6162 (Inst.getNumOperands() == 0 ||
isa<Constant>(Inst.getOperand(0))))
6166 Inst.replaceAllUsesWith(
C);
6169 Inst.eraseFromParent();
6175 for (
Use &U : Inst.operands()) {
6180 Constant *&FoldRes = FoldedConstants[
C];
6186 <<
"\n Old = " << *
C
6187 <<
"\n New = " << *FoldRes <<
'\n');
6197 InstrsForInstructionWorklist.
push_back(&Inst);
6198 SeenAliasScopes.
analyse(&Inst);
6208 HandleOnlyLiveSuccessor(BB,
nullptr);
6212 bool CondVal =
Cond->getZExtValue();
6213 HandleOnlyLiveSuccessor(BB, BI->getSuccessor(!CondVal));
6219 HandleOnlyLiveSuccessor(BB,
nullptr);
6223 HandleOnlyLiveSuccessor(BB,
6224 SI->findCaseValue(
Cond)->getCaseSuccessor());
6234 if (LiveBlocks.
count(&BB))
6237 unsigned NumDeadInstInBB;
6241 NumDeadInst += NumDeadInstInBB;
6258 Inst->eraseFromParent();
6273 Visited[BB->getNumber()] =
true;
6275 if (Visited[Succ->getNumber()])
6287 auto &
DL =
F.getDataLayout();
6289 !
F.hasFnAttribute(
"instcombine-no-verify-fixpoint");
6296 bool MadeIRChange =
false;
6297 if (CLOpts.lower_dbg_declare)
6301 unsigned Iteration = 0;
6305 <<
" on " <<
F.getName()
6306 <<
" reached; stopping without verifying fixpoint\n");
6311 ++NumWorklistIterations;
6312 LLVM_DEBUG(
dbgs() <<
"\n\nINSTCOMBINE ITERATION #" << Iteration <<
" on "
6313 <<
F.getName() <<
"\n");
6315 InstCombinerImpl IC(Worklist,
F,
AA, AC,
TLI,
TTI, DT, ORE, BFI, BPI, PSI,
6318 MadeChangeInThisIteration |= IC.
run();
6319 if (!MadeChangeInThisIteration)
6322 MadeIRChange =
true;
6325 "Instruction Combining on " +
Twine(
F.getName()) +
6328 "Use 'instcombine<no-verify-fixpoint>' or function attribute "
6329 "'instcombine-no-verify-fixpoint' to suppress this error.");
6335 else if (Iteration == 2)
6337 else if (Iteration == 3)
6338 ++NumThreeIterations;
6340 ++NumFourOrMoreIterations;
6342 return MadeIRChange;
6349 static_cast<PassInfoMixin<InstCombinePass> *
>(
this)->
printPipeline(
6350 OS, MapClassName2PassName);
6352 OS <<
"max-iterations=" << Options.MaxIterations <<
";";
6353 OS << (Options.VerifyFixpoint ?
"" :
"no-") <<
"verify-fixpoint";
6357char InstCombinePass::ID = 0;
6363 if (LRT.shouldSkip(&ID))
6376 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
6381 BFI, BPI, PSI, Options)) {
6383 LRT.update(&ID,
false);
6389 LRT.update(&ID,
true);
6429 if (
auto *WrapperPass =
6431 BPI = &WrapperPass->getBPI();
6442 "Combine redundant instructions",
false,
false)
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseMap class.
static bool isSigned(unsigned Opcode)
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
iv Induction Variable Users
static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, bool HasNUW, bool HasNSW, Intrinsic::ID ROp)
Return whether "(X ROp Y) LOp Z" is always equal to "(X LOp Z) ROp (Y LOp Z)".
static bool leftDistributesOverRight(Instruction::BinaryOps LOp, bool HasNUW, bool HasNSW, Intrinsic::ID ROp)
Return whether "X LOp (Y ROp Z)" is always equal to "(X LOp Y) ROp (X LOp Z)".
This file provides internal interfaces used to implement the InstCombine.
This file provides the primary interface to the instcombine pass.
static Value * simplifySwitchOnSelectUsingRanges(SwitchInst &SI, SelectInst *Select, bool IsTrueArm)
static bool isUsedWithinShuffleVector(Value *V)
static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo &TLI, Instruction *AI)
static Constant * constantFoldBinOpWithSplat(unsigned Opcode, Constant *Vector, Constant *Splat, bool SplatLHS, const DataLayout &DL)
static bool shorter_filter(const Value *LHS, const Value *RHS)
static Instruction * combineConstantOffsets(GetElementPtrInst &GEP, InstCombinerImpl &IC)
Combine constant offsets separated by variable offsets.
static std::optional< ModRefInfo > isAllocSiteRemovable(Instruction *AI, SmallVectorImpl< Instruction * > &Users, const TargetLibraryInfo &TLI, bool KnowInit, unsigned MaxUsers)
static Instruction * foldSelectGEP(GetElementPtrInst &GEP, InstCombiner::BuilderTy &Builder)
Thread a GEP operation with constant indices through the constant true/false arms of a select.
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src)
static Instruction * foldSpliceBinOp(BinaryOperator &Inst, InstCombiner::BuilderTy &Builder)
static bool hasNoSignedWrap(BinaryOperator &I)
static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1, InstCombinerImpl &IC)
Combine constant operands of associative operations either before or after a cast to eliminate one of...
static bool combineInstructionsOverFunction(Function &F, InstructionWorklist &Worklist, AliasAnalysis *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI, const InstCombineOptions &Opts)
static Value * simplifyInstructionWithPHI(Instruction &I, PHINode *PN, Value *InValue, BasicBlock *InBB, const DataLayout &DL, const SimplifyQuery SQ)
static bool shouldCanonicalizeGEPToPtrAdd(GetElementPtrInst &GEP)
Return true if we should canonicalize the gep to an i8 ptradd.
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 Value * foldFrexpOfSelect(ExtractValueInst &EV, IntrinsicInst *FrexpCall, SelectInst *SelectInst, InstCombiner::BuilderTy &Builder)
static std::optional< std::pair< Value *, Value * > > matchSymmetricPhiNodesPair(PHINode *LHS, PHINode *RHS)
static Value * foldOperationIntoSelectOperand(Instruction &I, SelectInst *SI, Value *NewOp, InstCombiner &IC)
static void distributeBinOpOverSelect(InstCombinerImpl &IC, Instruction::BinaryOps Opcode, SelectInst *Sel, Value *Other, bool SelIsLHS, FastMathFlags FMF, const SimplifyQuery &SQ, Value *&True, Value *&False)
Distribute a binop over a select: (Cond ?
static Instruction * canonicalizeGEPOfConstGEPI8(GetElementPtrInst &GEP, GEPOperator *Src, InstCombinerImpl &IC)
static Instruction * tryToMoveFreeBeforeNullTest(CallInst &FI, const DataLayout &DL)
Move the call to free before a NULL test.
static Value * simplifyOperationIntoSelectOperand(Instruction &I, SelectInst *SI, bool IsTrueArm)
static Value * tryFactorization(BinaryOperator &I, const SimplifyQuery &SQ, InstCombiner::BuilderTy &Builder, Instruction::BinaryOps InnerOpcode, Value *A, Value *B, Value *C, Value *D)
This tries to simplify binary operations by factorizing out common terms (e.
static bool isRemovableWrite(CallBase &CB, Value *UsedV, const TargetLibraryInfo &TLI)
Given a call CB which uses an address UsedV, return true if we can prove the call's only possible eff...
static Instruction::BinaryOps getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, Value *&LHS, Value *&RHS, BinaryOperator *OtherOp)
This function predicates factorization using distributive laws.
static bool hasNoUnsignedWrap(BinaryOperator &I)
static bool SoleWriteToDeadLocal(Instruction *I, TargetLibraryInfo &TLI)
Check for case where the call writes to an otherwise dead alloca.
static Instruction * foldGEPOfPhi(GetElementPtrInst &GEP, PHINode *PN, IRBuilderBase &Builder)
static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo)
Return 'true' if the given typeinfo will match anything.
static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C)
static GEPNoWrapFlags getMergedGEPNoWrapFlags(GEPOperator &GEP1, GEPOperator &GEP2)
Determine nowrap flags for (gep (gep p, x), y) to (gep p, (x + y)) transform.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
uint64_t IntrinsicInst * II
static bool IsSelect(unsigned Opcode, bool CheckOnlyCC=false)
Check if the opcode is a SELECT or SELECT_CC variant.
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
static const uint32_t IV[8]
bool isNoAliasScopeDeclDead(Instruction *Inst)
void analyse(Instruction *I)
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static constexpr roundingMode rmNearestTiesToEven
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
unsigned getBitWidth() const
Return the number of bits in the APInt.
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
bool isMaxSignedValue() const
Determine if this is the largest signed value.
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Wrapper around alias scope domain metedata to allow accessing their fields, including surfacing the o...
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
uint64_t getNumElements() const
Type * getElementType() const
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI uint64_t getDereferenceableBytes() const
Returns the number of dereferenceable bytes from the dereferenceable attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM Basic Block Representation.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateNUW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
This class represents a no-op cast from one type to another.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
Represents analyses that only rely on functions' control flow.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
void setAttributes(AttributeList A)
Set the attributes for this call.
bool doesNotThrow() const
Determine if the call cannot unwind.
Value * getArgOperand(unsigned i) const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_UGT
unsigned greater than
@ ICMP_ULT
unsigned less than
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
ConstantArray - Constant Array Declarations.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
Constant Vector Declarations.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
const Constant * stripPointerCasts() const
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
A parsed version of the target data layout string in and methods for querying it.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
static bool shouldExecute(CounterInfo &Counter)
Identifies a unique instance of a variable.
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Analysis pass which computes a DominatorTree.
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Convenience struct for specifying and reasoning about fast-math flags.
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass class - This class is used to implement most global optimizations.
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
const BasicBlock & getEntryBlock() const
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags all()
static GEPNoWrapFlags noUnsignedWrap()
GEPNoWrapFlags intersectForReassociate(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep (gep, p, y), x).
bool hasNoUnsignedWrap() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
static GEPNoWrapFlags none()
GEPNoWrapFlags getNoWrapFlags() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Legacy wrapper pass to provide the GlobalsAAResult object.
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
void InsertHelper(Instruction *I, const Twine &Name, BasicBlock::iterator InsertPt) const
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI InstCombinePass(InstCombineOptions Opts={})
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Instruction * visitBitExtractInst(BitExtractInst &BE)
Instruction * foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I)
Tries to simplify binops of select and cast of the select condition.
Instruction * visitCondBrInst(CondBrInst &BI)
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
bool SimplifyAssociativeOrCommutative(BinaryOperator &I)
Performs a few simplifications for operators which are associative or commutative.
Instruction * visitGEPOfGEP(GetElementPtrInst &GEP, GEPOperator *Src)
Value * foldUsingDistributiveLaws(BinaryOperator &I)
Tries to simplify binary operations which some other binary operation distributes over.
Instruction * foldBinOpShiftWithShift(BinaryOperator &I)
Instruction * visitUnreachableInst(UnreachableInst &I)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
void handleUnreachableFrom(Instruction *I, SmallVectorImpl< BasicBlock * > &Worklist)
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Instruction * visitFreeze(FreezeInst &I)
Instruction * foldBinOpSelectBinOp(BinaryOperator &Op)
In some cases it is beneficial to fold a select into a binary operator.
void handlePotentiallyDeadBlocks(SmallVectorImpl< BasicBlock * > &Worklist)
bool prepareWorklist(Function &F)
Perform early cleanup and prepare the InstCombine worklist.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitFree(CallInst &FI, Value *FreedOp)
Instruction * visitExtractValueInst(ExtractValueInst &EV)
void handlePotentiallyDeadSuccessors(BasicBlock *BB, BasicBlock *LiveSucc)
Instruction * foldBinopWithRecurrence(BinaryOperator &BO)
Try to fold binary operators whose operands are simple interleaved recurrences to a single recurrence...
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitLandingPadInst(LandingPadInst &LI)
const InstCombineCLOptions & CLOpts
Value * simplifyNestedSelectsUsingImpliedCond(SelectInst &SI, Value *CondVal, bool CondIsTrue)
Given that CondVal is known to be CondIsTrue, try to simplify SI to one of its arms.
Instruction * visitReturnInst(ReturnInst &RI)
Instruction * visitSwitchInst(SwitchInst &SI)
Instruction * visitBitInsertInst(BitInsertInst &BI)
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth=0)
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; }...
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Instruction * visitUncondBrInst(UncondBrInst &BI)
bool tryReassociateAndFoldSymmetricPair(BinaryOperator &OuterOp, BinaryOperator &InnerOp, Value *InnerVal0, Value *InnerVal1, Value *OuterVal)
If InnerVal1 and OuterVal form a symmetric pair, and "op" is commutative: "(InnerVal0 op InnerVal1) o...
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
Value * pushFreezeToPreventPoisonFromPropagating(FreezeInst &FI)
bool run()
Run the combiner over the entire worklist until it is empty.
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
bool removeInstructionsBeforeUnreachable(Instruction &I)
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
void tryToSinkInstructionDbgVariableRecords(Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock, BasicBlock *DestBlock, SmallVectorImpl< DbgVariableRecord * > &DPUsers)
void addDeadEdge(BasicBlock *From, BasicBlock *To, SmallVectorImpl< BasicBlock * > &Worklist)
Constant * unshuffleConstant(ArrayRef< int > ShMask, Constant *C, VectorType *NewCTy)
Find a constant NewC that has property: shuffle(NewC, poison, ShMask) = C for lanes that select NewC.
Instruction * visitAllocSite(Instruction &FI)
Instruction * visitGetElementPtrInst(GetElementPtrInst &GEP)
Value * tryFactorizationFolds(BinaryOperator &I)
This tries to simplify binary operations by factorizing out common terms (e.
Instruction * foldFreezeIntoRecurrence(FreezeInst &I, PHINode *PN)
bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock)
Try to move the specified instruction from its current block into the beginning of DestBlock,...
bool freezeOtherUses(FreezeInst &FI)
void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser=nullptr)
Freely adapt every user of V as-if V was changed to !V.
The core instruction combiner logic.
const DataLayout & getDataLayout() const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CtxI=nullptr, unsigned Depth=0)
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static bool shouldAvoidAbsorbingNotIntoSelect(const SelectInst &SI)
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
static bool isCanonicalPredicate(CmpPredicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
Instruction * AnnotationMetadataSource
Source for annotation metadata, used by the IRBuilder inserter.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
BranchProbabilityInfo * BPI
ReversePostOrderTraversal< BasicBlock * > & RPOT
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
LLVM_ABI std::optional< Instruction * > targetInstCombineIntrinsic(IntrinsicInst &II)
void addToWorklist(Instruction *I)
LLVM_ABI Value * getFreelyInvertedImpl(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume, unsigned Depth)
Return nonnull value if V is free to invert under the condition of WillInvertAllUses.
SmallDenseSet< std::pair< const BasicBlock *, const BasicBlock * >, 8 > BackEdges
Backedges, used to avoid pushing instructions across backedges in cases where this may result in infi...
LLVM_ABI std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
LLVM_ABI void computeBackEdges()
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
SmallDenseSet< std::pair< BasicBlock *, BasicBlock * >, 8 > DeadEdges
Edges that are known to never be taken.
LLVM_ABI std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
bool isBackEdge(const BasicBlock *From, const BasicBlock *To)
void visit(Iterator Start, Iterator End)
The legacy pass manager's instcombine pass.
InstructionCombiningPass()
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
bool isTerminator() const
iterator_range< user_iterator > users()
void dropPoisonGeneratingAnnotations()
Drops flags, attributes and metadata that may generate poison.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI bool willReturn() const LLVM_READONLY
Return true if the instruction will return (unwinding is considered as a form of returning control fl...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isBitwiseLogicOp() const
Return true if this is and/or/xor.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
A function/module analysis which provides an empty LastRunTrackingInfo.
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
An instruction for reading from memory.
Value * getPointerOperand()
bool isVolatile() const
Return true if this is a load from a volatile memory location.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
Tracking metadata reference owned by Metadata.
This is the common base class for memset/memcpy/memmove.
static LLVM_ABI MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
A Module instance is used to store all the information related to an LLVM module.
MDNode * getScopeList() const
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
A global registry used in conjunction with static constructors to make pluggable components (like tar...
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
const Value * getTrueValue() const
bool insert(const value_type &X)
Insert a new element into the SetVector.
This instruction constructs a fixed permutation of two input vectors.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM_ABI const fltSemantics & getFltSemantics() const
Unconditional Branch instruction.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVMContext & getContext() const
All values hold a context through their type.
bool hasUseList() const
Check if this Value has a use-list.
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool *CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Value handle that is nullable, but tries to track the Value.
An efficient, type-erasing, non-owning reference to a callable.
Type * getIndexedType() const
const ParentTy * getParent() const
reverse_self_iterator getReverseIterator()
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
br_match m_UnconditionalBr(BasicBlock *&Succ)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
auto m_ConstantExpr()
Match a constant expression or a constant that contains a constant expression.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
ContainsMatchingVectorElement_match< SPTy > m_ContainsMatchingVectorElement(const SPTy &SubPattern)
Match a vector constant where at least one of its elements matches the subpattern.
NNegZExt_match< OpTy > m_NNegZExt(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
Splat_match< T > m_Splat(const T &SubPattern)
Match a vector splat.
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_VectorInsert(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
cstfp_pred_ty< is_non_zero_fp > m_NonZeroFP()
Match a floating-point non-zero.
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
void stable_sort(R &&Range)
LLVM_ABI void initializeInstructionCombiningPassPass(PassRegistry &)
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than its terminator and any present EH pad instructi...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Value * simplifyBitInsertInst(Value *Base, Value *Val, Value *Offset, const SimplifyQuery &Q)
Given operands for a BitInsertInst, fold the result or return null.
LLVM_ABI Value * simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef< Value * > Indices, GEPNoWrapFlags NW, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
bool succ_empty(const Instruction *I)
LLVM_ABI Value * simplifyFreezeInst(Value *Op, const SimplifyQuery &Q)
Given an operand for a Freeze, see if we can fold the result.
LLVM_ABI FunctionPass * createInstructionCombiningPass()
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
@ Known
Known to have no common set bits.
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
auto successors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
LLVM_ABI std::optional< StringRef > getAllocationFamily(const Value *I, const TargetLibraryInfo *TLI)
If a function is part of an allocation family (e.g.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI 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.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI Value * getReallocatedOperand(const CallBase *CB)
If this is a call to a realloc function, return the reallocated operand.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc,...
LLVM_ABI bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
const InstCombineCLOptions & getInstCombineCLOptions(const Function &F)
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
constexpr bool has_single_bit(T Value) noexcept
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
constexpr unsigned MaxAnalysisRecursionDepth
auto reverse(ContainerTy &&C)
bool isModSet(const ModRefInfo MRI)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DbgRecords)
Salvage only the records in DbgRecords instead of finding every debug user of I.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
LLVM_ABI Value * simplifyBitExtractInst(Type *Ty, Value *Src, Value *Offset, const SimplifyQuery &Q)
Given operands for a BitExtractInst, fold the result or return null.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ Sub
Subtraction of integers.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
constexpr unsigned BitWidth
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
@ End
Run the machine verifier once, at the end of the pipeline.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI void initializeInstCombine(PassRegistry &)
Initialize all passes linked into the InstCombine library.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
bool isRefSet(const ModRefInfo MRI)
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
SimplifyQuery getWithInstruction(const Instruction *I) const