47#define DEBUG_TYPE "vector-combine"
53STATISTIC(NumVecLoad,
"Number of vector loads formed");
54STATISTIC(NumVecCmp,
"Number of vector compares formed");
55STATISTIC(NumVecBO,
"Number of vector binops formed");
56STATISTIC(NumVecCmpBO,
"Number of vector compare + binop formed");
57STATISTIC(NumShufOfBitcast,
"Number of shuffles moved after bitcast");
58STATISTIC(NumScalarOps,
"Number of scalar unary + binary ops formed");
59STATISTIC(NumScalarCmp,
"Number of scalar compares formed");
60STATISTIC(NumScalarIntrinsic,
"Number of scalar intrinsic calls formed");
62static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
67 VectorCombine(
const VectorizeOptions &Opts,
Function &
F,
78 TTI(TTI), DT(DT), AA(AA),
DL(DL), CostKind(CostKind),
79 SQ(*DL,
nullptr, &DT, &AC),
80 TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
85 const VectorizeOptions &Opts;
87 IRBuilder<InstSimplifyFolder, IRBuilderCallbackInserter> Builder;
88 const TargetTransformInfo &TTI;
89 const DominatorTree &DT;
93 const SimplifyQuery SQ;
97 bool TryEarlyFoldsOnly;
99 InstructionWorklist Worklist;
108 bool vectorizeLoadInsert(Instruction &
I);
109 bool widenSubvectorLoad(Instruction &
I);
110 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
111 ExtractElementInst *Ext1,
112 unsigned PreferredExtractIndex)
const;
113 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
114 const Instruction &
I,
115 ExtractElementInst *&ConvertToShuffle,
116 unsigned PreferredExtractIndex);
119 bool foldExtractExtract(Instruction &
I);
120 bool foldInsExtFNeg(Instruction &
I);
121 bool foldInsExtBinop(Instruction &
I);
122 bool foldInsExtVectorToShuffle(Instruction &
I);
123 bool foldInsertScalarPartsToShuffle(Instruction &
I);
124 bool foldBitOpOfCastops(Instruction &
I);
125 bool foldBitOpOfCastConstant(Instruction &
I);
126 bool foldBitcastShuffle(Instruction &
I);
127 bool scalarizeOpOrCmp(Instruction &
I);
128 bool foldExtractedCmps(Instruction &
I);
129 bool foldSelectsFromBitcast(Instruction &
I);
130 bool foldBinopOfReductions(Instruction &
I);
131 bool foldInsertElementsToStores(Instruction &
I);
132 bool scalarizeLoad(Instruction &
I);
133 bool scalarizeLoadExtract(LoadInst *LI, VectorType *VecTy,
Value *Ptr);
134 bool scalarizeLoadBitcast(LoadInst *LI, VectorType *VecTy,
Value *Ptr);
135 bool scalarizeExtExtract(Instruction &
I);
136 bool foldConcatOfBoolMasks(Instruction &
I);
137 bool foldPermuteOfBinops(Instruction &
I);
138 bool foldShuffleOfBinops(Instruction &
I);
139 bool foldShuffleOfSelects(Instruction &
I);
140 bool foldShuffleOfCastops(Instruction &
I);
141 bool foldShuffleOfShuffles(Instruction &
I);
142 bool foldShuffleOfAdjacentLoads(Instruction &
I);
143 bool foldPermuteOfIntrinsic(Instruction &
I);
144 bool foldShufflesOfLengthChangingShuffles(Instruction &
I);
145 bool foldShuffleOfIntrinsics(Instruction &
I);
146 bool foldShuffleToIdentity(Instruction &
I);
147 bool foldShuffleFromReductions(Instruction &
I);
148 bool foldShuffleChainsToReduce(Instruction &
I);
149 bool foldCastFromReductions(Instruction &
I);
150 bool foldSignBitReductionCmp(Instruction &
I);
151 bool foldReductionZeroTest(Instruction &
I);
152 bool foldICmpEqZeroVectorReduce(Instruction &
I);
153 bool foldEquivalentReductionCmp(Instruction &
I);
154 bool foldReduceAddCmpZero(Instruction &
I);
155 bool foldSelectShuffle(Instruction &
I,
bool FromReduction =
false);
156 bool foldInterleaveIntrinsics(Instruction &
I);
157 bool foldDeinterleaveIntrinsics(Instruction &
I);
158 bool foldBitcastOfVPLoad(Instruction &
I);
159 bool foldBitOrderReverseAndSwap(Instruction &
I);
160 bool shrinkType(Instruction &
I);
161 bool shrinkLoadForShuffles(Instruction &
I);
162 bool shrinkPhiOfShuffles(Instruction &
I);
163 bool foldInterleaveOfDeinterleaveChains(Instruction &
I);
165 void replaceValue(Instruction &Old,
Value &New,
bool Erase =
true) {
171 Worklist.pushUsersToWorkList(*NewI);
172 Worklist.pushValue(NewI);
189 SmallPtrSet<Value *, 4> Visited;
194 OpI,
nullptr,
nullptr, [&](
Value *
V) {
199 NextInst = NextInst->getNextNode();
204 Worklist.pushUsersToWorkList(*OpI);
205 Worklist.pushValue(OpI);
217 V = BitCast->getOperand(0);
223 return X->getType() ==
Y->getType() &&
232 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
238 Type *ScalarTy =
Load->getType()->getScalarType();
240 unsigned MinVectorSize =
TTI.getMinVectorRegisterBitWidth();
241 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
248bool VectorCombine::vectorizeLoadInsert(
Instruction &
I) {
274 Value *SrcPtr =
Load->getPointerOperand()->stripPointerCasts();
277 unsigned MinVecNumElts = MinVectorSize / ScalarSize;
278 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts,
false);
279 unsigned OffsetEltIndex = 0;
290 unsigned OffsetBitWidth =
DL->getIndexTypeSizeInBits(SrcPtr->
getType());
291 APInt
Offset(OffsetBitWidth, 0);
301 uint64_t ScalarSizeInBytes = ScalarSize / 8;
302 if (
Offset.urem(ScalarSizeInBytes) != 0)
306 APInt OffsetEltIndexAP =
Offset.udiv(ScalarSizeInBytes);
307 if (OffsetEltIndexAP.
uge(MinVecNumElts))
326 unsigned AS =
Load->getPointerAddressSpace();
332 true, HasExtract, CostKind);
345 unsigned OutputNumElts = Ty->getNumElements();
347 assert(OffsetEltIndex < MinVecNumElts &&
"Address offset too big");
348 Mask[0] = OffsetEltIndex;
355 if (OldCost < NewCost || !NewCost.
isValid())
366 replaceValue(
I, *VecLd);
374bool VectorCombine::widenSubvectorLoad(Instruction &
I) {
377 if (!Shuf->isIdentityWithPadding())
383 unsigned OpIndex =
any_of(Shuf->getShuffleMask(), [&NumOpElts](
int M) {
384 return M >= (int)(NumOpElts);
407 unsigned AS =
Load->getPointerAddressSpace();
422 if (OldCost < NewCost || !NewCost.
isValid())
429 replaceValue(
I, *VecLd);
436ExtractElementInst *VectorCombine::getShuffleExtract(
437 ExtractElementInst *Ext0, ExtractElementInst *Ext1,
441 assert(Index0C && Index1C &&
"Expected constant extract indexes");
443 unsigned Index0 = Index0C->getZExtValue();
444 unsigned Index1 = Index1C->getZExtValue();
447 if (Index0 == Index1)
471 if (PreferredExtractIndex == Index0)
473 if (PreferredExtractIndex == Index1)
477 return Index0 > Index1 ? Ext0 : Ext1;
485bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
486 ExtractElementInst *Ext1,
487 const Instruction &
I,
488 ExtractElementInst *&ConvertToShuffle,
489 unsigned PreferredExtractIndex) {
492 assert(Ext0IndexC && Ext1IndexC &&
"Expected constant extract indexes");
494 unsigned Opcode =
I.getOpcode();
507 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
508 "Expected a compare");
518 unsigned Ext0Index = Ext0IndexC->getZExtValue();
519 unsigned Ext1Index = Ext1IndexC->getZExtValue();
533 unsigned BestExtIndex = Extract0Cost > Extract1Cost ? Ext0Index : Ext1Index;
534 unsigned BestInsIndex = Extract0Cost > Extract1Cost ? Ext1Index : Ext0Index;
535 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
540 if (Ext0Src == Ext1Src && Ext0Index == Ext1Index) {
545 bool HasUseTax = Ext0 == Ext1 ? !Ext0->
hasNUses(2)
547 OldCost = CheapExtractCost + ScalarOpCost;
548 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
552 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
553 NewCost = VectorOpCost + CheapExtractCost +
558 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
559 if (ConvertToShuffle) {
560 if (IsBinOp && Opts.disable_binop_extract_shuffle)
571 SmallVector<int> ShuffleMask(FixedVecTy->getNumElements(),
573 ShuffleMask[BestInsIndex] = BestExtIndex;
575 VecTy, VecTy, CostKind, ShuffleMask, 0,
576 nullptr, {ConvertToShuffle});
579 VecTy, VecTy, CostKind, {}, 0,
nullptr,
584 LLVM_DEBUG(
dbgs() <<
"Found a binop of extractions: " <<
I <<
"\n OldCost: "
585 << OldCost <<
" vs NewCost: " << NewCost <<
"\n");
590 return OldCost < NewCost;
602 ShufMask[NewIndex] = OldIndex;
603 return Builder.CreateShuffleVector(Vec, ShufMask,
"shift");
655 V1,
"foldExtExtBinop");
660 VecBOInst->copyIRFlags(&
I);
666bool VectorCombine::foldExtractExtract(Instruction &
I) {
682 V0->getType() !=
V1->getType())
687 unsigned NumElts = FixedVecTy->getNumElements();
688 if (
C0 >= NumElts ||
C1 >= NumElts)
704 ExtractElementInst *ExtractToChange;
705 if (isExtractExtractCheap(Ext0, Ext1,
I, ExtractToChange, InsertIndex))
711 if (ExtractToChange) {
712 unsigned CheapExtractIdx = ExtractToChange == Ext0 ?
C1 :
C0;
717 if (ExtractToChange == Ext0)
726 ? foldExtExtCmp(ExtOp0, ExtOp1, ExtIndex,
I)
727 : foldExtExtBinop(ExtOp0, ExtOp1, ExtIndex,
I);
728 replaceValue(
I, *NewExt);
734bool VectorCombine::foldInsExtFNeg(Instruction &
I) {
753 auto *DstVecScalarTy = DstVecTy->getScalarType();
755 if (!SrcVecTy || DstVecScalarTy != SrcVecTy->getScalarType())
760 unsigned NumDstElts = DstVecTy->getNumElements();
761 unsigned NumSrcElts = SrcVecTy->getNumElements();
762 if (ExtIdx > NumSrcElts || InsIdx >= NumDstElts || NumDstElts == 1)
768 SmallVector<int>
Mask(NumDstElts);
769 std::iota(
Mask.begin(),
Mask.end(), 0);
770 Mask[InsIdx] = (ExtIdx % NumDstElts) + NumDstElts;
784 DstVecTy, CostKind, Mask);
786 bool NeedLenChg = SrcVecTy->getNumElements() != NumDstElts;
789 SmallVector<int> SrcMask;
792 SrcMask[ExtIdx % NumDstElts] = ExtIdx;
794 DstVecTy, SrcVecTy, CostKind, SrcMask);
798 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
800 if (NewCost > OldCost)
803 Value *NewShuf, *LenChgShuf =
nullptr;
815 replaceValue(
I, *NewShuf);
821bool VectorCombine::foldInsExtBinop(Instruction &
I) {
822 BinaryOperator *VecBinOp, *SclBinOp;
854 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
856 if (NewCost > OldCost)
867 NewInst->copyIRFlags(VecBinOp);
868 NewInst->andIRFlags(SclBinOp);
871 replaceValue(
I, *NewBO);
877bool VectorCombine::foldBitOpOfCastops(Instruction &
I) {
880 if (!BinOp || !BinOp->isBitwiseLogicOp())
886 if (!LHSCast || !RHSCast) {
887 LLVM_DEBUG(
dbgs() <<
" One or both operands are not cast instructions\n");
893 if (CastOpcode != RHSCast->getOpcode())
897 switch (CastOpcode) {
898 case Instruction::BitCast:
899 case Instruction::Trunc:
900 case Instruction::SExt:
901 case Instruction::ZExt:
907 Value *LHSSrc = LHSCast->getOperand(0);
908 Value *RHSSrc = RHSCast->getOperand(0);
914 auto *SrcTy = LHSSrc->
getType();
915 auto *DstTy =
I.getType();
918 if (CastOpcode != Instruction::BitCast &&
923 if (!SrcTy->getScalarType()->isIntegerTy() ||
924 !DstTy->getScalarType()->isIntegerTy())
939 LHSCastCost + RHSCastCost;
950 if (!LHSCast->hasOneUse())
951 NewCost += LHSCastCost;
952 if (!RHSCast->hasOneUse())
953 NewCost += RHSCastCost;
956 <<
" NewCost=" << NewCost <<
"\n");
958 if (NewCost > OldCost)
963 BinOp->getName() +
".inner");
965 NewBinOp->copyIRFlags(BinOp);
977 replaceValue(
I, *Result);
986bool VectorCombine::foldBitOpOfCastConstant(Instruction &
I) {
1002 switch (CastOpcode) {
1003 case Instruction::BitCast:
1004 case Instruction::ZExt:
1005 case Instruction::SExt:
1006 case Instruction::Trunc:
1012 Value *LHSSrc = LHSCast->getOperand(0);
1014 auto *SrcTy = LHSSrc->
getType();
1015 auto *DstTy =
I.getType();
1018 if (CastOpcode != Instruction::BitCast &&
1023 if (!SrcTy->getScalarType()->isIntegerTy() ||
1024 !DstTy->getScalarType()->isIntegerTy())
1028 PreservedCastFlags RHSFlags;
1053 if (!LHSCast->hasOneUse())
1054 NewCost += LHSCastCost;
1056 LLVM_DEBUG(
dbgs() <<
"foldBitOpOfCastConstant: OldCost=" << OldCost
1057 <<
" NewCost=" << NewCost <<
"\n");
1059 if (NewCost > OldCost)
1064 LHSSrc, InvC,
I.getName() +
".inner");
1066 NewBinOp->copyIRFlags(&
I);
1084 replaceValue(
I, *Result);
1091bool VectorCombine::foldBitcastShuffle(Instruction &
I) {
1105 if (!DestTy || !SrcTy)
1108 unsigned DestEltSize = DestTy->getScalarSizeInBits();
1109 unsigned SrcEltSize = SrcTy->getScalarSizeInBits();
1110 if (SrcTy->getPrimitiveSizeInBits() % DestEltSize != 0)
1120 if (!(BCTy0 && BCTy0->getElementType() == DestTy->getElementType()) &&
1121 !(BCTy1 && BCTy1->getElementType() == DestTy->getElementType()))
1125 SmallVector<int, 16> NewMask;
1126 if (DestEltSize <= SrcEltSize) {
1129 if (SrcEltSize % DestEltSize != 0)
1131 unsigned ScaleFactor = SrcEltSize / DestEltSize;
1136 if (DestEltSize % SrcEltSize != 0)
1138 unsigned ScaleFactor = DestEltSize / SrcEltSize;
1145 unsigned NumSrcElts = SrcTy->getPrimitiveSizeInBits() / DestEltSize;
1146 auto *NewShuffleTy =
1148 auto *OldShuffleTy =
1150 unsigned NumOps = IsUnary ? 1 : 2;
1160 TargetTransformInfo::CastContextHint::None,
1165 TargetTransformInfo::CastContextHint::None,
1168 LLVM_DEBUG(
dbgs() <<
"Found a bitcasted shuffle: " <<
I <<
"\n OldCost: "
1169 << OldCost <<
" vs NewCost: " << NewCost <<
"\n");
1171 if (NewCost > OldCost || !NewCost.
isValid())
1179 replaceValue(
I, *Shuf);
1186bool VectorCombine::scalarizeOpOrCmp(Instruction &
I) {
1191 if (!UO && !BO && !CI && !
II)
1199 if (Arg->getType() !=
II->getType() &&
1209 for (User *U :
I.users())
1216 std::optional<uint64_t>
Index;
1218 auto Ops =
II ?
II->args() :
I.operands();
1227 if (OpTy->getElementCount().getKnownMinValue() <= InsIdx)
1233 else if (InsIdx != *Index)
1250 if (!
Index.has_value())
1254 Type *ScalarTy = VecTy->getScalarType();
1255 assert(VecTy->isVectorTy() &&
1258 "Unexpected types for insert element into binop or cmp");
1260 unsigned Opcode =
I.getOpcode();
1268 }
else if (UO || BO) {
1272 IntrinsicCostAttributes ScalarICA(
1273 II->getIntrinsicID(), ScalarTy,
1276 IntrinsicCostAttributes VectorICA(
1277 II->getIntrinsicID(), VecTy,
1284 Value *NewVecC =
nullptr;
1286 NewVecC =
simplifyCmpInst(CI->getPredicate(), VecCs[0], VecCs[1], SQ);
1289 simplifyUnOp(UO->getOpcode(), VecCs[0], UO->getFastMathFlags(), SQ);
1291 NewVecC =
simplifyBinOp(BO->getOpcode(), VecCs[0], VecCs[1], SQ);
1303 CostKind, *Index, NewVecC);
1305 for (
auto [Idx,
Op, VecC, Scalar] :
enumerate(
Ops, VecCs, ScalarOps)) {
1307 II->getIntrinsicID(), Idx, &
TTI)))
1310 Instruction::InsertElement, VecTy, CostKind, *Index, VecC, Scalar);
1311 OldCost += InsertCost;
1312 NewCost += !
Op->hasOneUse() * InsertCost;
1316 if (OldCost < NewCost || !NewCost.
isValid())
1326 ++NumScalarIntrinsic;
1329 for (
auto [OpIdx, Scalar, VecC] :
enumerate(ScalarOps, VecCs))
1341 ScalarOps[1], FPMO->getFastMathFlags(),
1342 CI->getName() +
".scalar");
1345 ScalarOps[1], CI->getName() +
".scalar");
1349 UO->getName() +
".scalar");
1351 if (OverflowingBinaryOperator *OBO =
1354 BO->getOpcode(), ScalarOps[0], ScalarOps[1], OBO->hasNoUnsignedWrap(),
1355 OBO->hasNoSignedWrap(), BO->getName() +
".scalar");
1358 BO->getName() +
".scalar", PDI->isDisjoint());
1359 }
else if (PossiblyExactOperator *PEO =
1363 PEO->isExact(), BO->getName() +
".scalar");
1366 ScalarOps[1], FPMO->getFastMathFlags(),
1367 BO->getName() +
".scalar");
1370 BO->getName() +
".scalar");
1375 FMF = FPMO->getFastMathFlags();
1377 FMF,
II->getName() +
".scalar");
1381 replaceValue(
I, *Insert);
1388bool VectorCombine::foldExtractedCmps(Instruction &
I) {
1393 if (!BI || !
I.getType()->isIntegerTy(1))
1398 Value *
B0 =
I.getOperand(0), *
B1 =
I.getOperand(1);
1401 CmpPredicate
P0,
P1;
1420 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1, CostKind);
1423 assert((ConvertToShuf == Ext0 || ConvertToShuf == Ext1) &&
1424 "Unknown ExtractElementInst");
1429 unsigned CmpOpcode =
1435 if (Index0 >= VecTy->getNumElements() || Index1 >= VecTy->getNumElements())
1447 Ext0Cost + Ext1Cost + CmpCost * 2 +
1453 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
1454 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
1459 ShufMask[CheapIndex] = ExpensiveIndex;
1461 CmpTy, CostKind, ShufMask);
1464 NewCost += Ext0->
hasOneUse() ? 0 : Ext0Cost;
1465 NewCost += Ext1->
hasOneUse() ? 0 : Ext1Cost;
1470 if (OldCost < NewCost || !NewCost.
isValid())
1480 Value *
LHS = ConvertToShuf == Ext0 ? Shuf : VCmp;
1481 Value *
RHS = ConvertToShuf == Ext0 ? VCmp : Shuf;
1484 replaceValue(
I, *NewExt);
1511bool VectorCombine::foldSelectsFromBitcast(Instruction &
I) {
1518 if (!SrcVecTy || !DstVecTy)
1528 if (SrcEltBits != 32 && SrcEltBits != 64)
1531 if (!DstEltTy->
isIntegerTy() || DstEltBits >= SrcEltBits)
1548 if (!ScalarSelCost.
isValid() || ScalarSelCost == 0)
1551 unsigned MinSelects = (VecSelCost.
getValue() / ScalarSelCost.
getValue()) + 1;
1554 if (!BC->hasNUsesOrMore(MinSelects))
1559 DenseMap<Value *, SmallVector<SelectInst *, 8>> CondToSelects;
1561 for (User *U : BC->users()) {
1566 for (User *ExtUser : Ext->users()) {
1570 Cond->getType()->isIntegerTy(1))
1575 if (CondToSelects.
empty())
1578 bool MadeChange =
false;
1579 Value *SrcVec = BC->getOperand(0);
1582 for (
auto [
Cond, Selects] : CondToSelects) {
1584 if (Selects.size() < MinSelects) {
1585 LLVM_DEBUG(
dbgs() <<
"VectorCombine: foldSelectsFromBitcast not "
1586 <<
"profitable (VecCost=" << VecSelCost
1587 <<
", ScalarCost=" << ScalarSelCost
1588 <<
", NumSelects=" << Selects.size() <<
")\n");
1593 auto InsertPt = std::next(BC->getIterator());
1597 InsertPt = std::next(CondInst->getIterator());
1605 for (SelectInst *Sel : Selects) {
1607 Value *
Idx = Ext->getIndexOperand();
1611 replaceValue(*Sel, *NewExt);
1616 <<
" selects into vector select\n");
1630 unsigned ReductionOpc =
1636 CostBeforeReduction =
1637 TTI.getCastInstrCost(RedOp->getOpcode(), VecRedTy, ExtType,
1639 CostAfterReduction =
1640 TTI.getExtendedReductionCost(ReductionOpc, IsUnsigned,
II.getType(),
1644 if (RedOp &&
II.getIntrinsicID() == Intrinsic::vector_reduce_add &&
1650 (Op0->
getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
1657 TTI.getCastInstrCost(Op0->
getOpcode(), MulType, ExtType,
1660 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
1662 TTI.getCastInstrCost(RedOp->getOpcode(), VecRedTy, MulType,
1665 CostBeforeReduction = ExtCost * 2 + MulCost + Ext2Cost;
1666 CostAfterReduction =
TTI.getMulAccReductionCost(
1667 IsUnsigned, ReductionOpc,
II.getType(), ExtType, CostKind);
1670 CostAfterReduction =
TTI.getArithmeticReductionCost(ReductionOpc, VecRedTy,
1671 std::nullopt, CostKind);
1674bool VectorCombine::foldBinopOfReductions(Instruction &
I) {
1677 if (BinOpOpc == Instruction::Sub)
1678 ReductionIID = Intrinsic::vector_reduce_add;
1682 if (ReductionIID == Intrinsic::vector_reduce_fadd ||
1683 ReductionIID == Intrinsic::vector_reduce_fmul)
1686 auto checkIntrinsicAndGetItsArgument = [](
Value *
V,
1691 if (
II->getIntrinsicID() == IID &&
II->hasOneUse())
1692 return II->getArgOperand(0);
1696 Value *
V0 = checkIntrinsicAndGetItsArgument(
I.getOperand(0), ReductionIID);
1699 Value *
V1 = checkIntrinsicAndGetItsArgument(
I.getOperand(1), ReductionIID);
1704 if (
V1->getType() != VTy)
1708 unsigned ReductionOpc =
1721 CostOfRedOperand0 + CostOfRedOperand1 +
1724 if (NewCost >= OldCost || !NewCost.
isValid())
1728 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
1731 if (BinOpOpc == Instruction::Or)
1738 replaceValue(
I, *Rdx);
1748 unsigned NumScanned = 0;
1751 ++NumScanned > Opts.vector_combine_max_scan_instrs;
1763class ScalarizationResult {
1764 enum class StatusTy { Unsafe,
Safe, SafeWithFreeze };
1769 ScalarizationResult(StatusTy Status,
Value *ToFreeze =
nullptr)
1770 : Status(Status), ToFreeze(ToFreeze) {}
1773 ScalarizationResult(
const ScalarizationResult &
Other) =
default;
1774 ~ScalarizationResult() {
1775 assert(!ToFreeze &&
"freeze() not called with ToFreeze being set");
1778 static ScalarizationResult unsafe() {
return {StatusTy::Unsafe}; }
1779 static ScalarizationResult safe() {
return {StatusTy::Safe}; }
1780 static ScalarizationResult safeWithFreeze(
Value *ToFreeze) {
1781 return {StatusTy::SafeWithFreeze, ToFreeze};
1785 bool isSafe()
const {
return Status == StatusTy::Safe; }
1787 bool isUnsafe()
const {
return Status == StatusTy::Unsafe; }
1790 bool isSafeWithFreeze()
const {
return Status == StatusTy::SafeWithFreeze; }
1795 Status = StatusTy::Unsafe;
1799 void freeze(IRBuilderBase &Builder, Instruction &UserI) {
1800 assert(isSafeWithFreeze() &&
1801 "should only be used when freezing is required");
1803 "UserI must be a user of ToFreeze");
1804 IRBuilder<>::InsertPointGuard Guard(Builder);
1809 if (
U.get() == ToFreeze)
1824 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1825 unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
1828 if (
C->getValue().ult(NumElements))
1829 return ScalarizationResult::safe();
1830 return ScalarizationResult::unsafe();
1835 return ScalarizationResult::unsafe();
1838 APInt MaxElts(IntWidth, NumElements);
1845 return ScalarizationResult::safe();
1846 return ScalarizationResult::unsafe();
1859 if (ValidIndices.
contains(IdxRange))
1860 return ScalarizationResult::safeWithFreeze(IdxBase);
1861 return ScalarizationResult::unsafe();
1881 unsigned GEPBits = GEPIndexTy->getBitWidth();
1882 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1884 uint64_t MaxLane = NumElements - 1;
1886 if (
C->getValue().uge(NumElements))
1888 MaxLane =
C->getZExtValue();
1892 if (!
DL.typeSizeEqualsStoreSize(
ElemTy))
1912 unsigned WideBits = std::max(GEPBits, 128u);
1913 APInt MaxLaneValue(WideBits, MaxLane);
1914 APInt ByteOffset = MaxLaneValue;
1919 if (ByteOffset.
ugt(MaxGEPOffset))
1930 unsigned SrcBits = Idx->getType()->getIntegerBitWidth();
1932 if (SrcBits >= DstBits)
1935 return Builder.CreateZExt(Idx, GEPIndexTy, Idx->getName() +
".gepidx");
1947 C->getZExtValue() *
DL.getTypeStoreSize(ScalarType));
1984bool VectorCombine::foldInsertElementsToStores(Instruction &
I) {
1999 if (!
Insert->hasOneUse())
2007 if (InsertElements.
empty())
2012 std::reverse(InsertElements.
begin(), InsertElements.
end());
2021 if (InsertElements.
size() == FVT->getNumElements()) {
2022 Value *FirstVal = InsertElements.
front().first;
2023 if (
all_of(InsertElements,
2024 [FirstVal](
const auto &Elt) {
return Elt.first == FirstVal; }))
2028 Value *SrcAddr =
Load->getPointerOperand()->stripPointerCasts();
2033 if (!
Load->isSimple() ||
Load->getParent() !=
SI->getParent() ||
2034 !
DL->typeSizeEqualsStoreSize(
Load->getType()->getScalarType()) ||
2035 SrcAddr !=
SI->getPointerOperand()->stripPointerCasts())
2045 for (
auto [InsertVal, Idx] : InsertElements) {
2046 auto ScalarizableIdx =
2048 if (ScalarizableIdx.isUnsafe())
2054 ScalarizableIdx.discard();
2060 ScalarizableIdx.discard();
2064 Instruction::Store,
SI->getValueOperand()->getType(),
SI->getAlign(),
2065 SI->getPointerAddressSpace(), CostKind);
2067 if (
Load->hasOneUse())
2070 Load->getPointerAddressSpace(), CostKind);
2072 for (
auto [InsertVal, Idx] : InsertElements) {
2075 Index = CIdx->getZExtValue();
2086 for (
auto [InsertVal, Idx] : InsertElements) {
2089 const Value *GEPIndices[] = {ConstantInt::get(
Idx->getType(), 0),
Idx};
2091 CostKind, InsertVal->
getType());
2094 for (
auto [InsertVal, Idx] : InsertElements) {
2096 std::max(
SI->getAlign(),
Load->getAlign()), InsertVal->
getType(), Idx,
2101 SI->getPointerAddressSpace(), CostKind);
2104 LLVM_DEBUG(
dbgs() <<
"Found an insert-elements vector store scalarization "
2107 <<
" NumInserts: " << InsertElements.size() <<
"\n"
2108 <<
" OldCost: " << OldCost <<
" vs NewCost: " << NewCost
2111 if (OldCost <= NewCost)
2114 for (
auto [InsertVal, Idx] : InsertElements) {
2115 auto ScalarizableIdx =
2117 assert(!ScalarizableIdx.isUnsafe() &&
"already checked above");
2119 if (ScalarizableIdx.isSafeWithFreeze())
2124 StoreInst *LastStore =
nullptr;
2125 for (
auto [InsertVal, Idx] : InsertElements) {
2126 auto ScalarizableIdx =
2128 if (ScalarizableIdx.isUnsafe())
2131 IntegerType *GEPIndexTy =
2136 SI->getValueOperand()->getType(),
SI->getPointerOperand(),
2137 {ConstantInt::get(GEPIdx->getType(), 0), GEPIdx});
2144 LastStore->
setMetadata(LLVMContext::MD_invariant_group,
nullptr);
2146 std::max(
SI->getAlign(),
Load->getAlign()), InsertVal->
getType(), Idx,
2151 replaceValue(
I, *LastStore);
2158bool VectorCombine::scalarizeLoad(Instruction &
I) {
2168 if (!LI->isSimple() || !
DL->typeSizeEqualsStoreSize(VecTy->getScalarType()))
2171 bool AllExtracts =
true;
2172 bool AllBitcasts =
true;
2174 unsigned NumInstChecked = 0;
2179 for (User *U : LI->users()) {
2181 if (!UI || UI->getParent() != LI->getParent())
2186 if (UI->use_empty())
2190 AllExtracts =
false;
2192 AllBitcasts =
false;
2196 for (Instruction &
I :
2197 make_range(std::next(LI->getIterator()), UI->getIterator())) {
2200 if (NumInstChecked == Opts.vector_combine_max_scan_instrs ||
2201 I.mayWriteToMemory())
2205 LastCheckedInst = UI;
2210 return scalarizeLoadExtract(LI, VecTy, Ptr);
2212 return scalarizeLoadBitcast(LI, VecTy, Ptr);
2217bool VectorCombine::scalarizeLoadExtract(LoadInst *LI, VectorType *VecTy,
2222 DenseMap<ExtractElementInst *, ScalarizationResult> NeedFreeze;
2223 DenseMap<ExtractElementInst *, IntegerType *> GEPIndexInfos;
2226 for (
auto &Pair : NeedFreeze)
2227 Pair.second.discard();
2235 for (User *U : LI->
users()) {
2240 if (ScalarIdx.isUnsafe())
2246 ScalarIdx.discard();
2252 if (ScalarIdx.isSafeWithFreeze()) {
2253 NeedFreeze.try_emplace(UI, ScalarIdx);
2254 ScalarIdx.discard();
2260 Index ?
Index->getZExtValue() : -1);
2265 nullptr,
nullptr, CostKind);
2266 if (!Index && UI->getIndexOperand()->getType()->getIntegerBitWidth() <
2269 Instruction::ZExt, GEPIndex, UI->getIndexOperand()->getType(),
2273 LLVM_DEBUG(
dbgs() <<
"Found all extractions of a vector load: " << *LI
2274 <<
"\n LoadExtractCost: " << OriginalCost
2275 <<
" vs ScalarizedCost: " << ScalarizedCost <<
"\n");
2277 if (ScalarizedCost > OriginalCost)
2279 if (ScalarizedCost == OriginalCost && !LI->
hasOneUse())
2286 Type *ElemType = VecTy->getElementType();
2289 for (User *U : LI->
users()) {
2291 Value *
Idx = EI->getIndexOperand();
2294 if (
auto It = NeedFreeze.find(EI); It != NeedFreeze.end())
2298 auto It = GEPIndexInfos.
find(EI);
2300 "Missing scalarized GEP index information");
2303 VecTy, Ptr, {ConstantInt::get(GEPIdx->
getType(), 0), GEPIdx});
2305 Builder.
CreateLoad(ElemType,
GEP, EI->getName() +
".scalar"));
2307 Align ScalarOpAlignment =
2309 NewLoad->setAlignment(ScalarOpAlignment);
2310 NewLoad->copyMetadata(*LI,
2311 {LLVMContext::MD_mmra, LLVMContext::MD_nontemporal,
2312 LLVMContext::MD_mem_cache_hint});
2315 size_t Offset = ConstIdx->getZExtValue() *
DL->getTypeStoreSize(ElemType);
2320 replaceValue(*EI, *NewLoad,
false);
2323 FailureGuard.release();
2328bool VectorCombine::scalarizeLoadBitcast(LoadInst *LI, VectorType *VecTy,
2337 Type *TargetScalarType =
nullptr;
2338 unsigned VecBitWidth =
DL->getTypeSizeInBits(VecTy);
2340 for (User *U : LI->
users()) {
2343 Type *DestTy = BC->getDestTy();
2347 unsigned DestBitWidth =
DL->getTypeSizeInBits(DestTy);
2348 if (DestBitWidth != VecBitWidth)
2352 if (!TargetScalarType)
2353 TargetScalarType = DestTy;
2354 else if (TargetScalarType != DestTy)
2362 if (!TargetScalarType)
2370 LLVM_DEBUG(
dbgs() <<
"Found vector load feeding only bitcasts: " << *LI
2371 <<
"\n OriginalCost: " << OriginalCost
2372 <<
" vs ScalarizedCost: " << ScalarizedCost <<
"\n");
2374 if (ScalarizedCost >= OriginalCost)
2385 ScalarLoad->copyMetadata(*LI);
2388 for (User *U : LI->
users()) {
2390 replaceValue(*BC, *ScalarLoad,
false);
2396bool VectorCombine::scalarizeExtExtract(Instruction &
I) {
2411 Type *ScalarDstTy = DstTy->getElementType();
2412 if (
DL->getTypeSizeInBits(SrcTy) !=
DL->getTypeSizeInBits(ScalarDstTy))
2418 unsigned ExtCnt = 0;
2419 bool ExtLane0 =
false;
2420 for (User *U : Ext->users()) {
2426 if (Idx >= SrcTy->getNumElements())
2438 Instruction::And, ScalarDstTy, CostKind,
2441 (ExtCnt - ExtLane0) *
2443 Instruction::LShr, ScalarDstTy, CostKind,
2446 if (ScalarCost > VectorCost)
2449 Value *ScalarV = Ext->getOperand(0);
2456 SmallDenseSet<ConstantInt *, 8> ExtractedLanes;
2457 bool AllExtractsTriggerUB =
true;
2458 ExtractElementInst *LastExtract =
nullptr;
2460 for (User *U : Ext->users()) {
2463 AllExtractsTriggerUB =
false;
2467 if (!LastExtract || LastExtract->
comesBefore(Extract))
2468 LastExtract = Extract;
2470 if (ExtractedLanes.
size() != DstTy->getNumElements() ||
2471 !AllExtractsTriggerUB ||
2479 uint64_t SrcEltSizeInBits =
DL->getTypeSizeInBits(SrcTy->getElementType());
2480 uint64_t TotalBits =
DL->getTypeSizeInBits(SrcTy);
2483 Value *
Mask = ConstantInt::get(PackedTy, EltBitMask);
2484 for (User *U : Ext->users()) {
2490 ? (TotalBits - SrcEltSizeInBits -
Idx * SrcEltSizeInBits)
2491 : (
Idx * SrcEltSizeInBits);
2494 U->replaceAllUsesWith(
And);
2502bool VectorCombine::foldConcatOfBoolMasks(Instruction &
I) {
2503 Type *Ty =
I.getType();
2508 if (
DL->isBigEndian())
2535 if (ShAmtX > ShAmtY) {
2543 uint64_t ShAmtDiff = ShAmtY - ShAmtX;
2544 unsigned NumSHL = (ShAmtX > 0) + (ShAmtY > 0);
2549 MaskTy->getNumElements() != ShAmtDiff ||
2550 MaskTy->getNumElements() > (
BitWidth / 2))
2555 Type::getIntNTy(Ty->
getContext(), ConcatTy->getNumElements());
2556 auto *MaskIntTy = Type::getIntNTy(Ty->
getContext(), ShAmtDiff);
2559 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
2573 MaskTy, CostKind, ConcatMask);
2576 if (Ty != ConcatIntTy)
2582 LLVM_DEBUG(
dbgs() <<
"Found a concatenation of bitcasted bool masks: " <<
I
2583 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
2586 if (NewCost > OldCost)
2595 if (Ty != ConcatIntTy) {
2603 replaceValue(
I, *Result);
2609bool VectorCombine::foldPermuteOfBinops(Instruction &
I) {
2610 BinaryOperator *BinOp;
2611 ArrayRef<int> OuterMask;
2619 Value *Op00, *Op01, *Op10, *Op11;
2620 ArrayRef<int> Mask0, Mask1;
2625 if (!Match0 && !Match1)
2638 if (!ShuffleDstTy || !BinOpTy || !Op0Ty || !Op1Ty)
2641 unsigned NumSrcElts = BinOpTy->getNumElements();
2646 any_of(OuterMask, [NumSrcElts](
int M) {
return M >= (int)NumSrcElts; }))
2650 SmallVector<int> NewMask0, NewMask1;
2651 for (
int M : OuterMask) {
2652 if (M < 0 || M >= (
int)NumSrcElts) {
2656 NewMask0.
push_back(Match0 ? Mask0[M] : M);
2657 NewMask1.
push_back(Match1 ? Mask1[M] : M);
2661 unsigned NumOpElts = Op0Ty->getNumElements();
2662 bool IsIdentity0 = ShuffleDstTy == Op0Ty &&
2663 all_of(NewMask0, [NumOpElts](
int M) {
return M < (int)NumOpElts; }) &&
2665 bool IsIdentity1 = ShuffleDstTy == Op1Ty &&
2666 all_of(NewMask1, [NumOpElts](
int M) {
return M < (int)NumOpElts; }) &&
2675 ShuffleDstTy, BinOpTy, CostKind, OuterMask,
2676 0,
nullptr, {BinOp}, &
I);
2678 NewCost += BinOpCost;
2684 OldCost += Shuf0Cost;
2686 NewCost += Shuf0Cost;
2692 OldCost += Shuf1Cost;
2694 NewCost += Shuf1Cost;
2702 Op0Ty, CostKind, NewMask0, 0,
nullptr, {Op00, Op01});
2706 Op1Ty, CostKind, NewMask1, 0,
nullptr, {Op10, Op11});
2708 LLVM_DEBUG(
dbgs() <<
"Found a shuffle feeding a shuffled binop: " <<
I
2709 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
2713 if (NewCost > OldCost)
2724 NewInst->copyIRFlags(BinOp);
2726 replaceValue(
I, *NewBO);
2732bool VectorCombine::foldShuffleOfBinops(Instruction &
I) {
2733 ArrayRef<int> OldMask;
2740 if (
LHS->getOpcode() !=
RHS->getOpcode())
2744 bool IsCommutative =
false;
2753 IsCommutative = BinaryOperator::isCommutative(BO->getOpcode());
2764 if (!ShuffleDstTy || !BinResTy || !BinOpTy ||
X->getType() !=
Z->getType())
2767 bool SameBinOp =
LHS ==
RHS;
2768 unsigned NumSrcElts = BinOpTy->getNumElements();
2771 if (IsCommutative &&
X != Z &&
Y != W && (
X == W ||
Y == Z))
2774 auto ConvertToUnary = [NumSrcElts](
int &
M) {
2775 if (M >= (
int)NumSrcElts)
2779 SmallVector<int> NewMask0(OldMask);
2788 SmallVector<int> NewMask1(OldMask);
2807 ShuffleDstTy, BinResTy, CostKind, OldMask, 0,
2818 ArrayRef<int> InnerMask;
2820 m_Mask(InnerMask)))) &&
2823 [NumSrcElts](
int M) {
return M < (int)NumSrcElts; })) {
2838 bool ReducedInstCount =
false;
2839 ReducedInstCount |= MergeInner(
X, 0, NewMask0, CostKind,
LHS);
2840 ReducedInstCount |= MergeInner(
Y, 0, NewMask1, CostKind,
LHS);
2841 ReducedInstCount |= MergeInner(Z, NumSrcElts, NewMask0, CostKind,
RHS);
2842 ReducedInstCount |= MergeInner(W, NumSrcElts, NewMask1, CostKind,
RHS);
2843 bool SingleSrcBinOp = (
X ==
Y) && (Z == W) && (NewMask0 == NewMask1);
2855 I.getType()->getScalarType()->isIntegerTy(1) &&
2859 auto *ShuffleCmpTy =
2862 SK0, ShuffleCmpTy, BinOpTy, CostKind, NewMask0, 0,
nullptr, {
X,
Z});
2863 if (!SingleSrcBinOp)
2865 NewMask1, 0,
nullptr, {
Y,
W});
2869 CostKind, Op0Info, Op1Info);
2873 PredLHS, CostKind, Op0Info, Op1Info);
2883 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
2890 if (ReducedInstCount ? (NewCost > OldCost) : (NewCost >= OldCost))
2899 : Builder.
CreateCmp(PredLHS, Shuf0, Shuf1);
2903 NewInst->copyIRFlags(
LHS);
2904 NewInst->andIRFlags(
RHS);
2907 replaceValue(
I, *NewBO);
2914bool VectorCombine::foldShuffleOfSelects(Instruction &
I) {
2927 if (!C1VecTy || !C2VecTy || C1VecTy != C2VecTy)
2933 if (((SI0FOp ==
nullptr) != (SI1FOp ==
nullptr)) ||
2934 ((SI0FOp !=
nullptr) &&
2935 (SI0FOp->getFastMathFlags() != SI1FOp->getFastMathFlags())))
2941 auto SelOp = Instruction::Select;
2949 CostSel1 + CostSel2 +
2951 {
I.getOperand(0),
I.getOperand(1)}, &
I);
2955 CostKind, Mask, 0,
nullptr, {C1, C2});
2965 if (!Sel1->hasOneUse())
2966 NewCost += CostSel1;
2967 if (!Sel2->hasOneUse())
2968 NewCost += CostSel2;
2971 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
2973 if (NewCost > OldCost)
2982 NewSel = Builder.
CreateSelectFMF(ShuffleCmp, ShuffleTrue, ShuffleFalse,
2983 SI0FOp->getFastMathFlags());
2985 NewSel = Builder.
CreateSelect(ShuffleCmp, ShuffleTrue, ShuffleFalse);
2987 replaceValue(
I, *NewSel);
2993bool VectorCombine::foldShuffleOfCastops(Instruction &
I) {
2995 ArrayRef<int> OldMask;
3004 if (!
C0 || (IsBinaryShuffle && !
C1))
3011 if (!IsBinaryShuffle && Opcode == Instruction::BitCast)
3014 if (IsBinaryShuffle) {
3015 if (
C0->getSrcTy() !=
C1->getSrcTy())
3018 if (Opcode !=
C1->getOpcode()) {
3020 Opcode = Instruction::SExt;
3029 if (!ShuffleDstTy || !CastDstTy || !CastSrcTy)
3032 unsigned NumSrcElts = CastSrcTy->getNumElements();
3033 unsigned NumDstElts = CastDstTy->getNumElements();
3034 assert((NumDstElts == NumSrcElts || Opcode == Instruction::BitCast) &&
3035 "Only bitcasts expected to alter src/dst element counts");
3039 if (NumDstElts != NumSrcElts && (NumSrcElts % NumDstElts) != 0 &&
3040 (NumDstElts % NumSrcElts) != 0)
3043 SmallVector<int, 16> NewMask;
3044 if (NumSrcElts >= NumDstElts) {
3047 assert(NumSrcElts % NumDstElts == 0 &&
"Unexpected shuffle mask");
3048 unsigned ScaleFactor = NumSrcElts / NumDstElts;
3053 assert(NumDstElts % NumSrcElts == 0 &&
"Unexpected shuffle mask");
3054 unsigned ScaleFactor = NumDstElts / NumSrcElts;
3059 auto *NewShuffleDstTy =
3068 if (IsBinaryShuffle)
3075 OldMask, 0,
nullptr, {}, &
I);
3078 CastSrcTy, CostKind, NewMask);
3081 if (!
C0->hasOneUse())
3083 if (IsBinaryShuffle) {
3088 if (!
C1->hasOneUse())
3093 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
3095 if (NewCost > OldCost)
3099 if (IsBinaryShuffle)
3109 NewInst->copyIRFlags(
C0);
3110 if (IsBinaryShuffle)
3111 NewInst->andIRFlags(
C1);
3114 replaceValue(
I, *Cast);
3124bool VectorCombine::foldShuffleOfShuffles(Instruction &
I) {
3125 ArrayRef<int> OuterMask;
3126 Value *OuterV0, *OuterV1;
3131 ArrayRef<int> InnerMask0, InnerMask1;
3132 Value *X0, *X1, *Y0, *Y1;
3137 if (!Match0 && !Match1)
3142 SmallVector<int, 16> PoisonMask1;
3147 InnerMask1 = PoisonMask1;
3151 X0 = Match0 ? X0 : OuterV0;
3152 Y0 = Match0 ? Y0 : OuterV0;
3153 X1 = Match1 ? X1 : OuterV1;
3154 Y1 = Match1 ? Y1 : OuterV1;
3158 if (!ShuffleDstTy || !ShuffleSrcTy || !ShuffleImmTy ||
3162 unsigned NumSrcElts = ShuffleSrcTy->getNumElements();
3163 unsigned NumImmElts = ShuffleImmTy->getNumElements();
3168 SmallVector<int, 16> NewMask(OuterMask);
3169 Value *NewX =
nullptr, *NewY =
nullptr;
3170 for (
int &M : NewMask) {
3171 Value *Src =
nullptr;
3172 if (0 <= M && M < (
int)NumImmElts) {
3176 Src =
M >= (int)NumSrcElts ? Y0 : X0;
3177 M =
M >= (int)NumSrcElts ? (M - NumSrcElts) :
M;
3179 }
else if (M >= (
int)NumImmElts) {
3184 Src =
M >= (int)NumSrcElts ? Y1 : X1;
3185 M =
M >= (int)NumSrcElts ? (M - NumSrcElts) :
M;
3189 assert(0 <= M && M < (
int)NumSrcElts &&
"Unexpected shuffle mask index");
3198 if (!NewX || NewX == Src) {
3202 if (!NewY || NewY == Src) {
3221 replaceValue(
I, *NewX);
3238 bool IsUnary =
all_of(NewMask, [&](
int M) {
return M < (int)NumSrcElts; });
3244 nullptr, {NewX, NewY});
3246 NewCost += InnerCost0;
3248 NewCost += InnerCost1;
3251 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
3253 if (NewCost > OldCost)
3257 replaceValue(
I, *Shuf);
3273bool VectorCombine::foldShufflesOfLengthChangingShuffles(Instruction &
I) {
3278 unsigned ChainLength = 0;
3279 SmallVector<int>
Mask;
3280 SmallVector<int> YMask;
3290 ArrayRef<int> OuterMask;
3291 Value *OuterV0, *OuterV1;
3292 if (ChainLength != 0 && !Trunk->
hasOneUse())
3295 m_Mask(OuterMask))))
3297 if (OuterV0->
getType() != TrunkType) {
3303 ArrayRef<int> InnerMask0, InnerMask1;
3309 bool Match0Leaf = Match0 && A0->
getType() !=
I.getType();
3310 bool Match1Leaf = Match1 && A1->
getType() !=
I.getType();
3311 if (Match0Leaf == Match1Leaf) {
3317 SmallVector<int> CommutedOuterMask;
3324 for (
int &M : CommutedOuterMask) {
3327 if (M < (
int)NumTrunkElts)
3332 OuterMask = CommutedOuterMask;
3351 int NumLeafElts = YType->getNumElements();
3352 SmallVector<int> LocalYMask(InnerMask1);
3353 for (
int &M : LocalYMask) {
3354 if (M >= NumLeafElts)
3364 Mask.assign(OuterMask);
3365 YMask.
assign(LocalYMask);
3366 OldCost = NewCost = LocalOldCost;
3373 SmallVector<int> NewYMask(YMask);
3375 for (
auto [CombinedM, LeafM] :
llvm::zip(NewYMask, LocalYMask)) {
3376 if (LeafM == -1 || CombinedM == LeafM)
3378 if (CombinedM == -1) {
3388 SmallVector<int> NewMask;
3389 NewMask.
reserve(NumTrunkElts);
3390 for (
int M : Mask) {
3391 if (M < 0 || M >=
static_cast<int>(NumTrunkElts))
3402 YType, CostKind, NewYMask) +
3404 TrunkType, CostKind, NewMask);
3406 if (LocalNewCost >= NewCost && LocalOldCost < LocalNewCost - NewCost)
3410 if (ChainLength == 1) {
3411 dbgs() <<
"Found chain of shuffles fed by length-changing shuffles: "
3414 dbgs() <<
" next chain link: " << *Trunk <<
'\n'
3415 <<
" old cost: " << (OldCost + LocalOldCost)
3416 <<
" new cost: " << LocalNewCost <<
'\n';
3421 OldCost += LocalOldCost;
3422 NewCost = LocalNewCost;
3426 if (ChainLength <= 1)
3434 return M < 0 || M >=
static_cast<int>(NumTrunkElts);
3437 for (
int &M : Mask) {
3438 if (M >=
static_cast<int>(NumTrunkElts))
3439 M = YMask[
M - NumTrunkElts];
3443 replaceValue(
I, *Root);
3450 replaceValue(
I, *Root);
3456bool VectorCombine::foldShuffleOfIntrinsics(Instruction &
I) {
3458 ArrayRef<int> OldMask;
3468 if (IID != II1->getIntrinsicID())
3477 if (!ShuffleDstTy || !II0Ty)
3483 for (
unsigned Idx = 0,
E = II0->arg_size(); Idx !=
E; ++Idx) {
3484 Value *Arg0 = II0->getArgOperand(Idx);
3485 Value *Arg1 = II1->getArgOperand(Idx);
3502 II0Ty, CostKind, OldMask, 0,
nullptr, {II0, II1}, &
I);
3506 SmallDenseSet<std::pair<Value *, Value *>> SeenOperandPairs;
3507 for (
unsigned Idx = 0,
E = II0->arg_size(); Idx !=
E; ++Idx) {
3509 NewArgsTy.
push_back(II0->getArgOperand(Idx)->getType());
3513 ShuffleDstTy->getNumElements());
3515 std::pair<Value *, Value *> OperandPair =
3516 std::make_pair(II0->getArgOperand(Idx), II1->getArgOperand(Idx));
3517 if (!SeenOperandPairs.
insert(OperandPair).second) {
3523 OldMask, 0,
nullptr,
3524 {II0->getArgOperand(Idx), II1->getArgOperand(Idx)});
3527 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy);
3530 if (!II0->hasOneUse())
3532 if (II1 != II0 && !II1->hasOneUse())
3536 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
3539 if (NewCost > OldCost)
3543 SmallDenseMap<std::pair<Value *, Value *>,
Value *> ShuffleCache;
3544 for (
unsigned Idx = 0,
E = II0->arg_size(); Idx !=
E; ++Idx) {
3546 NewArgs.
push_back(II0->getArgOperand(Idx));
3548 std::pair<Value *, Value *> OperandPair =
3549 std::make_pair(II0->getArgOperand(Idx), II1->getArgOperand(Idx));
3550 auto It = ShuffleCache.
find(OperandPair);
3551 if (It != ShuffleCache.
end()) {
3557 II0->getArgOperand(Idx), II1->getArgOperand(Idx), OldMask);
3558 ShuffleCache[OperandPair] = Shuf;
3566 NewInst->copyIRFlags(II0);
3567 NewInst->andIRFlags(II1);
3570 replaceValue(
I, *NewIntrinsic);
3576bool VectorCombine::foldPermuteOfIntrinsic(Instruction &
I) {
3588 if (!ShuffleDstTy || !IntrinsicSrcTy)
3592 unsigned NumSrcElts = IntrinsicSrcTy->getNumElements();
3593 if (
any_of(Mask, [NumSrcElts](
int M) {
return M >= (int)NumSrcElts; }))
3606 IntrinsicSrcTy, CostKind, Mask, 0,
nullptr, {
V0}, &
I);
3610 for (
unsigned I = 0,
E = II0->arg_size();
I !=
E; ++
I) {
3612 NewArgsTy.
push_back(II0->getArgOperand(
I)->getType());
3616 ShuffleDstTy->getNumElements());
3619 ArgTy, VecTy, CostKind, Mask, 0,
nullptr,
3620 {II0->getArgOperand(
I)});
3623 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy);
3628 if (!II0->hasOneUse())
3631 LLVM_DEBUG(
dbgs() <<
"Found a permute of intrinsic: " <<
I <<
"\n OldCost: "
3632 << OldCost <<
" vs NewCost: " << NewCost <<
"\n");
3634 if (NewCost > OldCost)
3639 for (
unsigned I = 0,
E = II0->arg_size();
I !=
E; ++
I) {
3651 NewInst->copyIRFlags(II0);
3653 replaceValue(
I, *NewIntrinsic);
3663 int M = SV->getMaskValue(Lane);
3666 if (
static_cast<unsigned>(M) < NumElts) {
3667 V = SV->getOperand(0);
3670 V = SV->getOperand(1);
3681 auto [U, Lane] = IL;
3694 unsigned NumElts = Ty->getNumElements();
3695 if (Item.
size() == NumElts || NumElts == 1 || Item.
size() % NumElts != 0)
3701 std::iota(ConcatMask.
begin(), ConcatMask.
end(), 0);
3704 Ty, CostKind, ConcatMask) != 0)
3707 unsigned NumSlices = Item.
size() / NumElts;
3712 for (
unsigned Slice = 0; Slice < NumSlices; ++Slice) {
3713 Value *SliceV = Item[Slice * NumElts].first;
3714 if (!SliceV || SliceV->
getType() != Ty)
3716 for (
unsigned Elt = 0; Elt < NumElts; ++Elt) {
3717 auto [
V, Lane] = Item[Slice * NumElts + Elt];
3718 if (Lane !=
static_cast<int>(Elt) || SliceV !=
V)
3727 const DenseSet<std::pair<Value *, Use *>> &IdentityLeafs,
3728 const DenseSet<std::pair<Value *, Use *>> &SplatLeafs,
3729 const DenseSet<std::pair<Value *, Use *>> &ConcatLeafs,
3732 auto [FrontV, FrontLane] = Item.
front();
3734 if (IdentityLeafs.contains(std::make_pair(FrontV, From))) {
3737 if (SplatLeafs.contains(std::make_pair(FrontV, From))) {
3739 return Builder.CreateShuffleVector(FrontV, Mask);
3741 if (ConcatLeafs.contains(std::make_pair(FrontV, From))) {
3745 for (
unsigned S = 0; S <
Values.size(); ++S)
3746 Values[S] = Item[S * NumElts].first;
3748 while (
Values.size() > 1) {
3751 std::iota(Mask.begin(), Mask.end(), 0);
3753 for (
unsigned S = 0; S < NewValues.
size(); ++S)
3755 Builder.CreateShuffleVector(
Values[S * 2],
Values[S * 2 + 1], Mask);
3769 if (BCDstTy && BCSrcTy &&
3770 BCDstTy->getElementCount() != BCSrcTy->getElementCount()) {
3771 unsigned DstElts = BCDstTy->getNumElements();
3772 unsigned SrcElts = BCSrcTy->getNumElements();
3774 if (DstElts > SrcElts) {
3776 unsigned R = DstElts / SrcElts;
3777 if (Item.
size() % R != 0)
3779 for (
unsigned Idx = 0,
E = Item.
size(); Idx <
E; Idx += R) {
3780 auto [
V, Lane] = Item[Idx];
3790 unsigned R = SrcElts / DstElts;
3791 for (
auto [
V, Lane] : Item) {
3797 for (
unsigned J = 0; J < R; ++J)
3802 IdentityLeafs, SplatLeafs, ConcatLeafs,
3803 Builder, WorkList,
TTI);
3804 return Builder.CreateBitCast(
3809 unsigned NumOps =
I->getNumOperands() - (
II ? 1 : 0);
3811 for (
unsigned Idx = 0; Idx <
NumOps; Idx++) {
3814 Ops[Idx] =
II->getOperand(Idx);
3819 IdentityLeafs, SplatLeafs, ConcatLeafs, Builder, WorkList,
TTI);
3831 for (
const auto &Lane : Item)
3844 auto *
Value = Builder.CreateCmp(CI->getPredicate(),
Ops[0],
Ops[1]);
3854 auto *
Value = Builder.CreateCast(CI->getOpcode(),
Ops[0], DstTy);
3859 auto *
Value = Builder.CreateIntrinsic(DstTy,
II->getIntrinsicID(),
Ops);
3873bool VectorCombine::foldShuffleToIdentity(Instruction &
I) {
3875 if (!Ty ||
I.use_empty())
3879 for (
unsigned M = 0,
E = Ty->getNumElements(); M <
E; ++M)
3883 Candidates.
push_back(std::make_pair(Start, &*
I.use_begin()));
3884 DenseSet<std::pair<Value *, Use *>> IdentityLeafs, SplatLeafs, ConcatLeafs;
3885 unsigned NumVisited = 0;
3886 bool TraversedElCountChangingBitcast =
false;
3888 while (!Candidates.
empty()) {
3889 if (++NumVisited > Opts.vector_combine_max_scan_instrs)
3893 auto Item = ItemFrom.first;
3894 auto From = ItemFrom.second;
3895 auto [FrontV, FrontLane] = Item.front();
3902 if (FrontLane == 0 &&
3906 Value *FrontV = Item.front().first;
3908 E.value().second == (int)
E.index());
3910 IdentityLeafs.
insert(std::make_pair(FrontV, From));
3915 C &&
C->getSplatValue() &&
3917 Value *FrontV = Item.front().first;
3923 SplatLeafs.
insert(std::make_pair(FrontV, From));
3928 auto [FrontV, FrontLane] = Item.front();
3929 auto [
V, Lane] = IL;
3930 return !
V || (
V == FrontV && Lane == FrontLane);
3932 SplatLeafs.
insert(std::make_pair(FrontV, From));
3938 auto CheckLaneIsEquivalentToFirst = [Item](
InstLane IL) {
3939 Value *FrontV = Item.front().first;
3948 if (CI->getPredicate() !=
cast<CmpInst>(FrontV)->getPredicate())
3951 if (CI->getSrcTy()->getScalarType() !=
3956 SI->getOperand(0)->getType() !=
3963 II->getIntrinsicID() ==
3965 !
II->hasOperandBundles());
3972 BO && BO->isIntDivRem())
3979 }
else if (
isa<UnaryOperator, TruncInst, ZExtInst, SExtInst, FPToSIInst,
3980 FPToUIInst, SIToFPInst, UIToFPInst>(FrontV)) {
3987 if (BCDstTy && BCSrcTy) {
3988 ElementCount DstEC = BCDstTy->getElementCount();
3989 ElementCount SrcEC = BCSrcTy->getElementCount();
3990 if (DstEC == SrcEC) {
3993 &BitCast->getOperandUse(0));
3998 if (DstElts > SrcElts && DstElts % SrcElts == 0) {
4002 unsigned R = DstElts / SrcElts;
4004 bool Valid = Item.size() %
R == 0;
4005 for (
unsigned Idx = 0,
E = Item.size(); Valid && Idx <
E;
4007 auto [
V0, L0] = Item[
Idx];
4010 [](
InstLane IL) {
return IL.first !=
nullptr; })) {
4021 for (
unsigned J = 1; J <
R; ++J) {
4022 auto [VJ, LJ] = Item[
Idx + J];
4023 if (!VJ || VJ != V0 || LJ != L0 + (
int)J) {
4034 TraversedElCountChangingBitcast =
true;
4035 Candidates.
emplace_back(NItem, &BitCast->getOperandUse(0));
4038 }
else if (SrcElts > DstElts && SrcElts % DstElts == 0) {
4041 unsigned R = SrcElts / DstElts;
4043 for (
auto [
V, Lane] : Item) {
4049 for (
unsigned J = 0; J <
R; ++J)
4052 TraversedElCountChangingBitcast =
true;
4053 Candidates.
emplace_back(NItem, &BitCast->getOperandUse(0));
4059 &Sel->getOperandUse(0));
4061 &Sel->getOperandUse(1));
4063 &Sel->getOperandUse(2));
4067 !
II->hasOperandBundles()) {
4068 for (
unsigned Op = 0,
E =
II->getNumOperands() - 1;
Op <
E;
Op++) {
4072 Value *FrontV = Item.front().first;
4089 ConcatLeafs.
insert(std::make_pair(FrontV, From));
4096 if (NumVisited <= 1)
4102 if (NumVisited == 2 && TraversedElCountChangingBitcast)
4105 LLVM_DEBUG(
dbgs() <<
"Found a superfluous identity shuffle: " <<
I <<
"\n");
4112 ConcatLeafs, Builder, Worklist, &
TTI);
4113 replaceValue(
I, *
V);
4120bool VectorCombine::foldShuffleFromReductions(Instruction &
I) {
4124 switch (
II->getIntrinsicID()) {
4125 case Intrinsic::vector_reduce_add:
4126 case Intrinsic::vector_reduce_mul:
4127 case Intrinsic::vector_reduce_and:
4128 case Intrinsic::vector_reduce_or:
4129 case Intrinsic::vector_reduce_xor:
4130 case Intrinsic::vector_reduce_smin:
4131 case Intrinsic::vector_reduce_smax:
4132 case Intrinsic::vector_reduce_umin:
4133 case Intrinsic::vector_reduce_umax:
4142 std::queue<Value *> Worklist;
4143 SmallPtrSet<Value *, 4> Visited;
4144 ShuffleVectorInst *Shuffle =
nullptr;
4148 while (!Worklist.empty()) {
4149 Value *CV = Worklist.front();
4161 if (CI->isBinaryOp()) {
4162 for (
auto *
Op : CI->operand_values())
4166 if (Shuffle && Shuffle != SV)
4183 for (
auto *
V : Visited)
4184 for (
auto *U :
V->users())
4185 if (!Visited.contains(U) && U != &
I)
4188 FixedVectorType *VecType =
4192 FixedVectorType *ShuffleInputType =
4194 if (!ShuffleInputType)
4200 SmallVector<int> ConcatMask;
4202 sort(ConcatMask, [](
int X,
int Y) {
return (
unsigned)
X < (unsigned)
Y; });
4203 bool UsesSecondVec =
4204 any_of(ConcatMask, [&](
int M) {
return M >= (int)NumInputElts; });
4211 ShuffleInputType, CostKind, ConcatMask);
4213 LLVM_DEBUG(
dbgs() <<
"Found a reduction feeding from a shuffle: " << *Shuffle
4215 LLVM_DEBUG(
dbgs() <<
" OldCost: " << OldCost <<
" vs NewCost: " << NewCost
4217 bool MadeChanges =
false;
4218 if (NewCost < OldCost) {
4222 LLVM_DEBUG(
dbgs() <<
"Created new shuffle: " << *NewShuffle <<
"\n");
4223 replaceValue(*Shuffle, *NewShuffle);
4229 MadeChanges |= foldSelectShuffle(*Shuffle,
true);
4250bool VectorCombine::foldShuffleChainsToReduce(Instruction &
I) {
4259 if (FVT->getNumElements() < 2)
4262 std::optional<Instruction::BinaryOps> CommonBinOp;
4263 std::optional<Intrinsic::ID> CommonCallOp;
4268 CommonBinOp = BO->getOpcode();
4270 CommonCallOp = MMI->getIntrinsicID();
4276 FastMathFlags CommonFMF;
4277 bool IsFloatReduction =
false;
4281 auto IsChainNode = [&](
Value *
V) {
4283 return CommonBinOp && BO->getOpcode() == *CommonBinOp;
4285 return CommonCallOp && MMI->getIntrinsicID() == *CommonCallOp;
4293 constexpr unsigned MaxChainNodes = 32;
4294 SmallSetVector<Value *, 16> Nodes;
4295 SmallSetVector<Value *, 4> Sources;
4296 unsigned NumVisited = 0;
4297 auto AddSource = [&](
Value *
V) {
4303 auto Walk = [&](
Value *
V,
auto &&Walk) ->
bool {
4306 if (++NumVisited > MaxChainNodes)
4308 if (!IsChainNode(
V))
4309 return AddSource(
V);
4314 if (!Walk(
U->getOperand(
I), Walk))
4323 return AddSource(
V);
4325 if (!Walk(VecOpEE, Walk) || Nodes.
empty())
4338 if (!IsFloatReduction) {
4340 IsFloatReduction =
true;
4354 DenseMap<Value *, Demand> Demands;
4355 auto DemandOf = [&](
Value *
V) -> Demand & {
4357 Demand &
D = Demands[
V];
4358 if (
D.Lanes.getBitWidth() !=
N)
4362 DemandOf(VecOpEE).Lanes.setBit(0);
4364 Demand DV = Demands.
lookup(
V);
4365 if (DV.Lanes.isZero())
4368 ArrayRef<int>
Mask = SVI->getShuffleMask();
4369 Demand &
DS = DemandOf(SVI->getOperand(0));
4370 for (
unsigned I = 0,
E =
Mask.size();
I !=
E; ++
I) {
4372 if (!DV.Lanes[
I] || Mask[
I] < 0 ||
4373 (
unsigned)Mask[
I] >=
DS.Lanes.getBitWidth())
4375 if (
DS.Lanes[Mask[
I]] || DV.Duplicates[
I])
4376 DS.Duplicates.setBit(Mask[
I]);
4377 DS.Lanes.setBit(Mask[
I]);
4381 for (
Value *
Op : {
U->getOperand(0),
U->getOperand(1)}) {
4382 Demand &DOp = DemandOf(
Op);
4384 DOp.Duplicates |= DV.Duplicates | (DOp.Lanes & DV.Lanes);
4385 DOp.Lanes |= DV.Lanes;
4392 auto CoversChain = [&](
Value *
V) {
4393 SmallVector<Value *, 8> Worklist(1, VecOpEE);
4394 SmallPtrSet<Value *, 8> Seen;
4396 while (!Worklist.empty()) {
4399 for (
unsigned I = 0;
I !=
NumOps; ++
I) {
4403 if (!Nodes.contains(
Op))
4405 Worklist.push_back(
Op);
4413 struct ReductionCut {
4417 std::optional<ReductionCut> Cut;
4418 for (
Value *S : Sources) {
4419 auto It = Demands.
find(S);
4420 if (It == Demands.
end() || It->second.Lanes.isZero())
4422 if (!IsIdempotent && !It->second.Duplicates.isZero()) {
4427 Cut = ReductionCut{S, It->second.Lanes};
4434 if (!IsIdempotent && !(Cut->Elts & It->second.Lanes).isZero()) {
4438 Cut->Elts |= It->second.Lanes;
4444 auto It = Demands.
find(
V);
4445 if (It == Demands.
end() || !It->second.Lanes.isAllOnes())
4447 if (!IsIdempotent && !It->second.Duplicates.isZero())
4449 if (!CoversChain(
V))
4451 Cut = ReductionCut{
V, It->second.Lanes};
4456 if (!Cut || Cut->Elts.popcount() < 2)
4470 bool IsPartialReduction = !Cut->Elts.isAllOnes();
4471 FixedVectorType *ReduceVecTy =
4476 SmallVector<int> ExtractMask;
4478 if (IsPartialReduction) {
4479 for (
unsigned I = 0,
E = Cut->Elts.getBitWidth();
I !=
E; ++
I)
4481 ExtractMask.push_back(
I);
4482 unsigned SubIdx = 0, SubLen;
4483 auto SK = Cut->Elts.isShiftedMask(SubIdx, SubLen)
4487 SubIdx, ReduceVecTy);
4490 IntrinsicCostAttributes ICA(
4491 ReducedOp, ReduceVecTy->getElementType(),
4495 IsFloatReduction ? CommonFMF : FastMathFlags());
4498 LLVM_DEBUG(
dbgs() <<
"Found reduction shuffle chain: " <<
I <<
"\n OldCost : "
4499 << OrigCost <<
" vs NewCost: " << NewCost <<
"\n");
4504 if (VecOpEE->
hasOneUse() ? (NewCost > OrigCost) : (NewCost >= OrigCost))
4507 Value *ReduceInput = Cut->Src;
4508 if (IsPartialReduction)
4511 Value *ReducedResult;
4512 if (IsFloatReduction) {
4514 *CommonBinOp, ReduceVecTy->getElementType(),
false,
4517 {Identity, ReduceInput}, CommonFMF);
4522 replaceValue(
I, *ReducedResult);
4531bool VectorCombine::foldCastFromReductions(Instruction &
I) {
4536 bool TruncOnly =
false;
4539 case Intrinsic::vector_reduce_add:
4540 case Intrinsic::vector_reduce_mul:
4543 case Intrinsic::vector_reduce_and:
4544 case Intrinsic::vector_reduce_or:
4545 case Intrinsic::vector_reduce_xor:
4552 Value *ReductionSrc =
I.getOperand(0);
4564 Type *ResultTy =
I.getType();
4567 ReductionOpc, ReductionSrcTy, std::nullopt, CostKind);
4577 if (OldCost <= NewCost || !NewCost.
isValid())
4581 II->getIntrinsicID(), {Src});
4583 replaceValue(
I, *NewCast);
4611bool VectorCombine::foldSignBitReductionCmp(Instruction &
I) {
4613 IntrinsicInst *ReduceOp;
4614 const APInt *CmpVal;
4621 case Intrinsic::vector_reduce_or:
4622 case Intrinsic::vector_reduce_umax:
4623 case Intrinsic::vector_reduce_and:
4624 case Intrinsic::vector_reduce_umin:
4625 case Intrinsic::vector_reduce_add:
4636 unsigned BitWidth = VecTy->getScalarSizeInBits();
4640 unsigned NumElts = VecTy->getNumElements();
4649 case Intrinsic::vector_reduce_or:
4650 case Intrinsic::vector_reduce_umax:
4651 TreeOpcode = Instruction::Or;
4653 case Intrinsic::vector_reduce_and:
4654 case Intrinsic::vector_reduce_umin:
4655 TreeOpcode = Instruction::And;
4657 case Intrinsic::vector_reduce_add:
4658 TreeOpcode = Instruction::Add;
4666 SmallVector<Value *, 8> Worklist;
4667 SmallVector<Value *, 8> Sources;
4669 std::optional<bool> IsAShr;
4670 constexpr unsigned MaxSources = 8;
4675 while (!Worklist.
empty() && Worklist.
size() <= MaxSources &&
4676 Sources.
size() <= MaxSources) {
4685 bool ThisIsAShr = Shr->getOpcode() == Instruction::AShr;
4687 IsAShr = ThisIsAShr;
4688 else if (*IsAShr != ThisIsAShr)
4714 if (Sources.
empty() || Sources.
size() > MaxSources ||
4715 Worklist.
size() > MaxSources || !IsAShr)
4718 unsigned NumSources = Sources.
size();
4722 if (OrigIID == Intrinsic::vector_reduce_add &&
4730 (OrigIID == Intrinsic::vector_reduce_add) ? NumSources * NumElts : 1;
4733 NegativeVal.negate();
4765 TestsNegative =
false;
4766 }
else if (*CmpVal == NegativeVal) {
4767 TestsNegative =
true;
4771 IsEq =
Pred == ICmpInst::ICMP_EQ;
4772 }
else if (
Pred == ICmpInst::ICMP_SLT && *CmpVal == RangeHigh) {
4774 TestsNegative = (RangeHigh == NegativeVal);
4775 }
else if (
Pred == ICmpInst::ICMP_SGT && *CmpVal == RangeHigh - 1) {
4777 TestsNegative = (RangeHigh == NegativeVal);
4778 }
else if (
Pred == ICmpInst::ICMP_SGT && *CmpVal == RangeLow) {
4780 TestsNegative = (RangeLow == NegativeVal);
4781 }
else if (
Pred == ICmpInst::ICMP_SLT && *CmpVal == RangeLow + 1) {
4783 TestsNegative = (RangeLow == NegativeVal);
4826 enum CheckKind :
unsigned {
4833 auto RequiresOr = [](CheckKind
C) ->
bool {
return C & 0b100; };
4835 auto IsNegativeCheck = [](CheckKind
C) ->
bool {
return C & 0b010; };
4837 auto Invert = [](CheckKind
C) {
return CheckKind(
C ^ 0b011); };
4841 case Intrinsic::vector_reduce_or:
4842 case Intrinsic::vector_reduce_umax:
4843 Base = TestsNegative ? AnyNeg : AllNonNeg;
4845 case Intrinsic::vector_reduce_and:
4846 case Intrinsic::vector_reduce_umin:
4847 Base = TestsNegative ? AllNeg : AnyNonNeg;
4849 case Intrinsic::vector_reduce_add:
4850 Base = TestsNegative ? AllNeg : AllNonNeg;
4861 VecTy, std::nullopt, CostKind);
4864 FastMathFlags(), CostKind);
4865 return ArithCost <= MinMaxCost ? std::make_pair(Arith, ArithCost)
4866 : std::make_pair(MinMax, MinMaxCost);
4870 auto [NewIID, NewCost] = RequiresOr(
Check)
4871 ? PickCheaper(Intrinsic::vector_reduce_or,
4872 Intrinsic::vector_reduce_umax)
4873 : PickCheaper(
Intrinsic::vector_reduce_and,
4877 if (NumSources > 1) {
4878 unsigned CombineOpc =
4879 RequiresOr(
Check) ? Instruction::Or : Instruction::And;
4884 LLVM_DEBUG(
dbgs() <<
"Found sign-bit reduction cmp: " <<
I <<
"\n OldCost: "
4885 << OldCost <<
" vs NewCost: " << NewCost <<
"\n");
4887 if (NewCost > OldCost)
4892 Type *ScalarTy = VecTy->getScalarType();
4895 if (NumSources == 1) {
4906 replaceValue(
I, *NewCmp);
4937bool VectorCombine::foldReductionZeroTest(Instruction &
I) {
4946 if (!
II || !
II->hasOneUse())
4949 auto ReduceID =
II->getIntrinsicID();
4950 if (ReduceID != Intrinsic::vector_reduce_or &&
4951 ReduceID != Intrinsic::vector_reduce_umax)
4954 Value *Vec =
II->getArgOperand(0);
4956 if (!VecTy || !VecTy->getElementType()->isIntegerTy())
4961 ? Intrinsic::vector_reduce_or
4976 LLVM_DEBUG(
dbgs() <<
"Found a reduction zero test: " <<
I <<
"\n OldCost: "
4977 << OldCost <<
" vs NewCost: " << NewCost <<
"\n");
4979 if (!OldCost.
isValid() || !NewCost.
isValid() || NewCost > OldCost)
4985 replaceValue(
I, *NewReduce);
5010bool VectorCombine::foldICmpEqZeroVectorReduce(Instruction &
I) {
5021 switch (
II->getIntrinsicID()) {
5022 case Intrinsic::vector_reduce_add:
5023 case Intrinsic::vector_reduce_or:
5024 case Intrinsic::vector_reduce_umin:
5025 case Intrinsic::vector_reduce_umax:
5026 case Intrinsic::vector_reduce_smin:
5027 case Intrinsic::vector_reduce_smax:
5033 Value *InnerOp =
II->getArgOperand(0);
5076 switch (
II->getIntrinsicID()) {
5077 case Intrinsic::vector_reduce_add: {
5082 unsigned NumElems = XTy->getNumElements();
5088 if (LeadingZerosX <= LostBits || LeadingZerosFX <= LostBits)
5096 case Intrinsic::vector_reduce_smin:
5097 case Intrinsic::vector_reduce_smax:
5107 LLVM_DEBUG(
dbgs() <<
"Found a reduction to 0 comparison with removable op: "
5123 case Intrinsic::vector_reduce_add:
5124 case Intrinsic::vector_reduce_or:
5130 case Intrinsic::vector_reduce_umin:
5131 case Intrinsic::vector_reduce_umax:
5132 case Intrinsic::vector_reduce_smin:
5133 case Intrinsic::vector_reduce_smax:
5145 NewReduceCost + (InnerOp->
hasOneUse() ? 0 : ExtCost);
5147 LLVM_DEBUG(
dbgs() <<
"Found a removable extension before reduction: "
5148 << *InnerOp <<
"\n OldCost: " << OldCost
5149 <<
" vs NewCost: " << NewCost <<
"\n");
5155 if (NewCost > OldCost)
5164 Builder.
CreateICmp(
Pred, NewReduce, ConstantInt::getNullValue(Ty));
5165 replaceValue(
I, *NewCmp);
5196bool VectorCombine::foldEquivalentReductionCmp(Instruction &
I) {
5199 const APInt *CmpVal;
5204 if (!
II || !
II->hasOneUse())
5207 const auto IsValidOrUmaxCmp = [&]() {
5216 bool IsPositive = CmpVal->
isAllOnes() &&
Pred == ICmpInst::ICMP_SGT;
5218 bool IsNegative = (CmpVal->
isZero() || CmpVal->
isOne() || *CmpVal == 2) &&
5219 Pred == ICmpInst::ICMP_SLT;
5220 return IsEquality || IsPositive || IsNegative;
5223 const auto IsValidAndUminCmp = [&]() {
5228 const auto LeadingOnes = CmpVal->
countl_one();
5235 bool IsNegative = CmpVal->
isZero() &&
Pred == ICmpInst::ICMP_SLT;
5244 ((*CmpVal)[0] || (*CmpVal)[1]) &&
Pred == ICmpInst::ICMP_SGT;
5245 return IsEquality || IsNegative || IsPositive;
5253 switch (OriginalIID) {
5254 case Intrinsic::vector_reduce_or:
5255 if (!IsValidOrUmaxCmp())
5257 AlternativeIID = Intrinsic::vector_reduce_umax;
5259 case Intrinsic::vector_reduce_umax:
5260 if (!IsValidOrUmaxCmp())
5262 AlternativeIID = Intrinsic::vector_reduce_or;
5264 case Intrinsic::vector_reduce_and:
5265 if (!IsValidAndUminCmp())
5267 AlternativeIID = Intrinsic::vector_reduce_umin;
5269 case Intrinsic::vector_reduce_umin:
5270 if (!IsValidAndUminCmp())
5272 AlternativeIID = Intrinsic::vector_reduce_and;
5285 if (ReductionOpc != Instruction::ICmp)
5289 FastMathFlags(), CostKind);
5296 <<
"\n OrigCost: " << OrigCost
5297 <<
" vs AltCost: " << AltCost <<
"\n");
5299 if (AltCost >= OrigCost)
5303 Type *ScalarTy = VecTy->getScalarType();
5306 Builder.
CreateICmp(
Pred, NewReduce, ConstantInt::get(ScalarTy, *CmpVal));
5308 replaceValue(
I, *NewCmp);
5322 unsigned Depth = 0) {
5323 constexpr unsigned MaxLocalDepth = 2;
5324 if (
Depth > MaxLocalDepth)
5327 auto NumSignBits = [&](
const Value *
X) {
5330 if (NumSignBits(
V) ==
V->getType()->getScalarSizeInBits())
5335 return NumSignBits(
A) >= 2 && NumSignBits(
B) >= 2 &&
5346bool VectorCombine::foldReduceAddCmpZero(Instruction &
I) {
5356 if (!VecTy || VecTy->getNumElements() < 2)
5362 if (!IsNonNegative && !IsNonPositive)
5367 unsigned NumElts = VecTy->getNumElements();
5369 if (
Log2_32(NumElts) >= NumSignBits)
5372 ICmpInst::Predicate NewPred;
5374 case ICmpInst::ICMP_EQ:
5375 case ICmpInst::ICMP_ULE:
5376 case ICmpInst::ICMP_SLE:
5377 case ICmpInst::ICMP_SGE:
5378 NewPred = ICmpInst::ICMP_EQ;
5380 case ICmpInst::ICMP_NE:
5381 case ICmpInst::ICMP_UGT:
5382 case ICmpInst::ICMP_SGT:
5383 case ICmpInst::ICMP_SLT:
5384 NewPred = ICmpInst::ICMP_NE;
5394 if (!IsNonNegative &&
5395 (
Pred == ICmpInst::ICMP_SGT ||
Pred == ICmpInst::ICMP_SLE))
5397 if (!IsNonPositive &&
5398 (
Pred == ICmpInst::ICMP_SLT ||
Pred == ICmpInst::ICMP_SGE))
5400 if ((
Pred == ICmpInst::ICMP_SGT ||
Pred == ICmpInst::ICMP_SLE ||
5401 Pred == ICmpInst::ICMP_SLT ||
Pred == ICmpInst::ICMP_SGE) &&
5402 Log2_32(NumElts) >= NumSignBits - 1)
5406 Instruction::Add, VecTy, std::nullopt, CostKind);
5408 Instruction::Or, VecTy, std::nullopt, CostKind);
5410 Intrinsic::umax, VecTy, FastMathFlags(), CostKind);
5413 bool UseOr = OrCost.
isValid() && (!UmaxCost.
isValid() || OrCost <= UmaxCost);
5415 if (AltCost > OrigCost)
5421 Intrinsic::vector_reduce_umax, {VecTy}, {Vec});
5423 NewPred, NewReduce, ConstantInt::getNullValue(VecTy->getScalarType()));
5424 replaceValue(
I, *NewCmp);
5433 constexpr unsigned MaxVisited = 32;
5436 bool FoundReduction =
false;
5439 while (!WorkList.
empty()) {
5441 for (
User *U :
I->users()) {
5443 if (!UI || !Visited.
insert(UI).second)
5445 if (Visited.
size() > MaxVisited)
5451 switch (
II->getIntrinsicID()) {
5452 case Intrinsic::vector_reduce_add:
5453 case Intrinsic::vector_reduce_mul:
5454 case Intrinsic::vector_reduce_and:
5455 case Intrinsic::vector_reduce_or:
5456 case Intrinsic::vector_reduce_xor:
5457 case Intrinsic::vector_reduce_smin:
5458 case Intrinsic::vector_reduce_smax:
5459 case Intrinsic::vector_reduce_umin:
5460 case Intrinsic::vector_reduce_umax:
5461 FoundReduction =
true;
5474 return FoundReduction;
5487bool VectorCombine::foldSelectShuffle(Instruction &
I,
bool FromReduction) {
5492 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
5493 VT != Op0->getType())
5500 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
5502 if (!
I ||
I->getOperand(0)->getType() != VT)
5504 return any_of(
I->users(), [&](User *U) {
5505 return U != Op0 && U != Op1 &&
5506 !(isa<ShuffleVectorInst>(U) &&
5507 (InputShuffles.contains(cast<Instruction>(U)) ||
5508 isInstructionTriviallyDead(cast<Instruction>(U))));
5511 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
5512 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
5520 for (
auto *U :
I->users()) {
5522 if (!SV ||
SV->getType() != VT)
5524 if ((
SV->getOperand(0) != Op0 &&
SV->getOperand(0) != Op1) ||
5525 (
SV->getOperand(1) != Op0 &&
SV->getOperand(1) != Op1))
5532 if (!collectShuffles(Op0) || !collectShuffles(Op1))
5536 if (FromReduction && Shuffles.
size() > 1)
5541 if (!FromReduction) {
5542 for (
size_t Idx = 0,
E = Shuffles.
size(); Idx !=
E; ++Idx) {
5543 for (
auto *U : Shuffles[Idx]->
users()) {
5558 int MaxV1Elt = 0, MaxV2Elt = 0;
5559 unsigned NumElts = VT->getNumElements();
5560 for (ShuffleVectorInst *SVN : Shuffles) {
5561 SmallVector<int>
Mask;
5562 SVN->getShuffleMask(Mask);
5566 Value *SVOp0 = SVN->getOperand(0);
5567 Value *SVOp1 = SVN->getOperand(1);
5572 for (
int &Elem : Mask) {
5578 if (SVOp0 == Op1 && SVOp1 == Op0) {
5582 if (SVOp0 != Op0 || SVOp1 != Op1)
5588 SmallVector<int> ReconstructMask;
5589 for (
unsigned I = 0;
I <
Mask.size();
I++) {
5592 }
else if (Mask[
I] <
static_cast<int>(NumElts)) {
5593 MaxV1Elt = std::max(MaxV1Elt, Mask[
I]);
5594 auto It =
find_if(
V1, [&](
const std::pair<int, int> &
A) {
5595 return Mask[
I] ==
A.first;
5601 V1.emplace_back(Mask[
I],
V1.size());
5604 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[
I] - NumElts);
5605 auto It =
find_if(V2, [&](
const std::pair<int, int> &
A) {
5606 return Mask[
I] -
static_cast<int>(NumElts) ==
A.first;
5620 sort(ReconstructMask);
5621 OrigReconstructMasks.
push_back(std::move(ReconstructMask));
5628 if (
V1.empty() || V2.
empty() ||
5629 (MaxV1Elt ==
static_cast<int>(
V1.size()) - 1 &&
5630 MaxV2Elt ==
static_cast<int>(V2.
size()) - 1))
5642 if (InputShuffles.contains(SSV))
5644 return SV->getMaskValue(M);
5652 std::pair<int, int>
Y) {
5653 int MXA = GetBaseMaskValue(
A,
X.first);
5654 int MYA = GetBaseMaskValue(
A,
Y.first);
5658 return SortBase(SVI0A,
A,
B);
5660 stable_sort(V2, [&](std::pair<int, int>
A, std::pair<int, int>
B) {
5661 return SortBase(SVI1A,
A,
B);
5666 for (
const auto &Mask : OrigReconstructMasks) {
5667 SmallVector<int> ReconstructMask;
5668 for (
int M : Mask) {
5670 auto It =
find_if(
V, [M](
auto A) {
return A.second ==
M; });
5671 assert(It !=
V.end() &&
"Expected all entries in Mask");
5672 return std::distance(
V.begin(), It);
5676 else if (M <
static_cast<int>(NumElts)) {
5679 ReconstructMask.
push_back(NumElts + FindIndex(V2, M));
5682 ReconstructMasks.
push_back(std::move(ReconstructMask));
5687 SmallVector<int> V1A, V1B, V2A, V2B;
5688 for (
unsigned I = 0;
I <
V1.size();
I++) {
5692 for (
unsigned I = 0;
I < V2.
size();
I++) {
5693 V2A.
push_back(GetBaseMaskValue(SVI1A, V2[
I].first));
5694 V2B.
push_back(GetBaseMaskValue(SVI1B, V2[
I].first));
5696 while (V1A.
size() < NumElts) {
5700 while (V2A.
size() < NumElts) {
5712 VT, VT, CostKind,
SV->getShuffleMask());
5719 unsigned ElementSize = VT->getElementType()->getPrimitiveSizeInBits();
5720 unsigned MaxVectorSize =
5722 unsigned MaxElementsInVector = MaxVectorSize / ElementSize;
5723 if (MaxElementsInVector == 0)
5732 std::set<SmallVector<int, 4>> UniqueShuffles;
5737 unsigned NumFullVectors =
Mask.size() / MaxElementsInVector;
5738 if (NumFullVectors < 2)
5739 return C + ShuffleCost;
5740 SmallVector<int, 4> SubShuffle(MaxElementsInVector);
5741 unsigned NumUniqueGroups = 0;
5742 unsigned NumGroups =
Mask.size() / MaxElementsInVector;
5745 for (
unsigned I = 0;
I < NumFullVectors; ++
I) {
5746 for (
unsigned J = 0; J < MaxElementsInVector; ++J)
5747 SubShuffle[J] = Mask[MaxElementsInVector *
I + J];
5748 if (UniqueShuffles.insert(SubShuffle).second)
5749 NumUniqueGroups += 1;
5751 return C + ShuffleCost * NumUniqueGroups / NumGroups;
5757 SmallVector<int, 16>
Mask;
5758 SV->getShuffleMask(Mask);
5759 return AddShuffleMaskAdjustedCost(
C, Mask);
5762 auto AllShufflesHaveSameOperands =
5763 [](SmallPtrSetImpl<Instruction *> &InputShuffles) {
5764 if (InputShuffles.size() < 2)
5766 ShuffleVectorInst *FirstSV =
5773 std::next(InputShuffles.begin()), InputShuffles.end(),
5774 [&](Instruction *
I) {
5775 ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(I);
5776 return SV && SV->getOperand(0) == In0 && SV->getOperand(1) == In1;
5785 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
5787 if (AllShufflesHaveSameOperands(InputShuffles)) {
5788 UniqueShuffles.clear();
5789 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
5792 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
5798 FixedVectorType *Op0SmallVT =
5800 FixedVectorType *Op1SmallVT =
5805 UniqueShuffles.clear();
5806 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
5808 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
5810 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
5813 LLVM_DEBUG(
dbgs() <<
"Found a binop select shuffle pattern: " <<
I <<
"\n");
5815 <<
" vs CostAfter: " << CostAfter <<
"\n");
5816 if (CostBefore < CostAfter ||
5827 if (InputShuffles.contains(SSV))
5829 return SV->getOperand(
Op);
5833 GetShuffleOperand(SVI0A, 1), V1A);
5836 GetShuffleOperand(SVI0B, 1), V1B);
5839 GetShuffleOperand(SVI1A, 1), V2A);
5842 GetShuffleOperand(SVI1B, 1), V2B);
5847 I->copyIRFlags(Op0,
true);
5852 I->copyIRFlags(Op1,
true);
5854 for (
int S = 0,
E = ReconstructMasks.size(); S !=
E; S++) {
5857 replaceValue(*Shuffles[S], *NSV,
false);
5869bool VectorCombine::shrinkType(Instruction &
I) {
5870 Value *ZExted, *OtherOperand;
5876 Value *ZExtOperand =
I.getOperand(
I.getOperand(0) == OtherOperand ? 1 : 0);
5880 unsigned BW = SmallTy->getElementType()->getPrimitiveSizeInBits();
5882 if (
I.getOpcode() == Instruction::LShr) {
5899 Instruction::ZExt, BigTy, SmallTy,
5900 TargetTransformInfo::CastContextHint::None, CostKind);
5905 for (User *U : ZExtOperand->
users()) {
5912 ShrinkCost += ZExtCost;
5927 ShrinkCost += ZExtCost;
5934 Instruction::Trunc, SmallTy, BigTy,
5935 TargetTransformInfo::CastContextHint::None, CostKind);
5940 if (ShrinkCost > CurrentCost)
5944 Value *Op0 = ZExted;
5947 if (
I.getOperand(0) == OtherOperand)
5952 NewBinOpI->copyIRFlags(&
I);
5953 NewBinOpI->copyMetadata(
I);
5956 replaceValue(
I, *NewZExtr);
5962bool VectorCombine::foldInsExtVectorToShuffle(Instruction &
I) {
5963 Value *DstVec, *SrcVec;
5974 if (!DstVecTy || !SrcVecTy ||
5980 if (InsIdx >= NumDstElts || ExtIdx >= NumSrcElts || NumDstElts == 1)
5987 bool NeedExpOrNarrow = NumSrcElts != NumDstElts;
5989 if (NeedDstSrcSwap) {
5991 Mask[InsIdx] = ExtIdx % NumDstElts;
5995 std::iota(
Mask.begin(),
Mask.end(), 0);
5996 Mask[InsIdx] = (ExtIdx % NumDstElts) + NumDstElts;
6009 SmallVector<int> ExtToVecMask;
6010 if (!NeedExpOrNarrow) {
6015 nullptr, {DstVec, SrcVec});
6021 ExtToVecMask[ExtIdx % NumDstElts] = ExtIdx;
6024 DstVecTy, SrcVecTy, CostKind, ExtToVecMask);
6028 if (!Ext->hasOneUse())
6031 LLVM_DEBUG(
dbgs() <<
"Found a insert/extract shuffle-like pair: " <<
I
6032 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
6035 if (OldCost < NewCost)
6038 if (NeedExpOrNarrow) {
6039 if (!NeedDstSrcSwap)
6052 replaceValue(
I, *Shuf);
6061bool VectorCombine::foldInsertScalarPartsToShuffle(Instruction &
I) {
6070 Type *EltTy = VecTy->getElementType();
6072 !
DL->typeSizeEqualsStoreSize(EltTy))
6075 unsigned NumElts = VecTy->getNumElements();
6077 Value *Src =
nullptr;
6078 unsigned NumSrcElts = 0;
6084 if (Ins != &
I && !Ins->hasOneUse())
6089 Vec = Ins->getOperand(0);
6091 if (DemandedElts[Idx])
6093 DemandedElts.
setBit(Idx);
6097 Value *Elt = Ins->getOperand(1);
6102 Trunc->getType()->getPrimitiveSizeInBits() != EltBits)
6104 Value *Shift =
nullptr;
6112 unsigned SrcBits =
X->getType()->getIntegerBitWidth();
6113 if (SrcBits % EltBits)
6116 NumSrcElts = SrcBits / EltBits;
6117 }
else if (
X != Src) {
6121 if (ShAmt % EltBits || Part >= NumSrcElts)
6123 Mask[
Idx] =
DL->isBigEndian() ? NumSrcElts - 1 - Part : Part;
6129 if (!
V->hasOneUse())
6151 bool IsIdentity = NumSrcElts == NumElts &&
6157 LLVM_DEBUG(
dbgs() <<
"Found an insertelement chain of scalar parts: " <<
I
6158 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
6160 if (!OldCost.
isValid() || !NewCost.
isValid() || NewCost >= OldCost)
6165 replaceValue(
I, *Shuf);
6172 return CB->arg_size();
6184 if (
II->hasOperandBundles() ||
6197 OperandTy->getElementCount() != ResultTy->getElementCount())
6206 auto GetSplatOrScalar = [](
Value *
V) {
6210 Value *CommonValue = GetSplatOrScalar(
Values.front());
6214 if (GetSplatOrScalar(
V) != CommonValue)
6223 for (
const auto &[Index, Member] :
enumerate(Members)) {
6225 if (!Extract || Extract->getNumIndices() != 1 ||
6226 *Extract->idx_begin() != Index)
6234 unsigned Factor = Members.
size();
6245 unsigned OperandIndex) {
6247 for (
Value *Member : Members)
6257 unsigned Factor = Members.
size();
6264 if (Visited.
size() + Factor > Opts.vector_combine_max_scan_instrs)
6267 auto addUndroppableUsers = [&](
Value *
V) {
6268 for (
User *U :
V->users()) {
6269 if (U->isDroppable())
6271 UndroppableUsers.
insert(U);
6278 if (Visited.
insert(FirstInst).second && !FirstInst->getSingleUndroppableUse())
6279 addUndroppableUsers(FirstInst);
6286 if (Visited.
insert(Inst).second && !Inst->getSingleUndroppableUse())
6287 addUndroppableUsers(Inst);
6307 return Builder.CreateNAryOp(NarrowInst->
getOpcode(), NewOperands);
6309 return Builder.CreateCast(Cast->getOpcode(), NewOperands[0], WideResultTy);
6311 return Builder.CreateCmp(Cmp->getPredicate(), NewOperands[0],
6314 return Builder.CreateSelect(
6315 NewOperands[0], NewOperands[1], NewOperands[2],
"",
6318 return Builder.CreateFreeze(NewOperands[0]);
6320 return Builder.CreateIntrinsic(WideResultTy,
II->getIntrinsicID(),
6329 if (
Value *WideValue = WideValueCache.lookup(Members))
6335 "deinterleave source must have the interleaved element count");
6336 WideValueCache[Members] = Source;
6343 NewOperands.
reserve(NumOperands);
6344 for (
unsigned Op = 0;
Op != NumOperands; ++
Op) {
6346 Value *NewOperand =
nullptr;
6349 Builder.SetCurrentDebugLocation(NarrowInst->getDebugLoc());
6350 NewOperand = Builder.CreateVectorSplat(WideEC, NewOperand);
6361 Builder.SetCurrentDebugLocation(NarrowInst->getDebugLoc());
6362 auto *WideResultTy =
6370 WideValueCache[Members] = NewValue;
6410bool VectorCombine::foldInterleaveOfDeinterleaveChains(Instruction &
I) {
6416 if (!Factor || Interleave->hasOperandBundles())
6419 SmallVector<Value *, 8> RootMembers(Interleave->args());
6420 SmallPtrSet<User *, 4> UndroppableUsers;
6421 DenseSet<Value *> Visited;
6433 DenseMap<SmallVector<Value *, 8>,
Value *> WideValueCache;
6437 replaceValue(*Interleave, *WideValue);
6445bool VectorCombine::foldInterleaveIntrinsics(Instruction &
I) {
6446 if (foldInterleaveOfDeinterleaveChains(
I))
6449 const APInt *SplatVal0, *SplatVal1;
6459 auto *ExtVTy = VectorType::getExtendedElementVectorType(VTy);
6460 unsigned Width = VTy->getElementType()->getIntegerBitWidth();
6469 LLVM_DEBUG(
dbgs() <<
"VC: The cost to cast from " << *ExtVTy <<
" to "
6470 << *
I.getType() <<
" is too high.\n");
6477 const APInt &LowHalf =
DL->isLittleEndian() ? *SplatVal0 : *SplatVal1;
6478 const APInt &HighHalf =
DL->isLittleEndian() ? *SplatVal1 : *SplatVal0;
6479 APInt NewSplatVal = HighHalf.
zext(Width * 2);
6480 NewSplatVal <<= Width;
6481 NewSplatVal |= LowHalf.
zext(Width * 2);
6483 ExtVTy->getElementCount(), ConstantInt::get(
F.getContext(), NewSplatVal));
6518bool VectorCombine::foldDeinterleaveIntrinsics(Instruction &
I) {
6519 using namespace PatternMatch;
6520 Value *DeinterleavedVal;
6531 unsigned HalfElementWidth = ElementWidth / 2;
6535 std::array<ExtractValueInst *, 2> OrigFields{};
6536 for (User *Usr :
I.users()) {
6539 if (!
E ||
E->getNumIndices() != 1)
6541 unsigned Idx = *
E->idx_begin();
6543 if (Idx >= 2 || OrigFields[Idx] || !
E->hasNUses(2))
6545 OrigFields[
Idx] =
E;
6548 if (
DL->isBigEndian())
6549 std::swap(OrigFields[0], OrigFields[1]);
6552 SmallVector<Instruction *, 2> MergeInsts;
6553 for (
auto *FieldUsr : OrigFields[0]->
users()) {
6561 auto MatchMerge = [&](void) ->
bool {
6564 return match(MergeInsts[0],
6568 match(MergeInsts[1],
6573 if (!MatchMerge()) {
6574 std::swap(MergeInsts[0], MergeInsts[1]);
6589 auto *NewFieldTy = VecTy->getWithNewBitWidth(HalfElementWidth);
6599 if (OldCost <= NewCost || !NewCost.
isValid()) {
6601 dbgs() <<
"VC: New deinterleave2 sequence cost (" << NewCost <<
")"
6602 <<
" is higher than that of the old one (" << OldCost <<
")\n");
6610 Intrinsic::vector_deinterleave2, {NewVecTy}, {NewVecCast});
6611 for (
auto [Idx, MergeInst] :
enumerate(MergeInsts)) {
6612 if (
DL->isBigEndian())
6615 NewField = Builder.
CreateBitCast(NewField, MergeInst->getType());
6616 replaceValue(*MergeInst, *NewField);
6622bool VectorCombine::foldBitcastOfVPLoad(Instruction &
I) {
6623 const DataLayout &
DL =
I.getDataLayout();
6638 DL.getValueOrABITypeAlignment(
II->getPointerAlignment(), OrigVecTy);
6639 ElementCount OrigVecCnt = OrigVecTy->getElementCount();
6641 ElementCount NewVecCnt = NewVecTy->getElementCount();
6653 II->getMemoryPointerParam(),
false,
6659 {Intrinsic::vp_load, NewVecTy,
II->getMemoryPointerParam(),
false,
6663 <<
" NewCost=" << NewCost <<
"\n");
6664 if (NewCost > OldCost || !NewCost.
isValid())
6672 NewVecTy, Intrinsic::vp_load,
6673 {
II->getMemoryPointerParam(), NewMask, NewEVL});
6676 0, AttrBuilder(
II->getContext()).addAlignmentAttr(OrigAlign));
6677 replaceValue(*Cast, *NewVP);
6687bool VectorCombine::foldBitOrderReverseAndSwap(Instruction &
I) {
6691 Type *Ty =
X->getType();
6692 Type *VecTy =
I.getOperand(0)->getType();
6706 if (CanUseBswap || CanUseFshl) {
6717 IntrinsicCostAttributes ICABSwap(Intrinsic::bswap, Ty, {Ty});
6718 IntrinsicCostAttributes ICABFshl(Intrinsic::fshl, Ty, {
X,
X, HalfBW},
6720 IntrinsicCostAttributes ICABRev(Intrinsic::bitreverse, Ty, {Ty});
6725 if (!InnerCall->hasOneUse())
6728 else if (!InnerBitCast->hasOneUse())
6731 <<
"\n OldCost: " << OldCost
6732 <<
" vs NewCost: " << NewCost <<
"\n");
6733 if (NewCost.isValid() && NewCost < OldCost) {
6740 replaceValue(
I, *BRev);
6749 Type *Ty =
I.getType();
6751 TypeSize ElementSize =
DL->getTypeStoreSize(Ty);
6754 Type *NewVecTy = VectorType::get(I8Ty, NewVecCnt);
6767 IntrinsicCostAttributes ICANew(Intrinsic::bitreverse, NewVecTy, {NewVecTy});
6770 InstructionCost NewCost = CastToVecCost + NewIntrinsicCost + CastToOrigCost;
6771 if (!InnerII->hasOneUse())
6774 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
6776 if (!NewCost.
isValid() || NewCost >= OldCost)
6784 replaceValue(
I, *CastToOrig);
6794 unsigned RawNumElements = MaxIdx + 1u;
6798 return RawNumElements;
6802 return RawNumElements;
6807 return RawNumElements;
6812 if (ElemsPerReg == 0 || RawNumElements <= ElemsPerReg)
6813 return RawNumElements;
6815 return alignTo(RawNumElements, ElemsPerReg);
6819bool VectorCombine::shrinkLoadForShuffles(Instruction &
I) {
6821 if (!OldLoad || !OldLoad->isSimple())
6828 unsigned const OldNumElements = OldLoadTy->getNumElements();
6834 using IndexRange = std::pair<int, int>;
6835 auto GetIndexRangeInShuffles = [&]() -> std::optional<IndexRange> {
6836 IndexRange OutputRange = IndexRange(OldNumElements, -1);
6837 for (llvm::Use &Use :
I.uses()) {
6839 User *Shuffle =
Use.getUser();
6844 return std::nullopt;
6851 for (
int Index : Mask) {
6852 if (Index >= 0 && Index <
static_cast<int>(OldNumElements)) {
6853 OutputRange.first = std::min(Index, OutputRange.first);
6854 OutputRange.second = std::max(Index, OutputRange.second);
6859 if (OutputRange.second < OutputRange.first)
6860 return std::nullopt;
6866 if (std::optional<IndexRange> Indices = GetIndexRangeInShuffles()) {
6867 unsigned const NewNumElements =
6872 if (NewNumElements < OldNumElements) {
6877 Type *ElemTy = OldLoadTy->getElementType();
6879 Value *PtrOp = OldLoad->getPointerOperand();
6882 Instruction::Load, OldLoad->getType(), OldLoad->getAlign(),
6883 OldLoad->getPointerAddressSpace(), CostKind);
6886 OldLoad->getPointerAddressSpace(), CostKind);
6888 using UseEntry = std::pair<ShuffleVectorInst *, std::vector<int>>;
6890 unsigned const MaxIndex = NewNumElements * 2u;
6892 for (llvm::Use &Use :
I.uses()) {
6899 ArrayRef<int> OldMask = Shuffle->getShuffleMask();
6905 for (
int Index : OldMask) {
6906 if (Index >=
static_cast<int>(MaxIndex))
6913 OldLoadTy, CostKind, OldMask);
6916 NewLoadTy, CostKind, OldMask);
6920 dbgs() <<
"Found a load used only by shufflevector instructions: "
6921 <<
I <<
"\n OldCost: " << OldCost
6922 <<
" vs NewCost: " << NewCost <<
"\n");
6924 if (OldCost < NewCost || !NewCost.
isValid())
6930 NewLoad->copyMetadata(
I);
6933 for (UseEntry &Use : NewUses) {
6934 ShuffleVectorInst *Shuffle =
Use.first;
6935 std::vector<int> &NewMask =
Use.second;
6942 replaceValue(*Shuffle, *NewShuffle,
false);
6974bool VectorCombine::foldShuffleOfAdjacentLoads(Instruction &
I) {
6980 if (!Load0 || !Load1 || Load0 == Load1 || !Load0->isSimple() ||
6990 if (Load0->getParent() != Load1->getParent())
6993 if (Load0->getPointerAddressSpace() != Load1->getPointerAddressSpace())
6998 if (
DL->getTypeSizeInBits(LoadTy) != 8 *
DL->getTypeStoreSize(LoadTy))
7001 const unsigned NumElts = LoadTy->getNumElements();
7003 if (NumElts > INT_MAX / 2)
7009 unsigned AS = Load0->getPointerAddressSpace();
7010 unsigned IdxWidth =
DL->getIndexSizeInBits(AS);
7011 APInt Offset0(IdxWidth, 0), Offset1(IdxWidth, 0);
7012 const Value *Base0 =
7013 Load0->getPointerOperand()->stripAndAccumulateConstantOffsets(
7014 *
DL, Offset0,
true);
7015 const Value *Base1 =
7016 Load1->getPointerOperand()->stripAndAccumulateConstantOffsets(
7017 *
DL, Offset1,
true);
7022 int64_t LoadSize =
DL->getTypeStoreSize(LoadTy).getFixedValue();
7023 std::optional<int64_t> Dist = (Offset1 - Offset0).trySExtValue();
7024 LoadInst *LowLoad, *HighLoad;
7025 if (Dist == LoadSize) {
7028 }
else if (Dist == -LoadSize) {
7037 SmallPtrSet<ShuffleVectorInst *, 4> Shuffles;
7041 if (auto *SVI = dyn_cast<ShuffleVectorInst>(U)) {
7042 Shuffles.insert(SVI);
7051 LoadInst *FirstLoad = LowLoad, *LastLoad = HighLoad;
7056 LastLoad->getIterator(), FirstLoc, AA))
7067 auto RemapMask = [&](ShuffleVectorInst *
SV, SmallVectorImpl<int> &NewMask) {
7068 Value *SVOp0 =
SV->getOperand(0);
7069 assert(((SVOp0 == LowLoad &&
SV->getOperand(1) == HighLoad) ||
7070 (SVOp0 == HighLoad &&
SV->getOperand(1) == LowLoad)) &&
7071 "Shuffle operands must be exactly {LowLoad, HighLoad} or {HighLoad, "
7073 SV->getShuffleMask(NewMask);
7074 if (SVOp0 == HighLoad)
7089 for (ShuffleVectorInst *SV : Shuffles) {
7091 CostKind,
SV->getShuffleMask());
7093 RemapMask(SV, NewMask);
7101 WideTy, CostKind, NewMask);
7104 LLVM_DEBUG(
dbgs() <<
"Found adjacent loads feeding shuffles: " << *LowLoad
7105 <<
", " << *HighLoad <<
"\n OldCost: " << OldCost
7106 <<
" vs NewCost: " << NewCost <<
"\n");
7108 if (!NewCost.
isValid() || NewCost > OldCost)
7113 LoadInst *InsertPt = LastLoad;
7130 for (ShuffleVectorInst *SV : Shuffles) {
7132 RemapMask(SV, NewMask);
7139 replaceValue(*SV, *NewShuf,
false);
7148bool VectorCombine::shrinkPhiOfShuffles(Instruction &
I) {
7150 if (!Phi ||
Phi->getNumIncomingValues() != 2u)
7154 ArrayRef<int> Mask0;
7155 ArrayRef<int> Mask1;
7168 auto const InputNumElements = InputVT->getNumElements();
7170 if (InputNumElements >= ResultVT->getNumElements())
7175 SmallVector<int, 16> NewMask;
7178 auto IsPoison = [InputNumElements](
int M) {
7179 return M < 0 || (unsigned)M >= InputNumElements;
7182 for (
auto [
M0,
M1] :
zip(Mask0, Mask1)) {
7183 bool P0 = IsPoison(
M0);
7184 bool P1 = IsPoison(
M1);
7200 int MaskOffset = NewMask[0
u];
7201 unsigned Index = (InputNumElements + MaskOffset) % InputNumElements;
7204 for (
unsigned I = 0u;
I < InputNumElements; ++
I) {
7218 <<
"\n OldCost: " << OldCost <<
" vs NewCost: " << NewCost
7221 if (NewCost > OldCost)
7232 auto *NewPhi = Builder.
CreatePHI(NewShuf0->getType(), 2u);
7234 NewPhi->addIncoming(
Op,
Phi->getIncomingBlock(1u));
7240 replaceValue(*Phi, *NewShuf1);
7246bool VectorCombine::run() {
7247 if (Opts.disable_vector_combine)
7260 auto Opcode =
I.getOpcode();
7268 if (IsFixedVectorType) {
7270 case Instruction::InsertElement:
7271 if (vectorizeLoadInsert(
I))
7274 case Instruction::ShuffleVector:
7275 if (widenSubvectorLoad(
I))
7286 if (scalarizeOpOrCmp(
I))
7288 if (scalarizeLoad(
I))
7290 if (scalarizeExtExtract(
I))
7292 if (foldInterleaveIntrinsics(
I))
7294 if (foldBitcastOfVPLoad(
I))
7298 if (foldDeinterleaveIntrinsics(
I))
7301 if (Opcode == Instruction::Store)
7302 if (foldInsertElementsToStores(
I))
7306 if (TryEarlyFoldsOnly)
7309 if (Opcode == Instruction::Call)
7310 if (foldBitOrderReverseAndSwap(
I))
7312 if (Opcode == Instruction::BitCast)
7313 if (foldBitOrderReverseAndSwap(
I))
7320 if (IsFixedVectorType) {
7322 case Instruction::InsertElement:
7323 if (foldInsExtFNeg(
I))
7325 if (foldInsExtBinop(
I))
7327 if (foldInsExtVectorToShuffle(
I))
7329 if (foldInsertScalarPartsToShuffle(
I))
7332 case Instruction::ShuffleVector:
7333 if (foldPermuteOfBinops(
I))
7335 if (foldShuffleOfBinops(
I))
7337 if (foldShuffleOfSelects(
I))
7339 if (foldShuffleOfCastops(
I))
7341 if (foldShuffleOfShuffles(
I))
7343 if (foldShuffleOfAdjacentLoads(
I))
7345 if (foldPermuteOfIntrinsic(
I))
7347 if (foldShufflesOfLengthChangingShuffles(
I))
7349 if (foldShuffleOfIntrinsics(
I))
7351 if (foldSelectShuffle(
I))
7353 if (foldShuffleToIdentity(
I))
7356 case Instruction::Load:
7357 if (shrinkLoadForShuffles(
I))
7360 case Instruction::BitCast:
7361 if (foldBitcastShuffle(
I))
7363 if (foldSelectsFromBitcast(
I))
7366 case Instruction::And:
7367 case Instruction::Or:
7368 case Instruction::Xor:
7369 if (foldBitOpOfCastops(
I))
7371 if (foldBitOpOfCastConstant(
I))
7374 case Instruction::PHI:
7375 if (shrinkPhiOfShuffles(
I))
7385 case Instruction::Call:
7386 if (foldShuffleFromReductions(
I))
7388 if (foldCastFromReductions(
I))
7391 case Instruction::ExtractElement:
7392 if (foldShuffleChainsToReduce(
I))
7395 case Instruction::ICmp:
7396 if (foldSignBitReductionCmp(
I))
7398 if (foldICmpEqZeroVectorReduce(
I))
7400 if (foldReductionZeroTest(
I))
7402 if (foldEquivalentReductionCmp(
I))
7404 if (foldReduceAddCmpZero(
I))
7407 case Instruction::FCmp:
7408 if (foldExtractExtract(
I))
7411 case Instruction::Or:
7412 if (foldConcatOfBoolMasks(
I))
7417 if (foldExtractExtract(
I))
7419 if (foldExtractedCmps(
I))
7421 if (foldBinopOfReductions(
I))
7430 bool MadeChange =
false;
7431 for (BasicBlock &BB :
F) {
7443 MadeChange |= FoldInst(*
I);
7450 while (!Worklist.isEmpty()) {
7453 while (Instruction *
I = Worklist.popDeferred()) {
7471 MadeChange |= FoldInst(*
I);
7487 CostKind, TryEarlyFoldsOnly);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
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 defines the DenseMap class.
This is the interface for a simple mod/ref and alias analysis over globals.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines generic set operations that may be used on set's of different types,...
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 bool isEquivBitcast(Value *X, Value *Y)
Helper to peek through bitcasts to the same value.
static SmallVector< Value *, 8 > getInstrOperandsAtIdx(ArrayRef< Value * > Members, unsigned OperandIndex)
Return the operand at OperandIndex of each Members.
static bool isFreeConcat(ArrayRef< InstLane > Item, TTI::TargetCostKind CostKind, const TargetTransformInfo &TTI)
Detect concat of multiple values into a vector.
static void analyzeCostOfVecReduction(const IntrinsicInst &II, TTI::TargetCostKind CostKind, const TargetTransformInfo &TTI, InstructionCost &CostBeforeReduction, InstructionCost &CostAfterReduction)
static Value * generateNewInstTree(ArrayRef< InstLane > Item, Use *From, const DenseSet< std::pair< Value *, Use * > > &IdentityLeafs, const DenseSet< std::pair< Value *, Use * > > &SplatLeafs, const DenseSet< std::pair< Value *, Use * > > &ConcatLeafs, IRBuilderBase &Builder, InstructionWorklist &WorkList, const TargetTransformInfo *TTI)
static SmallVector< InstLane > generateInstLaneVectorFromOperand(ArrayRef< InstLane > Item, int Op)
static Value * createShiftShuffle(Value *Vec, unsigned OldIndex, unsigned NewIndex, IRBuilderBase &Builder)
Create a shuffle that translates (shifts) 1 element from the input vector to a new element location.
std::pair< Value *, int > InstLane
static Value * createWideInstruction(Instruction *NarrowInst, ArrayRef< Value * > NewOperands, VectorType *WideResultTy, IRBuilderBase &Builder)
static unsigned getNumDataOperands(const Instruction *Inst)
Return the number of data operands of Inst.
static bool isKnownNonPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Used by foldReduceAddCmpZero to check if we can prove that a value is non-positive.
static bool isSupportedElementwise(Instruction *Inst)
Return true if Inst is an elementwise operation that can be rebuilt at a wider element count.
static Value * materializeScalarizedGEPIndex(Value *Idx, IntegerType *GEPIndexTy, IRBuilderBase &Builder)
Materialize an index for a scalarized GEP after profitability is known.
static Align computeAlignmentAfterScalarization(Align VectorAlignment, Type *ScalarType, Value *Idx, const DataLayout &DL)
The memory operation on a vector of ScalarType had alignment of VectorAlignment.
static bool feedsIntoVectorReduction(ShuffleVectorInst *SVI)
Returns true if this ShuffleVectorInst eventually feeds into a vector reduction intrinsic (e....
static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI)
static const unsigned InvalidIndex
static Value * getCommonSplatValue(ArrayRef< Value * > Values)
Return the common splat value of Values.
static IntegerType * getScalarizedGEPIndexInfo(VectorType *VecTy, Value *Idx, Type *PtrTy, const DataLayout &DL)
Return the GEP index type if the unsigned vector index Idx can be represented by an inbounds GEP.
static Value * translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex, IRBuilderBase &Builder)
Given an extract element instruction with constant index operand, shuffle the source vector (shift th...
static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx, const SimplifyQuery &SQ)
Check if it is legal to scalarize a memory access to VecTy at index Idx.
static bool canWidenDeinterleavedOperations(const VectorizeOptions &Opts, ArrayRef< Value * > Members, DenseSet< Value * > &Visited, SmallPtrSetImpl< User * > &UndroppableUsers)
Check whether the tree of elementwise operations each feeding Members can be rebuilt at the interleav...
static unsigned getAlignedNumElements(unsigned MaxIdx, FixedVectorType *LoadTy, const TargetTransformInfo &TTI, const DataLayout &DL)
Given the maximum shuffle index and load vector type, compute the number of elements for the shrunk l...
static InstLane lookThroughShuffles(Value *V, int Lane)
static IntrinsicInst * getCommonDeinterleavedSource(ArrayRef< Value * > Members)
Return the common deinterleave intrinsic if Members are its extracts in field order.
static bool isMemModifiedBetween(const VectorizeOptions &Opts, BasicBlock::iterator Begin, BasicBlock::iterator End, const MemoryLocation &Loc, AAResults &AA)
static Value * widenDeinterleavedOperations(const SmallVector< Value *, 8 > &Members, ElementCount WideEC, IRBuilderBase &Builder, DenseMap< SmallVector< Value *, 8 >, Value * > &WideValueCache)
static constexpr int Concat[]
A manager for alias analyses.
Class for arbitrary precision integers.
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
uint64_t getZExtValue() const
Get zero extended value.
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.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
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.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
bool isNegative() const
Determine sign of this APInt.
unsigned countl_one() const
Count the number of leading one bits.
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
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.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
bool isOne() const
Determine if this is a value of 1.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
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),...
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
const T & front() const
Get the first element.
size_t size() const
Get the array size.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
InstListType::iterator iterator
Instruction iterators...
BinaryOps getOpcode() const
Represents analyses that only rely on functions' control flow.
Value * getArgOperand(unsigned i) const
void addParamAttrs(unsigned ArgNo, const AttrBuilder &B)
Adds attributes to the indicated argument.
This is the base class for all instructions that perform data casts.
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 ...
This class is the base class for the comparison instructions.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
bool isFPPredicate() const
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
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 ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
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)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
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 > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Convenience struct for specifying and reasoning about fast-math flags.
bool noSignedZeros() const
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static FixedVectorType * getDoubleElementsVectorType(FixedVectorType *VTy)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
This class represents a freeze function that returns random concrete value if an operand is either a ...
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Value * CreateNoWrapBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, bool IsNUW, bool IsNSW, const Twine &Name="")
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
ConstantInt * getTrue()
Get the constant value for i1 true.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateFCmpFMF(CmpInst::Predicate P, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Value * CreateBinOpFMF(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateUnOpFMF(Instruction::UnaryOps Opc, Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateExactBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, bool IsExact, const Twine &Name="")
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateFNegFMF(Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
void push(Instruction *I)
Push the instruction onto the worklist stack.
void remove(Instruction *I)
Remove I from the worklist if it exists.
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
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...
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
user_iterator user_begin()
@ CompareCallTargets
Check for equivalence by comparing call targets.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isIdempotent() const
Return true if the instruction is idempotent:
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
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.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void setAlignment(Align Align)
Value * getPointerOperand()
Type * getPointerOperandType() const
Align getAlign() const
Return the alignment of the access that is being performed.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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.
This class represents the LLVM 'select' instruction.
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
This instruction constructs a fixed permutation of two input vectors.
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void setAlignment(Align Align)
Analysis pass providing the TargetTransformInfo.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
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.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isIEEELikeFPTy() const
Return true if this is a well-behaved IEEE-like type, which has a IEEE compatible layout,...
A Use represents the edge between a Value definition and its users.
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.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
unsigned getValueID() const
Return an ID for the concrete type of this object.
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 PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
constexpr ScalarTy getFixedValue() const
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS*X will result in a value whose quantity matches our own.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
constexpr bool isZero() const
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
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)
auto m_BSwap(const Opnd0 &Op0)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_BitReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(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.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
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)
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.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
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.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
auto m_AnyIntrinsic()
Matches any intrinsic call and ignore it.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinOpPred_match< LHS, RHS, is_bitwiselogic_op, true > m_c_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations in either order.
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))
auto m_Deinterleave2(const Opnd &Op)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
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)
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.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
@ Valid
The data is already valid.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
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 cl::opt< bool > ProfcheckDisableMetadataFixes
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
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 Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
RelativeUniformCounterPtr Values
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Value * simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q)
Given operand for a UnaryOperator, fold the result or return null.
scope_exit(Callable) -> scope_exit< Callable >
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
LLVM_ABI unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
LLVM_ABI Value * simplifyCall(CallBase *Call, Value *Callee, ArrayRef< Value * > Args, const SimplifyQuery &Q)
Given a callsite, callee, and arguments, fold the result or return null.
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...
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...
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
LLVM_ABI bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Propagate metadata that can be preserved after vectorization from VL to I, retaining only information...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
unsigned M1(unsigned Val)
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...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
auto reverse(ContainerTy &&C)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI unsigned getDeinterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.deinterleaveN intrinsics.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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 void propagateIRFlags(Value *I, ArrayRef< Value * > VL, Value *OpValue=nullptr, bool IncludeWrapFlags=true)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
constexpr int PoisonMaskElem
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
LLVM_ABI void narrowShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Replace each shuffle mask index with the scaled sequential indices for an equivalent mask of narrowed...
LLVM_ABI Intrinsic::ID getReductionForBinop(Instruction::BinaryOps Opc)
Returns the reduction intrinsic id corresponding to the binary operation.
@ And
Bitwise or logical AND 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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
unsigned M0(unsigned Val)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
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...
const VectorizeOptions & getVectorizeOptions(const LLVMContext &C)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicID(Intrinsic::ID IID)
Returns the llvm.vector.reduce min/max intrinsic that corresponds to the intrinsic op.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
This struct is a compact representation of a valid (non-zero power of two) alignment.
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
SimplifyQuery getWithInstruction(const Instruction *I) const