27#define DEBUG_TYPE "instcombine"
33 const APInt &Demanded) {
35 assert(OpNo < I->getNumOperands() &&
"Operand index too large");
44 if (
C->isSubsetOf(Demanded))
48 I->setOperand(OpNo, ConstantInt::get(
Op->getType(), *
C & Demanded));
60 const APInt &DemandedMask,
63 assert(
I->getOpcode() == Instruction::LShr &&
64 "Only lshr instruction supported");
68 if (!
match(
I->getOperand(0),
78 if (DemandedBitWidth > ShlAmt)
82 if (
Upper->getType()->getScalarSizeInBits() < ShlAmt + DemandedBitWidth)
89 Value *ShrAmt =
I->getOperand(1);
94 if (~KnownShrBits.
Zero != ShlAmt)
113 if (
unsigned BitWidth = Ty->getScalarSizeInBits())
116 return DL.getPointerTypeSizeInBits(Ty);
125 SQ.getWithInstruction(&Inst));
126 if (!V)
return false;
127 if (V == &Inst)
return true;
143 const APInt &DemandedMask,
147 Use &U =
I->getOperandUse(OpNo);
155 if (DemandedMask.
isZero()) {
180 if (!NewVal)
return false;
212 const APInt &DemandedMask,
216 assert(
I !=
nullptr &&
"Null pointer of Value???");
219 Type *VTy =
I->getType();
223 "Value *V, DemandedMask and Known must have same BitWidth");
229 auto disableWrapFlagsBasedOnUnusedHighBits = [](
Instruction *
I,
235 I->setHasNoSignedWrap(
false);
236 I->setHasNoUnsignedWrap(
false);
243 auto simplifyOperandsBasedOnUnusedHighBits = [&](
APInt &DemandedFromOps) {
252 disableWrapFlagsBasedOnUnusedHighBits(
I, NLZ);
258 switch (
I->getOpcode()) {
262 case Instruction::And: {
280 return I->getOperand(0);
282 return I->getOperand(1);
290 case Instruction::Or: {
296 I->dropPoisonGeneratingFlags();
311 return I->getOperand(0);
313 return I->getOperand(1);
322 RHSCache(
I->getOperand(1), RHSKnown);
331 case Instruction::Xor: {
342 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop,
Xor);
356 return I->getOperand(0);
358 return I->getOperand(1);
365 BinaryOperator::CreateOr(
I->getOperand(0),
I->getOperand(1));
379 ~RHSKnown.
One & DemandedMask);
389 if ((*
C | ~DemandedMask).isAllOnes()) {
405 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
408 (LHSKnown.One & RHSKnown.
One & DemandedMask) != 0) {
409 APInt NewMask = ~(LHSKnown.One & RHSKnown.
One & DemandedMask);
412 Instruction *NewAnd = BinaryOperator::CreateAnd(
I->getOperand(0), AndC);
416 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
422 case Instruction::Select: {
432 auto CanonicalizeSelectConstant = [](
Instruction *
I,
unsigned OpNo,
433 const APInt &DemandedMask) {
453 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
454 I->setOperand(OpNo, ConstantInt::get(
I->getType(), *CmpC));
459 if (CanonicalizeSelectConstant(
I, 1, DemandedMask) ||
460 CanonicalizeSelectConstant(
I, 2, DemandedMask))
468 Known = LHSKnown.intersectWith(RHSKnown);
471 case Instruction::Trunc: {
490 case Instruction::ZExt: {
491 unsigned SrcBitWidth =
I->getOperand(0)->getType()->getScalarSizeInBits();
499 I->dropPoisonGeneratingFlags();
503 if (
I->getOpcode() == Instruction::ZExt &&
I->hasNonNeg() &&
510 case Instruction::SExt: {
512 unsigned SrcBitWidth =
I->getOperand(0)->getType()->getScalarSizeInBits();
514 APInt InputDemandedBits = DemandedMask.
trunc(SrcBitWidth);
519 InputDemandedBits.
setBit(SrcBitWidth-1);
540 case Instruction::Add: {
541 if ((DemandedMask & 1) == 0) {
547 X->getType()->isIntOrIntVectorTy(1) &&
X->getType() ==
Y->getType()) {
557 return Builder.CreateSExt(AndNot, VTy);
562 X->getType()->isIntOrIntVectorTy(1) &&
X->getType() ==
Y->getType() &&
563 (
I->getOperand(0)->hasOneUse() ||
I->getOperand(1)->hasOneUse())) {
584 return disableWrapFlagsBasedOnUnusedHighBits(
I, NLZ);
590 APInt DemandedFromLHS = DemandedFromOps;
594 return disableWrapFlagsBasedOnUnusedHighBits(
I, NLZ);
596 unsigned NtzLHS = (~DemandedMask & LHSKnown.Zero).
countr_one();
597 APInt DemandedFromRHS = DemandedFromOps;
600 return disableWrapFlagsBasedOnUnusedHighBits(
I, NLZ);
605 return I->getOperand(0);
606 if (DemandedFromOps.
isSubsetOf(LHSKnown.Zero))
607 return I->getOperand(1);
616 return Builder.CreateXor(
I->getOperand(0), ConstantInt::get(VTy, *
C));
626 case Instruction::Sub: {
633 return disableWrapFlagsBasedOnUnusedHighBits(
I, NLZ);
639 APInt DemandedFromLHS = DemandedFromOps;
643 return disableWrapFlagsBasedOnUnusedHighBits(
I, NLZ);
648 return I->getOperand(0);
651 if (DemandedFromOps.
isOne() && DemandedFromOps.
isSubsetOf(LHSKnown.Zero))
652 return I->getOperand(1);
660 return Builder.CreateNot(
I->getOperand(1));
669 case Instruction::Mul: {
670 APInt DemandedFromOps;
671 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
681 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
682 Instruction *Shl = BinaryOperator::CreateShl(
I->getOperand(0), ShiftC);
689 if (
I->getOperand(0) ==
I->getOperand(1) && DemandedMask.
ult(4)) {
690 Constant *One = ConstantInt::get(VTy, 1);
691 Instruction *And1 = BinaryOperator::CreateAnd(
I->getOperand(0), One);
698 case Instruction::Shl: {
705 DemandedMask,
Known))
709 if (
I->hasOneUse()) {
711 if (Inst->
getOpcode() == BinaryOperator::Or) {
713 auto [IID, FShiftArgs] = *Opt;
714 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
715 FShiftArgs[0] == FShiftArgs[1]) {
727 if (
I->hasNoSignedWrap()) {
731 if (SignBits > ShiftAmt && SignBits - ShiftAmt >= NumHiDemandedBits)
732 return I->getOperand(0);
742 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
746 LeftShiftAmtC,
DL) ==
C) {
747 Instruction *Lshr = BinaryOperator::CreateLShr(NewC,
X);
753 APInt DemandedMaskIn(DemandedMask.
lshr(ShiftAmt));
777 I->dropPoisonGeneratingFlags();
785 case Instruction::LShr: {
791 if (
I->hasOneUse()) {
793 if (Inst->
getOpcode() == BinaryOperator::Or) {
795 auto [IID, FShiftArgs] = *Opt;
796 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
797 FShiftArgs[0] == FShiftArgs[1]) {
813 if (SignBits >= NumHiDemandedBits)
814 return I->getOperand(0);
823 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
827 RightShiftAmtC,
DL) ==
C) {
834 if (
match(
I->getOperand(0),
838 X, ConstantInt::get(
X->getType(), Factor->
lshr(ShiftAmt)));
844 APInt DemandedMaskIn(DemandedMask.
shl(ShiftAmt));
847 I->dropPoisonGeneratingFlags();
852 Known.Zero.setHighBits(ShiftAmt);
862 case Instruction::AShr: {
868 if (SignBits >= NumHiDemandedBits)
869 return I->getOperand(0);
875 if (DemandedMask.
isOne()) {
878 I->getOperand(0),
I->getOperand(1),
I->getName());
887 APInt DemandedMaskIn(DemandedMask.
shl(ShiftAmt));
890 bool ShiftedInBitsDemanded = DemandedMask.
countl_zero() < ShiftAmt;
891 if (ShiftedInBitsDemanded)
895 I->dropPoisonGeneratingFlags();
911 ShiftAmt != 0,
I->isExact());
917 case Instruction::UDiv: {
923 APInt DemandedMaskIn =
928 I->dropPoisonGeneratingFlags();
939 case Instruction::SRem: {
942 if (DemandedMask.
ult(*Rem))
943 return I->getOperand(0);
945 APInt LowBits = *Rem - 1;
956 case Instruction::Call: {
957 bool KnownBitsComputed =
false;
959 switch (
II->getIntrinsicID()) {
960 case Intrinsic::abs: {
961 if (DemandedMask == 1)
962 return II->getArgOperand(0);
965 case Intrinsic::ctpop: {
973 II->getModule(), Intrinsic::ctpop, VTy);
978 case Intrinsic::bswap: {
995 NewVal = BinaryOperator::CreateLShr(
996 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
998 NewVal = BinaryOperator::CreateShl(
999 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
1005 case Intrinsic::ptrmask: {
1006 unsigned MaskWidth =
I->getOperand(1)->getType()->getScalarSizeInBits();
1011 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
1012 RHSKnown, Q,
Depth + 1))
1018 Known = LHSKnown & RHSKnown;
1019 KnownBitsComputed =
true;
1034 if (DemandedMask.
isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1035 return I->getOperand(0);
1039 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
1048 uint64_t PtrMaskImmediate;
1055 if (!LHSKnown.isZero()) {
1056 const unsigned trailingZeros = LHSKnown.countMinTrailingZeros();
1057 uint64_t PointerAlignBits = (
uint64_t(1) << trailingZeros) - 1;
1059 uint64_t HighBitsGEPIndex = GEPIndex & ~PointerAlignBits;
1060 uint64_t MaskedLowBitsGEPIndex =
1061 GEPIndex & PointerAlignBits & PtrMaskImmediate;
1063 uint64_t MaskedGEPIndex = HighBitsGEPIndex | MaskedLowBitsGEPIndex;
1065 if (MaskedGEPIndex != GEPIndex) {
1068 Type *GEPIndexType =
1069 DL.getIndexType(
GEP->getPointerOperand()->getType());
1071 GEP->getSourceElementType(), InnerPtr,
1072 ConstantInt::get(GEPIndexType, MaskedGEPIndex),
1073 GEP->getName(),
GEP->isInBounds());
1084 case Intrinsic::fshr:
1085 case Intrinsic::fshl: {
1093 if (
II->getIntrinsicID() == Intrinsic::fshr)
1096 APInt DemandedMaskLHS(DemandedMask.
lshr(ShiftAmt));
1098 if (
I->getOperand(0) !=
I->getOperand(1)) {
1104 I->dropPoisonGeneratingAnnotations();
1111 if (DemandedMaskLHS.
isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
1115 I->dropPoisonGeneratingAnnotations();
1124 I->dropPoisonGeneratingAnnotations();
1129 LHSKnown <<= ShiftAmt;
1131 Known = LHSKnown.unionWith(RHSKnown);
1132 KnownBitsComputed =
true;
1135 case Intrinsic::umax: {
1142 CTZ >=
C->getActiveBits())
1143 return II->getArgOperand(0);
1146 case Intrinsic::umin: {
1154 CTZ >=
C->getBitWidth() -
C->countl_one())
1155 return II->getArgOperand(0);
1161 *
II, DemandedMask,
Known, KnownBitsComputed);
1169 if (!KnownBitsComputed)
1175 if (
I->getType()->isPointerTy()) {
1176 Align Alignment =
I->getPointerAlignment(
DL);
1184 if (!
I->getType()->isPointerTy() &&
1188 if (
CLOpts.verify_known_bits) {
1190 if (
Known != ReferenceKnown) {
1191 errs() <<
"Mismatched known bits for " << *
I <<
" in "
1192 <<
I->getFunction()->getName() <<
"\n";
1193 errs() <<
"computeKnownBits(): " << ReferenceKnown <<
"\n";
1194 errs() <<
"SimplifyDemandedBits(): " <<
Known <<
"\n";
1209 Type *ITy =
I->getType();
1218 switch (
I->getOpcode()) {
1219 case Instruction::And: {
1234 return I->getOperand(0);
1236 return I->getOperand(1);
1240 case Instruction::Or: {
1257 return I->getOperand(0);
1259 return I->getOperand(1);
1263 case Instruction::Xor: {
1279 return I->getOperand(0);
1281 return I->getOperand(1);
1285 case Instruction::Add: {
1293 return I->getOperand(0);
1297 return I->getOperand(1);
1305 case Instruction::Sub: {
1313 return I->getOperand(0);
1322 case Instruction::AShr: {
1335 const APInt *ShiftRC;
1336 const APInt *ShiftLC;
1384 if (!ShlOp1 || !ShrOp1)
1389 unsigned BitWidth = Ty->getScalarSizeInBits();
1396 Known.One.clearAllBits();
1397 Known.Zero.setLowBits(ShlAmt - 1);
1398 Known.Zero &= DemandedMask;
1403 bool isLshr = (Shr->
getOpcode() == Instruction::LShr);
1404 BitMask1 = isLshr ? (BitMask1.
lshr(ShrAmt) << ShlAmt) :
1405 (BitMask1.
ashr(ShrAmt) << ShlAmt);
1407 if (ShrAmt <= ShlAmt) {
1408 BitMask2 <<= (ShlAmt - ShrAmt);
1410 BitMask2 = isLshr ? BitMask2.
lshr(ShrAmt - ShlAmt):
1411 BitMask2.
ashr(ShrAmt - ShlAmt);
1415 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1416 if (ShrAmt == ShlAmt)
1423 if (ShrAmt < ShlAmt) {
1425 New = BinaryOperator::CreateShl(VarX, Amt);
1431 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1432 BinaryOperator::CreateAShr(VarX, Amt);
1434 New->setIsExact(
true);
1449 unsigned DepthLimit) {
1452 if (!IE.hasOneUse())
1455 if (!UserIE || UserIE->getOperand(0) != &IE)
1463 if (!Idx || Idx->getValue().uge(VWidth))
1466 unsigned Index = Idx->getZExtValue();
1467 if (SeenIndices.
test(Index))
1470 SeenIndices.
set(Index);
1475 for (
unsigned I = 0;
I != DepthLimit; ++
I) {
1480 if (!HasNewIndexInRange(*Cur))
1488 if (!Cur || !Cur->hasOneUse())
1512 bool AllowMultipleUsers) {
1520 assert((DemandedElts & ~EltMask) == 0 &&
"Invalid DemandedElts!");
1524 PoisonElts = EltMask;
1528 if (DemandedElts.
isZero()) {
1529 PoisonElts = EltMask;
1544 for (
unsigned i = 0; i != VWidth; ++i) {
1545 if (!DemandedElts[i]) {
1551 Constant *Elt =
C->getAggregateElement(i);
1552 if (!Elt)
return nullptr;
1561 return NewCV !=
C ? NewCV :
nullptr;
1568 if (!AllowMultipleUsers) {
1572 if (!V->hasOneUse()) {
1581 DemandedElts = EltMask;
1586 if (!
I)
return nullptr;
1588 bool MadeChange =
false;
1589 auto simplifyAndSetOp = [&](
Instruction *Inst,
unsigned OpNum,
1599 APInt PoisonElts2(VWidth, 0);
1600 APInt PoisonElts3(VWidth, 0);
1601 switch (
I->getOpcode()) {
1604 case Instruction::GetElementPtr: {
1622 for (
unsigned i = 0; i <
I->getNumOperands(); i++) {
1626 PoisonElts = EltMask;
1629 if (
I->getOperand(i)->getType()->isVectorTy()) {
1630 APInt PoisonEltsOp(VWidth, 0);
1631 simplifyAndSetOp(
I, i, DemandedElts, PoisonEltsOp);
1636 PoisonElts |= PoisonEltsOp;
1642 case Instruction::InsertElement: {
1643 unsigned DepthLimit =
CLOpts.simplify_vector_elts_depth;
1646 if (
Depth == 0 && DemandedElts.
isAllOnes() && VWidth > DepthLimit &&
1656 simplifyAndSetOp(
I, 0, DemandedElts, PoisonElts2);
1662 unsigned IdxNo = Idx->getZExtValue();
1663 APInt PreInsertDemandedElts = DemandedElts;
1665 PreInsertDemandedElts.
clearBit(IdxNo);
1673 if (PreInsertDemandedElts == 0 &&
1680 simplifyAndSetOp(
I, 0, PreInsertDemandedElts, PoisonElts);
1684 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1686 return I->getOperand(0);
1693 case Instruction::ShuffleVector: {
1695 assert(Shuffle->getOperand(0)->getType() ==
1696 Shuffle->getOperand(1)->getType() &&
1697 "Expected shuffle operands to have same type");
1708 APInt LeftDemanded(OpWidth, 1);
1709 APInt LHSPoisonElts(OpWidth, 0);
1710 simplifyAndSetOp(
I, 0, LeftDemanded, LHSPoisonElts);
1711 if (LHSPoisonElts[0])
1712 PoisonElts = EltMask;
1718 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1719 for (
unsigned i = 0; i < VWidth; i++) {
1720 if (DemandedElts[i]) {
1721 unsigned MaskVal = Shuffle->getMaskValue(i);
1722 if (MaskVal != -1u) {
1723 assert(MaskVal < OpWidth * 2 &&
1724 "shufflevector mask index out of range!");
1725 if (MaskVal < OpWidth)
1726 LeftDemanded.setBit(MaskVal);
1728 RightDemanded.
setBit(MaskVal - OpWidth);
1733 APInt LHSPoisonElts(OpWidth, 0);
1734 simplifyAndSetOp(
I, 0, LeftDemanded, LHSPoisonElts);
1736 APInt RHSPoisonElts(OpWidth, 0);
1737 simplifyAndSetOp(
I, 1, RightDemanded, RHSPoisonElts);
1750 if (VWidth == OpWidth) {
1751 bool IsIdentityShuffle =
true;
1752 for (
unsigned i = 0; i < VWidth; i++) {
1753 unsigned MaskVal = Shuffle->getMaskValue(i);
1754 if (DemandedElts[i] && i != MaskVal) {
1755 IsIdentityShuffle =
false;
1759 if (IsIdentityShuffle)
1760 return Shuffle->getOperand(0);
1763 bool NewPoisonElts =
false;
1764 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1765 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1766 bool LHSUniform =
true;
1767 bool RHSUniform =
true;
1768 for (
unsigned i = 0; i < VWidth; i++) {
1769 unsigned MaskVal = Shuffle->getMaskValue(i);
1770 if (MaskVal == -1u) {
1772 }
else if (!DemandedElts[i]) {
1773 NewPoisonElts =
true;
1775 }
else if (MaskVal < OpWidth) {
1776 if (LHSPoisonElts[MaskVal]) {
1777 NewPoisonElts =
true;
1780 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1781 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1782 LHSUniform = LHSUniform && (MaskVal == i);
1785 if (RHSPoisonElts[MaskVal - OpWidth]) {
1786 NewPoisonElts =
true;
1789 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1790 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1791 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1807 if (LHSIdx < OpWidth && RHSUniform) {
1809 Op = Shuffle->getOperand(1);
1810 Value = CV->getOperand(LHSValIdx);
1814 if (RHSIdx < OpWidth && LHSUniform) {
1816 Op = Shuffle->getOperand(0);
1817 Value = CV->getOperand(RHSValIdx);
1830 if (NewPoisonElts) {
1833 for (
unsigned i = 0; i < VWidth; ++i) {
1837 Elts.
push_back(Shuffle->getMaskValue(i));
1839 Shuffle->setShuffleMask(Elts);
1844 case Instruction::Select: {
1854 simplifyAndSetOp(
I, 0, DemandedElts, PoisonElts);
1858 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1860 for (
unsigned i = 0; i < VWidth; i++) {
1865 DemandedLHS.clearBit(i);
1871 simplifyAndSetOp(
I, 1, DemandedLHS, PoisonElts2);
1872 simplifyAndSetOp(
I, 2, DemandedRHS, PoisonElts3);
1876 PoisonElts = PoisonElts2 & PoisonElts3;
1879 case Instruction::BitCast: {
1884 APInt InputDemandedElts(InVWidth, 0);
1885 PoisonElts2 =
APInt(InVWidth, 0);
1888 if (VWidth == InVWidth) {
1892 InputDemandedElts = DemandedElts;
1893 }
else if ((VWidth % InVWidth) == 0) {
1897 Ratio = VWidth / InVWidth;
1898 for (
unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1899 if (DemandedElts[OutIdx])
1900 InputDemandedElts.
setBit(OutIdx / Ratio);
1901 }
else if ((InVWidth % VWidth) == 0) {
1905 Ratio = InVWidth / VWidth;
1906 for (
unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1907 if (DemandedElts[InIdx / Ratio])
1908 InputDemandedElts.
setBit(InIdx);
1914 simplifyAndSetOp(
I, 0, InputDemandedElts, PoisonElts2);
1916 if (VWidth == InVWidth) {
1917 PoisonElts = PoisonElts2;
1918 }
else if ((VWidth % InVWidth) == 0) {
1922 for (
unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1923 if (PoisonElts2[OutIdx / Ratio])
1924 PoisonElts.
setBit(OutIdx);
1925 }
else if ((InVWidth % VWidth) == 0) {
1929 for (
unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1932 PoisonElts.
setBit(OutIdx);
1939 case Instruction::FPTrunc:
1940 case Instruction::FPExt:
1941 simplifyAndSetOp(
I, 0, DemandedElts, PoisonElts);
1944 case Instruction::Call: {
1947 switch (
II->getIntrinsicID()) {
1948 case Intrinsic::masked_gather:
1949 case Intrinsic::masked_load: {
1954 DemandedPassThrough(DemandedElts);
1956 for (
unsigned i = 0; i < VWidth; i++) {
1958 if (CElt->isNullValue())
1959 DemandedPtrs.clearBit(i);
1960 else if (CElt->isAllOnesValue())
1966 if (
II->getIntrinsicID() == Intrinsic::masked_gather)
1967 simplifyAndSetOp(
II, 0, DemandedPtrs, PoisonElts2);
1968 simplifyAndSetOp(
II, 2, DemandedPassThrough, PoisonElts3);
1972 PoisonElts = PoisonElts2 & PoisonElts3;
1975 case Intrinsic::vector_shuffle: {
1978 simplifyAndSetOp(
II, 1, DemandedElts, PoisonElts);
1983 II->getArgOperand(1),
false,
SQ.getWithInstruction(
II));
1989 simplifyAndSetOp(
II, 0, DemandedSrc, PoisonElts3);
1995 *
II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
2005 APInt PoisonEltsAcc(VWidth, 0);
2006 for (
Use &Arg :
II->args()) {
2007 unsigned OpNo = Arg.getOperandNo();
2011 APInt OpPoisonElts(VWidth, 0);
2012 simplifyAndSetOp(
II, OpNo, DemandedElts, OpPoisonElts);
2013 PoisonEltsAcc |= OpPoisonElts;
2018 PoisonElts = PoisonEltsAcc;
2050 if (DemandedElts == 1 && !
X->hasOneUse() && !
Y->hasOneUse() &&
2053 auto findShufBO = [&](
bool MatchShufAsOp0) ->
User * {
2058 Value *OtherOp = MatchShufAsOp0 ?
Y :
X;
2063 Value *ShufOp = MatchShufAsOp0 ?
X :
Y;
2074 if (
DT.dominates(U,
I))
2080 User *ShufBO = findShufBO(
true);
2082 ShufBO = findShufBO(
false);
2085 ShufBOI->andIRFlags(BO);
2091 simplifyAndSetOp(
I, 0, DemandedElts, PoisonElts);
2092 simplifyAndSetOp(
I, 1, DemandedElts, PoisonElts2);
2096 PoisonElts &= PoisonElts2;
2104 return MadeChange ?
I :
nullptr;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bpf unwind BPF Unwind Lower
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file provides internal interfaces used to implement the InstCombine.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
static Value * simplifyShiftSelectingPackedElement(Instruction *I, const APInt &DemandedMask, InstCombinerImpl &IC, unsigned Depth)
Let N = 2 * M.
static bool canSkipDemandedEltsInInsertChain(InsertElementInst &IE, unsigned VWidth, unsigned DepthLimit)
Return true if the top-level all-lanes demanded-elements query can be skipped for an intermediate ins...
This file provides the interface for the instcombine pass implementation.
uint64_t IntrinsicInst * II
This file implements the SmallBitVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
void clearBit(unsigned BitPosition)
Set a given bit to 0.
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
uint64_t getZExtValue() const
Get zero extended value.
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
unsigned popcount() const
Count the number of bits set.
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
unsigned getActiveBits() const
Compute the number of active bits in the value.
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
void setSignBit()
Set the sign bit to 1.
unsigned getBitWidth() const
Return the number of bits in the APInt.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
void clearAllBits()
Set every bit to 0.
unsigned countr_zero() const
Count the number of trailing zero bits.
unsigned countl_zero() const
The APInt version of std::countl_zero.
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
APInt shl(unsigned shiftAmt) const
Left-shift function.
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
bool isOne() const
Determine if this is a value of 1.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
BinaryOps getOpcode() const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the base class for all instructions that perform data casts.
This is the shared class of boolean and integer constants.
const APInt & getValue() const
Return the constant as an APInt value reference.
This class represents a range of values.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
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...
A parsed version of the target data layout string in and methods for querying it.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
LLVM_ABI Value * CreateSelectWithUnknownProfile(Value *C, Value *True, Value *False, StringRef PassName, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
This instruction inserts a single (scalar) element into a VectorType value.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
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.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
std::optional< std::pair< Intrinsic::ID, SmallVector< Value *, 3 > > > convertOrOfShiftsToFunnelShift(Instruction &Or)
const InstCombineCLOptions & CLOpts
Value * simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known)
Helper routine of SimplifyDemandedUseBits.
Value * SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Attempts to replace I with a simpler value based on the demanded bits.
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Value * SimplifyMultipleUseDemandedBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Helper routine of SimplifyDemandedUseBits.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
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.
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
LLVM_ABI std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
LLVM_ABI std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
A wrapper class for inspecting calls to intrinsic functions.
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.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
bool test(unsigned Idx) const
Returns true if bit Idx is set.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isVectorTy() const
True if this is an instance of VectorType.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
iterator_range< user_iterator > users()
bool hasUseList() const
Check if this Value has a use-list.
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.
Base class of all SIMD vector types.
This class represents zero extension of integer types.
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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< 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)
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
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.
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)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
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)
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
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.
DisjointOr_match< LHS, RHS, true > m_c_DisjointOr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
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 void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
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...
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
gep_type_iterator gep_type_end(const User *GEP)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
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 bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
DWARFExpression::Operation Op
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
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)
unsigned Log2(Align A)
Returns the log2 of the alignment.
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
bool isNonNegative() const
Returns true if this value is known to be non-negative.
void makeNonNegative()
Make this value non-negative.
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
unsigned getBitWidth() const
Get the bit width of this value.
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isNegative() const
Returns true if this value is known to be negative.
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).