101 using namespace llvm;
105 #define SV_NAME "slp-vectorizer" 106 #define DEBUG_TYPE "SLP" 108 STATISTIC(NumVectorInstructions,
"Number of vector instructions generated");
112 cl::desc(
"Run the SLP vectorization passes"));
116 cl::desc(
"Only vectorize if you gain more than this " 121 cl::desc(
"Attempt to vectorize horizontal reductions"));
126 "Attempt to vectorize horizontal reductions feeding into a store"));
130 cl::desc(
"Attempt to vectorize for this register size in bits"));
134 cl::desc(
"Maximum depth of the lookup for consecutive stores."));
142 cl::desc(
"Limit the size of the SLP scheduling region per block"));
146 cl::desc(
"Attempt to vectorize for this register size in bits"));
150 cl::desc(
"Limit the recursion depth when building a vectorizable tree"));
154 cl::desc(
"Only vectorize small trees if they are fully vectorizable"));
160 cl::desc(
"The maximum look-ahead depth for operand reordering scores"));
167 cl::desc(
"The maximum number of users to visit while visiting the " 168 "predecessors. This prevents compilation time increase."));
172 cl::desc(
"Display the SLP trees with Graphviz"));
206 for (
int i = 1,
e = VL.
size(); i <
e; i++) {
223 if (!isa<Constant>(i) || isa<ConstantExpr>(i) || isa<GlobalValue>(i))
230 for (
unsigned i = 1,
e = VL.
size(); i <
e; ++i)
238 if (
auto *IC = dyn_cast<CmpInst>(I))
239 return IC->isCommutative();
286 auto *EI0 = cast<ExtractElementInst>(VL[0]);
287 unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
288 Value *Vec1 =
nullptr;
289 Value *Vec2 =
nullptr;
290 enum ShuffleMode { Unknown,
Select, Permute };
291 ShuffleMode CommonShuffleMode = Unknown;
292 for (
unsigned I = 0,
E = VL.
size();
I <
E; ++
I) {
293 auto *EI = cast<ExtractElementInst>(VL[
I]);
294 auto *Vec = EI->getVectorOperand();
296 if (Vec->getType()->getVectorNumElements() !=
Size)
302 if (Idx->getValue().uge(Size))
304 unsigned IntIdx = Idx->getValue().getZExtValue();
306 if (isa<UndefValue>(Vec))
310 if (!Vec1 || Vec1 == Vec)
312 else if (!Vec2 || Vec2 == Vec)
316 if (CommonShuffleMode == Permute)
321 CommonShuffleMode = Permute;
324 CommonShuffleMode =
Select;
327 if (CommonShuffleMode ==
Select && Vec2)
338 struct InstructionsState {
340 Value *OpValue =
nullptr;
351 unsigned getAltOpcode()
const {
356 bool isAltShuffle()
const {
return getOpcode() != getAltOpcode(); }
360 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
363 InstructionsState() =
delete;
365 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
375 if (
I && S.isOpcodeOrAlt(
I))
396 unsigned BaseIndex = 0) {
399 return InstructionsState(VL[BaseIndex],
nullptr,
nullptr);
401 bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
402 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
403 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->
getOpcode();
404 unsigned AltOpcode = Opcode;
405 unsigned AltIndex = BaseIndex;
409 for (
int Cnt = 0,
E = VL.
size(); Cnt <
E; Cnt++) {
410 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->
getOpcode();
411 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
412 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
416 AltOpcode = InstOpcode;
420 }
else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
421 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
422 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
424 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
426 if (Opcode == AltOpcode) {
429 "Cast isn't safe for alternation, logic needs to be updated!");
430 AltOpcode = InstOpcode;
435 }
else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
437 return InstructionsState(VL[BaseIndex],
nullptr,
nullptr);
440 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
441 cast<Instruction>(VL[AltIndex]));
447 Type *Ty = VL[0]->getType();
448 for (
int i = 1,
e = VL.
size(); i <
e; i++)
458 assert((Opcode == Instruction::ExtractElement ||
459 Opcode == Instruction::ExtractValue) &&
460 "Expected extractelement or extractvalue instruction.");
461 if (Opcode == Instruction::ExtractElement) {
465 return CI->getZExtValue();
480 LoadInst *LI = cast<LoadInst>(UserInst);
488 CallInst *CI = cast<CallInst>(UserInst);
505 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
512 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
513 return LI->isSimple();
515 return SI->isSimple();
517 return !
MI->isVolatile();
542 :
F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
543 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
554 MaxVecRegSize = TTI->getRegisterBitWidth(
true);
559 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
564 Value *vectorizeTree();
573 int getSpillCost()
const;
594 VectorizableTree.clear();
595 ScalarToTreeEntry.clear();
597 ExternalUses.clear();
598 NumOpsWantToKeepOrder.clear();
599 NumOpsWantToKeepOriginalOrder = 0;
600 for (
auto &Iter : BlocksSchedules) {
601 BlockScheduling *BS = Iter.second.get();
610 void optimizeGatherSequence();
614 auto I = std::max_element(
615 NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
616 [](
const decltype(NumOpsWantToKeepOrder)::value_type &D1,
617 const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
618 return D1.second < D2.second;
620 if (
I == NumOpsWantToKeepOrder.end() ||
621 I->getSecond() <= NumOpsWantToKeepOriginalOrder)
632 unsigned getVectorElementSize(
Value *V)
const;
640 return MaxVecRegSize;
645 return MinVecRegSize;
658 bool isTreeTinyAndNotFullyVectorizable()
const;
667 bool isLoadCombineReductionCandidate(
unsigned ReductionOpcode)
const;
678 : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
680 TreeEntry *UserTE =
nullptr;
682 unsigned EdgeIdx = UINT_MAX;
692 <<
" EdgeIdx:" << EdgeIdx <<
"}";
727 OperandData() =
default;
728 OperandData(
Value *V,
bool APO,
bool IsUsed)
729 : V(V), APO(APO), IsUsed(IsUsed) {}
748 enum class ReorderingMode {
766 OperandData &getData(
unsigned OpIdx,
unsigned Lane) {
767 return OpsVec[OpIdx][Lane];
771 const OperandData &getData(
unsigned OpIdx,
unsigned Lane)
const {
772 return OpsVec[OpIdx][Lane];
777 for (
unsigned OpIdx = 0, NumOperands = getNumOperands();
778 OpIdx != NumOperands; ++OpIdx)
779 for (
unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
781 OpsVec[OpIdx][Lane].IsUsed =
false;
785 void swap(
unsigned OpIdx1,
unsigned OpIdx2,
unsigned Lane) {
786 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
798 static const int ScoreConsecutiveLoads = 3;
800 static const int ScoreConsecutiveExtracts = 3;
802 static const int ScoreConstants = 2;
804 static const int ScoreSameOpcode = 2;
806 static const int ScoreAltOpcodes = 1;
808 static const int ScoreSplat = 1;
810 static const int ScoreUndef = 1;
812 static const int ScoreFail = 0;
814 static const int ExternalUseCost = 1;
816 static const int UserInDiffLaneCost = ExternalUseCost;
825 ? VLOperands::ScoreConsecutiveLoads
826 : VLOperands::ScoreFail;
831 return VLOperands::ScoreConstants;
840 return VLOperands::ScoreConsecutiveExtracts;
846 return VLOperands::ScoreSplat;
850 if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
851 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
852 : VLOperands::ScoreSameOpcode;
855 if (isa<UndefValue>(V2))
856 return VLOperands::ScoreUndef;
858 return VLOperands::ScoreFail;
867 int getExternalUsesCost(
const std::pair<Value *, int> &LHS,
868 const std::pair<Value *, int> &RHS) {
871 for (
int Idx = 0, IdxE = Values.
size(); Idx != IdxE; ++Idx) {
872 Value *V = Values[Idx].first;
875 int Ln = std::min(LHS.second, RHS.second) + Idx;
876 assert(Ln >= 0 &&
"Bad lane calculation");
879 if (
const TreeEntry *UserTE = R.getTreeEntry(U)) {
882 assert(It != UserTE->Scalars.end() &&
"U is in UserTE");
883 int UserLn = std::distance(UserTE->Scalars.begin(), It);
884 assert(UserLn >= 0 &&
"Bad lane");
886 Cost += UserInDiffLaneCost;
889 auto It2 = InLookAheadValues.
find(U);
890 if (It2 != InLookAheadValues.
end()) {
892 if (It2->second != Ln)
893 Cost += UserInDiffLaneCost;
896 Cost += ExternalUseCost;
900 if (--UsersBudget == 0)
928 int getScoreAtLevelRec(
const std::pair<Value *, int> &LHS,
929 const std::pair<Value *, int> &RHS,
int CurrLevel,
932 Value *V1 = LHS.first;
933 Value *V2 = RHS.first;
935 int ShallowScoreAtThisLevel =
936 std::max((
int)ScoreFail, getShallowScore(V1, V2, DL, SE) -
937 getExternalUsesCost(LHS, RHS));
938 int Lane1 = LHS.second;
939 int Lane2 = RHS.second;
947 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
948 ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
949 (isa<LoadInst>(I1) && isa<LoadInst>(I2) && ShallowScoreAtThisLevel))
950 return ShallowScoreAtThisLevel;
951 assert(I1 && I2 &&
"Should have early exited.");
954 InLookAheadValues[V1] = Lane1;
955 InLookAheadValues[
V2] = Lane2;
962 for (
unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
963 OpIdx1 != NumOperands1; ++OpIdx1) {
966 unsigned MaxOpIdx2 = 0;
967 bool FoundBest =
false;
971 ? I2->getNumOperands()
972 : std::min(I2->getNumOperands(), OpIdx1 + 1);
973 assert(FromIdx <= ToIdx &&
"Bad index");
974 for (
unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
976 if (Op2Used.
count(OpIdx2))
979 int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
980 {I2->getOperand(OpIdx2), Lane2},
981 CurrLevel + 1, MaxLevel);
983 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
984 MaxTmpScore = TmpScore;
991 Op2Used.
insert(MaxOpIdx2);
992 ShallowScoreAtThisLevel += MaxTmpScore;
995 return ShallowScoreAtThisLevel;
1003 int getLookAheadScore(
const std::pair<Value *, int> &LHS,
1004 const std::pair<Value *, int> &RHS) {
1005 InLookAheadValues.
clear();
1013 getBestOperand(
unsigned OpIdx,
int Lane,
int LastLane,
1015 unsigned NumOperands = getNumOperands();
1018 Value *OpLastLane = getData(OpIdx, LastLane).V;
1021 ReorderingMode RMode = ReorderingModes[OpIdx];
1024 bool OpIdxAPO = getData(OpIdx, Lane).APO;
1035 for (
unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1037 OperandData &OpData = getData(Idx, Lane);
1039 bool OpAPO = OpData.APO;
1048 if (OpAPO != OpIdxAPO)
1055 case ReorderingMode::Opcode: {
1056 bool LeftToRight = Lane > LastLane;
1057 Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1058 Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1060 getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1061 if (Score > BestOp.Score) {
1063 BestOp.Score = Score;
1067 case ReorderingMode::Splat:
1068 if (Op == OpLastLane)
1077 getData(BestOp.Idx.getValue(), Lane).IsUsed =
true;
1087 unsigned getBestLaneToStartReordering()
const {
1088 unsigned BestLane = 0;
1089 unsigned Min = UINT_MAX;
1090 for (
unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1092 unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane);
1093 if (NumFreeOps < Min) {
1104 unsigned getMaxNumOperandsThatCanBeReordered(
unsigned Lane)
const {
1105 unsigned CntTrue = 0;
1106 unsigned NumOperands = getNumOperands();
1113 for (
unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx)
1114 if (getData(OpIdx, Lane).APO)
1116 unsigned CntFalse = NumOperands - CntTrue;
1117 return std::max(CntTrue, CntFalse);
1124 "Expected same number of lanes");
1125 assert(isa<Instruction>(VL[0]) &&
"Expected instruction");
1126 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1127 OpsVec.
resize(NumOperands);
1128 unsigned NumLanes = VL.
size();
1129 for (
unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1130 OpsVec[OpIdx].
resize(NumLanes);
1131 for (
unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1132 assert(isa<Instruction>(VL[Lane]) &&
"Expected instruction");
1143 bool IsInverseOperation = !
isCommutative(cast<Instruction>(VL[Lane]));
1144 bool APO = (OpIdx == 0) ?
false : IsInverseOperation;
1145 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1152 unsigned getNumOperands()
const {
return OpsVec.
size(); }
1155 unsigned getNumLanes()
const {
return OpsVec[0].
size(); }
1158 Value *getValue(
unsigned OpIdx,
unsigned Lane)
const {
1159 return getData(OpIdx, Lane).V;
1163 bool empty()
const {
return OpsVec.
empty(); }
1171 bool shouldBroadcast(
Value *
Op,
unsigned OpIdx,
unsigned Lane) {
1172 bool OpAPO = getData(OpIdx, Lane).APO;
1173 for (
unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1177 bool FoundCandidate =
false;
1178 for (
unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1179 OperandData &
Data = getData(OpI, Ln);
1180 if (Data.APO != OpAPO || Data.IsUsed)
1183 FoundCandidate =
true;
1188 if (!FoundCandidate)
1198 : DL(DL), SE(SE), R(R) {
1200 appendOperandsOfVL(RootVL);
1207 assert(OpsVec[OpIdx].
size() == getNumLanes() &&
1208 "Expected same num of lanes across all operands");
1209 for (
unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1210 OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1218 unsigned NumOperands = getNumOperands();
1219 unsigned NumLanes = getNumLanes();
1239 unsigned FirstLane = getBestLaneToStartReordering();
1242 for (
unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1243 Value *OpLane0 = getValue(OpIdx, FirstLane);
1246 if (isa<LoadInst>(OpLane0))
1248 else if (isa<Instruction>(OpLane0)) {
1250 if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1251 ReorderingModes[OpIdx] = ReorderingMode::Splat;
1253 ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1255 else if (isa<Constant>(OpLane0))
1257 else if (isa<Argument>(OpLane0))
1259 ReorderingModes[OpIdx] = ReorderingMode::Splat;
1271 bool StrategyFailed =
false;
1278 for (
unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1281 int Lane = FirstLane +
Direction * Distance;
1282 if (Lane < 0 || Lane >= (
int)NumLanes)
1285 assert(LastLane >= 0 && LastLane < (
int)NumLanes &&
1288 for (
unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1291 getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1303 StrategyFailed =
true;
1309 if (!StrategyFailed)
1314 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1319 case ReorderingMode::Opcode:
1323 case ReorderingMode::Splat:
1333 return OS << getModeStr(RMode);
1338 printMode(RMode,
dbgs());
1342 return printMode(RMode, OS);
1346 const unsigned Indent = 2;
1349 OS <<
"Operand " << Cnt++ <<
"\n";
1350 for (
const OperandData &OpData : OpDataVec) {
1351 OS.
indent(Indent) <<
"{";
1352 if (
Value *V = OpData.V)
1356 OS <<
", APO:" << OpData.APO <<
"}\n";
1381 int getEntryCost(TreeEntry *
E);
1396 Value *vectorizeTree(TreeEntry *E);
1412 void setInsertPointAfterBundle(TreeEntry *E);
1419 bool isFullyVectorizableTinyTree()
const;
1431 TreeEntry(VecTreeTy &Container) : Container(Container) {}
1435 if (VL.
size() == Scalars.size())
1437 return VL.
size() == ReuseShuffleIndices.size() &&
1439 VL.
begin(), VL.
end(), ReuseShuffleIndices.begin(),
1440 [
this](
Value *V,
unsigned Idx) {
return V == Scalars[Idx]; });
1447 Value *VectorizedValue =
nullptr;
1450 enum EntryState { Vectorize, NeedToGather };
1465 VecTreeTy &Container;
1487 if (Operands.
size() < OpIdx + 1)
1488 Operands.
resize(OpIdx + 1);
1489 assert(Operands[OpIdx].
size() == 0 &&
"Already resized?");
1490 Operands[OpIdx].
resize(Scalars.size());
1491 for (
unsigned Lane = 0, E = Scalars.size(); Lane !=
E; ++Lane)
1492 Operands[OpIdx][Lane] = OpVL[Lane];
1496 void setOperandsInOrder() {
1497 assert(Operands.
empty() &&
"Already initialized?");
1498 auto *I0 = cast<Instruction>(Scalars[0]);
1499 Operands.
resize(I0->getNumOperands());
1500 unsigned NumLanes = Scalars.size();
1501 for (
unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1502 OpIdx != NumOperands; ++OpIdx) {
1503 Operands[OpIdx].
resize(NumLanes);
1504 for (
unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1505 auto *I = cast<Instruction>(Scalars[Lane]);
1507 "Expected same number of operands");
1508 Operands[OpIdx][Lane] = I->
getOperand(OpIdx);
1515 assert(OpIdx < Operands.
size() &&
"Off bounds");
1516 return Operands[OpIdx];
1520 unsigned getNumOperands()
const {
return Operands.
size(); }
1523 Value *getSingleOperand(
unsigned OpIdx)
const {
1524 assert(OpIdx < Operands.
size() &&
"Off bounds");
1525 assert(!Operands[OpIdx].
empty() &&
"No operand available");
1526 return Operands[OpIdx][0];
1530 bool isAltShuffle()
const {
1535 unsigned CheckedOpcode = I->
getOpcode();
1537 getAltOpcode() == CheckedOpcode);
1545 if (I && isOpcodeOrAlt(I))
1550 void setOperations(
const InstructionsState &S) {
1565 return MainOp ? MainOp->
getOpcode() : 0;
1568 unsigned getAltOpcode()
const {
1573 bool updateStateIfReorder() {
1574 if (ReorderIndices.
empty())
1584 dbgs() << Idx <<
".\n";
1585 for (
unsigned OpI = 0, OpE = Operands.
size(); OpI != OpE; ++OpI) {
1586 dbgs() <<
"Operand " << OpI <<
":\n";
1587 for (
const Value *V : Operands[OpI])
1590 dbgs() <<
"Scalars: \n";
1591 for (
Value *V : Scalars)
1593 dbgs() <<
"State: ";
1596 dbgs() <<
"Vectorize\n";
1599 dbgs() <<
"NeedToGather\n";
1602 dbgs() <<
"MainOp: ";
1604 dbgs() << *MainOp <<
"\n";
1607 dbgs() <<
"AltOp: ";
1609 dbgs() << *AltOp <<
"\n";
1612 dbgs() <<
"VectorizedValue: ";
1613 if (VectorizedValue)
1614 dbgs() << *VectorizedValue <<
"\n";
1617 dbgs() <<
"ReuseShuffleIndices: ";
1618 if (ReuseShuffleIndices.
empty())
1621 for (
unsigned ReuseIdx : ReuseShuffleIndices)
1622 dbgs() << ReuseIdx <<
", ";
1624 dbgs() <<
"ReorderIndices: ";
1625 for (
unsigned ReorderIdx : ReorderIndices)
1626 dbgs() << ReorderIdx <<
", ";
1628 dbgs() <<
"UserTreeIndices: ";
1629 for (
const auto &EInfo : UserTreeIndices)
1630 dbgs() << EInfo <<
", ";
1638 const InstructionsState &S,
1642 bool Vectorized = (
bool)Bundle;
1643 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
1644 TreeEntry *Last = VectorizableTree.back().get();
1645 Last->Idx = VectorizableTree.size() - 1;
1646 Last->Scalars.insert(Last->Scalars.begin(), VL.
begin(), VL.
end());
1647 Last->State = Vectorized ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
1648 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
1649 ReuseShuffleIndices.end());
1650 Last->ReorderIndices = ReorderIndices;
1651 Last->setOperations(S);
1653 for (
int i = 0,
e = VL.
size(); i !=
e; ++i) {
1654 assert(!getTreeEntry(VL[i]) &&
"Scalar already in tree!");
1655 ScalarToTreeEntry[VL[i]] = Last;
1659 for (ScheduleData *BundleMember = Bundle.
getValue(); BundleMember;
1660 BundleMember = BundleMember->NextInBundle) {
1661 BundleMember->TE = Last;
1662 BundleMember->Lane = Lane;
1666 "Bundle and VL out of sync");
1668 MustGather.insert(VL.
begin(), VL.
end());
1672 Last->UserTreeIndices.push_back(UserTreeIdx);
1684 for (
unsigned Id = 0, IdE = VectorizableTree.
size();
Id != IdE; ++
Id) {
1685 VectorizableTree[
Id]->dump();
1691 TreeEntry *getTreeEntry(
Value *V) {
1692 auto I = ScalarToTreeEntry.find(V);
1693 if (I != ScalarToTreeEntry.end())
1698 const TreeEntry *getTreeEntry(
Value *V)
const {
1699 auto I = ScalarToTreeEntry.find(V);
1700 if (I != ScalarToTreeEntry.end())
1712 struct ExternalUser {
1734 AliasCacheKey key = std::make_pair(Inst1, Inst2);
1740 bool aliased =
true;
1743 aliased = AA->alias(Loc1, Loc2);
1750 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
1763 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
1764 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
1790 struct ScheduleData {
1793 enum { InvalidDeps = -1 };
1795 ScheduleData() =
default;
1797 void init(
int BlockSchedulingRegionID,
Value *OpVal) {
1798 FirstInBundle =
this;
1799 NextInBundle =
nullptr;
1800 NextLoadStore =
nullptr;
1801 IsScheduled =
false;
1802 SchedulingRegionID = BlockSchedulingRegionID;
1803 UnscheduledDepsInBundle = UnscheduledDeps;
1804 clearDependencies();
1811 bool hasValidDependencies()
const {
return Dependencies != InvalidDeps; }
1815 bool isSchedulingEntity()
const {
return FirstInBundle ==
this; }
1819 bool isPartOfBundle()
const {
1820 return NextInBundle !=
nullptr || FirstInBundle !=
this;
1825 bool isReady()
const {
1826 assert(isSchedulingEntity() &&
1827 "can't consider non-scheduling entity for ready list");
1828 return UnscheduledDepsInBundle == 0 && !IsScheduled;
1833 int incrementUnscheduledDeps(
int Incr) {
1834 UnscheduledDeps += Incr;
1835 return FirstInBundle->UnscheduledDepsInBundle += Incr;
1840 void resetUnscheduledDeps() {
1841 incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
1845 void clearDependencies() {
1846 Dependencies = InvalidDeps;
1847 resetUnscheduledDeps();
1848 MemoryDependencies.clear();
1852 if (!isSchedulingEntity()) {
1853 os <<
"/ " << *Inst;
1854 }
else if (NextInBundle) {
1856 ScheduleData *SD = NextInBundle;
1858 os <<
';' << *SD->Inst;
1859 SD = SD->NextInBundle;
1871 ScheduleData *FirstInBundle =
nullptr;
1875 ScheduleData *NextInBundle =
nullptr;
1879 ScheduleData *NextLoadStore =
nullptr;
1887 int SchedulingRegionID = 0;
1890 int SchedulingPriority = 0;
1896 int Dependencies = InvalidDeps;
1902 int UnscheduledDeps = InvalidDeps;
1906 int UnscheduledDepsInBundle = InvalidDeps;
1910 bool IsScheduled =
false;
1913 Value *OpValue =
nullptr;
1916 TreeEntry *
TE =
nullptr;
1924 const BoUpSLP::ScheduleData &SD) {
1934 struct BlockScheduling {
1936 : BB(BB), ChunkSize(BB->
size()), ChunkPos(ChunkSize) {}
1940 ScheduleStart =
nullptr;
1941 ScheduleEnd =
nullptr;
1942 FirstLoadStoreInRegion =
nullptr;
1943 LastLoadStoreInRegion =
nullptr;
1947 ScheduleRegionSizeLimit -= ScheduleRegionSize;
1948 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
1950 ScheduleRegionSize = 0;
1954 ++SchedulingRegionID;
1957 ScheduleData *getScheduleData(
Value *V) {
1958 ScheduleData *SD = ScheduleDataMap[V];
1959 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1966 return getScheduleData(V);
1967 auto I = ExtraScheduleDataMap.find(V);
1968 if (I != ExtraScheduleDataMap.end()) {
1969 ScheduleData *SD = I->second[
Key];
1970 if (SD && SD->SchedulingRegionID == SchedulingRegionID)
1976 bool isInSchedulingRegion(ScheduleData *SD)
const {
1977 return SD->SchedulingRegionID == SchedulingRegionID;
1982 template <
typename ReadyListType>
1983 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
1984 SD->IsScheduled =
true;
1987 ScheduleData *BundleMember = SD;
1988 while (BundleMember) {
1989 if (BundleMember->Inst != BundleMember->OpValue) {
1990 BundleMember = BundleMember->NextInBundle;
1996 auto &&DecrUnsched = [
this, &ReadyList](
Instruction *
I) {
1997 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
1998 if (OpDef && OpDef->hasValidDependencies() &&
1999 OpDef->incrementUnscheduledDeps(-1) == 0) {
2003 ScheduleData *DepBundle = OpDef->FirstInBundle;
2004 assert(!DepBundle->IsScheduled &&
2005 "already scheduled bundle gets ready");
2006 ReadyList.insert(DepBundle);
2008 <<
"SLP: gets ready (def): " << *DepBundle <<
"\n");
2016 if (TreeEntry *
TE = BundleMember->TE) {
2017 int Lane = BundleMember->Lane;
2018 assert(Lane >= 0 &&
"Lane not set");
2019 for (
unsigned OpIdx = 0, NumOperands =
TE->getNumOperands();
2020 OpIdx != NumOperands; ++OpIdx)
2021 if (
auto *I = dyn_cast<Instruction>(
TE->getOperand(OpIdx)[Lane]))
2026 for (
Use &U : BundleMember->Inst->operands())
2027 if (
auto *I = dyn_cast<Instruction>(U.get()))
2031 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2032 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2035 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2036 assert(!DepBundle->IsScheduled &&
2037 "already scheduled bundle gets ready");
2038 ReadyList.insert(DepBundle);
2040 <<
"SLP: gets ready (mem): " << *DepBundle <<
"\n");
2043 BundleMember = BundleMember->NextInBundle;
2047 void doForAllOpcodes(
Value *V,
2049 if (ScheduleData *SD = getScheduleData(V))
2051 auto I = ExtraScheduleDataMap.find(V);
2052 if (I != ExtraScheduleDataMap.end())
2053 for (
auto &
P : I->second)
2054 if (
P.second->SchedulingRegionID == SchedulingRegionID)
2059 template <
typename ReadyListType>
2060 void initialFillReadyList(ReadyListType &ReadyList) {
2061 for (
auto *I = ScheduleStart; I != ScheduleEnd; I = I->
getNextNode()) {
2062 doForAllOpcodes(I, [&](ScheduleData *SD) {
2063 if (SD->isSchedulingEntity() && SD->isReady()) {
2064 ReadyList.insert(SD);
2066 <<
"SLP: initially in ready list: " << *I <<
"\n");
2079 const InstructionsState &S);
2085 ScheduleData *allocateScheduleDataChunks();
2089 bool extendSchedulingRegion(
Value *V,
const InstructionsState &S);
2094 ScheduleData *PrevLoadStore,
2095 ScheduleData *NextLoadStore);
2099 void calculateDependencies(ScheduleData *SD,
bool InsertInReadyList,
2103 void resetSchedule();
2108 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2124 ExtraScheduleDataMap;
2127 void insert(ScheduleData *SD) { push_back(SD); }
2131 ReadyList ReadyInsts;
2141 ScheduleData *FirstLoadStoreInRegion =
nullptr;
2145 ScheduleData *LastLoadStoreInRegion =
nullptr;
2148 int ScheduleRegionSize = 0;
2157 int SchedulingRegionID = 1;
2165 void scheduleBlock(BlockScheduling *BS);
2173 struct OrdersTypeDenseMapInfo {
2186 static unsigned getHashValue(
const OrdersType &V) {
2201 unsigned NumOpsWantToKeepOriginalOrder = 0;
2216 unsigned MaxVecRegSize;
2217 unsigned MinVecRegSize;
2242 struct ChildIteratorType
2244 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2255 return R.VectorizableTree[0].get();
2259 return {N->UserTreeIndices.begin(), N->Container};
2263 return {N->UserTreeIndices.end(), N->Container};
2268 class nodes_iterator {
2269 using ItTy = ContainerTy::iterator;
2279 bool operator!=(
const nodes_iterator &N2)
const {
return N2.It != It; }
2283 return nodes_iterator(R->VectorizableTree.begin());
2287 return nodes_iterator(R->VectorizableTree.end());
2290 static unsigned size(BoUpSLP *R) {
return R->VectorizableTree.size(); }
2301 if (
isSplat(Entry->Scalars)) {
2302 OS <<
"<splat> " << *Entry->Scalars[0];
2305 for (
auto V : Entry->Scalars) {
2308 R->ExternalUses.begin(), R->ExternalUses.end(),
2309 [&](
const BoUpSLP::ExternalUser &EU) {
return EU.Scalar == V; }))
2318 if (Entry->State == TreeEntry::NeedToGather)
2326 BoUpSLP::~BoUpSLP() {
2327 for (
const auto &Pair : DeletedInstructions) {
2330 if (Pair.getSecond()) {
2334 Pair.getFirst()->dropAllReferences();
2336 for (
const auto &Pair : DeletedInstructions) {
2337 assert(Pair.getFirst()->use_empty() &&
2338 "trying to erase instruction with users.");
2339 Pair.getFirst()->eraseFromParent();
2344 for (
auto *V : AV) {
2345 if (
auto *
I = dyn_cast<Instruction>(V))
2353 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
2360 UserIgnoreList = UserIgnoreLst;
2363 buildTree_rec(Roots, 0,
EdgeInfo());
2366 for (
auto &TEPtr : VectorizableTree) {
2367 TreeEntry *
Entry = TEPtr.get();
2370 if (Entry->State == TreeEntry::NeedToGather)
2374 for (
int Lane = 0,
LE = Entry->Scalars.size(); Lane !=
LE; ++Lane) {
2376 int FoundLane = Lane;
2377 if (!Entry->ReuseShuffleIndices.empty()) {
2379 std::distance(Entry->ReuseShuffleIndices.begin(),
2380 llvm::find(Entry->ReuseShuffleIndices, FoundLane));
2384 auto ExtI = ExternallyUsedValues.
find(Scalar);
2385 if (ExtI != ExternallyUsedValues.
end()) {
2386 LLVM_DEBUG(
dbgs() <<
"SLP: Need to extract: Extra arg from lane " 2387 << Lane <<
" from " << *Scalar <<
".\n");
2388 ExternalUses.emplace_back(Scalar,
nullptr, FoundLane);
2398 if (TreeEntry *UseEntry = getTreeEntry(U)) {
2399 Value *UseScalar = UseEntry->Scalars[0];
2403 if (UseScalar != U ||
2405 LLVM_DEBUG(
dbgs() <<
"SLP: \tInternal user will be removed:" << *U
2407 assert(UseEntry->State != TreeEntry::NeedToGather &&
"Bad state");
2416 LLVM_DEBUG(
dbgs() <<
"SLP: Need to extract:" << *U <<
" from lane " 2417 << Lane <<
" from " << *Scalar <<
".\n");
2418 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
2430 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to max recursion depth.\n");
2431 newTreeEntry(VL,
None , S, UserTreeIdx);
2436 if (S.OpValue->getType()->isVectorTy()) {
2438 newTreeEntry(VL,
None , S, UserTreeIdx);
2442 if (
StoreInst *
SI = dyn_cast<StoreInst>(S.OpValue))
2443 if (
SI->getValueOperand()->getType()->isVectorTy()) {
2444 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to store vector type.\n");
2445 newTreeEntry(VL,
None , S, UserTreeIdx);
2452 newTreeEntry(VL,
None , S, UserTreeIdx);
2460 for (
Value *V : VL) {
2461 if (EphValues.count(V)) {
2463 <<
") is ephemeral.\n");
2464 newTreeEntry(VL,
None , S, UserTreeIdx);
2470 if (TreeEntry *
E = getTreeEntry(S.OpValue)) {
2471 LLVM_DEBUG(
dbgs() <<
"SLP: \tChecking bundle: " << *S.OpValue <<
".\n");
2472 if (!
E->isSame(VL)) {
2473 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to partial overlap.\n");
2474 newTreeEntry(VL,
None , S, UserTreeIdx);
2479 E->UserTreeIndices.push_back(UserTreeIdx);
2480 LLVM_DEBUG(
dbgs() <<
"SLP: Perfect diamond merge at " << *S.OpValue
2486 for (
Value *V : VL) {
2490 if (getTreeEntry(
I)) {
2492 <<
") is already in tree.\n");
2493 newTreeEntry(VL,
None , S, UserTreeIdx);
2501 for (
Value *V : VL) {
2502 if (MustGather.count(V) ||
is_contained(UserIgnoreList, V)) {
2503 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering due to gathered scalar.\n");
2504 newTreeEntry(VL,
None , S, UserTreeIdx);
2511 auto *VL0 = cast<Instruction>(S.OpValue);
2514 if (!DT->isReachableFromEntry(BB)) {
2518 newTreeEntry(VL,
None , S, UserTreeIdx);
2526 for (
Value *V : VL) {
2532 size_t NumUniqueScalarValues = UniqueValues.
size();
2533 if (NumUniqueScalarValues == VL.size()) {
2534 ReuseShuffleIndicies.
clear();
2537 if (NumUniqueScalarValues <= 1 ||
2540 newTreeEntry(VL,
None , S, UserTreeIdx);
2546 auto &BSRef = BlocksSchedules[BB];
2548 BSRef = std::make_unique<BlockScheduling>(BB);
2550 BlockScheduling &BS = *BSRef.get();
2554 LLVM_DEBUG(
dbgs() <<
"SLP: We are not able to schedule this bundle!\n");
2555 assert((!BS.getScheduleData(VL0) ||
2556 !BS.getScheduleData(VL0)->isPartOfBundle()) &&
2557 "tryScheduleBundle should cancelScheduling on failure");
2558 newTreeEntry(VL,
None , S, UserTreeIdx,
2559 ReuseShuffleIndicies);
2562 LLVM_DEBUG(
dbgs() <<
"SLP: We are able to schedule this bundle.\n");
2564 unsigned ShuffleOrOp = S.isAltShuffle() ?
2565 (
unsigned) Instruction::ShuffleVector : S.getOpcode();
2566 switch (ShuffleOrOp) {
2567 case Instruction::PHI: {
2568 auto *PH = cast<PHINode>(VL0);
2571 for (
unsigned j = 0; j < VL.size(); ++j)
2572 for (
unsigned i = 0,
e = PH->getNumIncomingValues(); i <
e; ++i) {
2574 cast<PHINode>(VL[j])->getIncomingValueForBlock(
2575 PH->getIncomingBlock(i)));
2578 <<
"SLP: Need to swizzle PHINodes (terminator use).\n");
2579 BS.cancelScheduling(VL, VL0);
2580 newTreeEntry(VL,
None , S, UserTreeIdx,
2581 ReuseShuffleIndicies);
2587 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
2592 for (
unsigned i = 0, e = PH->getNumIncomingValues(); i <
e; ++i) {
2596 Operands.
push_back(cast<PHINode>(j)->getIncomingValueForBlock(
2597 PH->getIncomingBlock(i)));
2598 TE->setOperand(i, Operands);
2601 for (
unsigned OpIdx = 0, OpE = OperandsVec.
size(); OpIdx != OpE; ++OpIdx)
2602 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {
TE, OpIdx});
2605 case Instruction::ExtractValue:
2606 case Instruction::ExtractElement: {
2608 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
2610 LLVM_DEBUG(
dbgs() <<
"SLP: Reusing or shuffling extract sequence.\n");
2611 ++NumOpsWantToKeepOriginalOrder;
2612 newTreeEntry(VL, Bundle , S, UserTreeIdx,
2613 ReuseShuffleIndicies);
2617 Op0.
assign(VL.size(), VL0->getOperand(0));
2618 VectorizableTree.back()->setOperand(0, Op0);
2621 if (!CurrentOrder.
empty()) {
2623 dbgs() <<
"SLP: Reusing or shuffling of reordered extract sequence " 2625 for (
unsigned Idx : CurrentOrder)
2626 dbgs() <<
" " << Idx;
2631 auto StoredCurrentOrderAndNum =
2632 NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
2633 ++StoredCurrentOrderAndNum->getSecond();
2634 newTreeEntry(VL, Bundle , S, UserTreeIdx,
2635 ReuseShuffleIndicies,
2636 StoredCurrentOrderAndNum->getFirst());
2640 Op0.
assign(VL.size(), VL0->getOperand(0));
2641 VectorizableTree.back()->setOperand(0, Op0);
2645 newTreeEntry(VL,
None , S, UserTreeIdx,
2646 ReuseShuffleIndicies);
2647 BS.cancelScheduling(VL, VL0);
2657 Type *ScalarTy = VL0->getType();
2659 if (DL->getTypeSizeInBits(ScalarTy) !=
2660 DL->getTypeAllocSizeInBits(ScalarTy)) {
2661 BS.cancelScheduling(VL, VL0);
2662 newTreeEntry(VL,
None , S, UserTreeIdx,
2663 ReuseShuffleIndicies);
2664 LLVM_DEBUG(
dbgs() <<
"SLP: Gathering loads of non-packed type.\n");
2671 auto POIter = PointerOps.
begin();
2672 for (
Value *V : VL) {
2673 auto *L = cast<LoadInst>(V);
2674 if (!L->isSimple()) {
2675 BS.cancelScheduling(VL, VL0);
2676 newTreeEntry(VL,
None , S, UserTreeIdx,
2677 ReuseShuffleIndicies);
2681 *POIter = L->getPointerOperand();
2690 if (CurrentOrder.
empty()) {
2691 Ptr0 = PointerOps.front();
2692 PtrN = PointerOps.back();
2694 Ptr0 = PointerOps[CurrentOrder.
front()];
2695 PtrN = PointerOps[CurrentOrder.
back()];
2697 const SCEV *Scev0 = SE->getSCEV(Ptr0);
2698 const SCEV *ScevN = SE->getSCEV(PtrN);
2701 uint64_t
Size = DL->getTypeAllocSize(ScalarTy);
2703 if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) {
2704 if (CurrentOrder.
empty()) {
2706 ++NumOpsWantToKeepOriginalOrder;
2707 TreeEntry *
TE = newTreeEntry(VL, Bundle , S,
2708 UserTreeIdx, ReuseShuffleIndicies);
2709 TE->setOperandsInOrder();
2713 auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
2716 newTreeEntry(VL, Bundle , S, UserTreeIdx,
2717 ReuseShuffleIndicies,
I->getFirst());
2718 TE->setOperandsInOrder();
2726 BS.cancelScheduling(VL, VL0);
2727 newTreeEntry(VL,
None , S, UserTreeIdx,
2728 ReuseShuffleIndicies);
2731 case Instruction::ZExt:
2732 case Instruction::SExt:
2733 case Instruction::FPToUI:
2734 case Instruction::FPToSI:
2735 case Instruction::FPExt:
2736 case Instruction::PtrToInt:
2737 case Instruction::IntToPtr:
2738 case Instruction::SIToFP:
2739 case Instruction::UIToFP:
2740 case Instruction::Trunc:
2741 case Instruction::FPTrunc:
2742 case Instruction::BitCast: {
2743 Type *SrcTy = VL0->getOperand(0)->getType();
2744 for (
Value *V : VL) {
2745 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
2747 BS.cancelScheduling(VL, VL0);
2748 newTreeEntry(VL,
None , S, UserTreeIdx,
2749 ReuseShuffleIndicies);
2751 <<
"SLP: Gathering casts with different src types.\n");
2755 TreeEntry *
TE = newTreeEntry(VL, Bundle , S, UserTreeIdx,
2756 ReuseShuffleIndicies);
2759 TE->setOperandsInOrder();
2760 for (
unsigned i = 0,
e = VL0->getNumOperands(); i <
e; ++i) {
2764 Operands.
push_back(cast<Instruction>(V)->getOperand(i));
2766 buildTree_rec(Operands, Depth + 1, {
TE, i});
2770 case Instruction::ICmp:
2771 case Instruction::FCmp: {
2775 Type *ComparedTy = VL0->getOperand(0)->getType();
2776 for (
Value *V : VL) {
2777 CmpInst *Cmp = cast<CmpInst>(V);
2780 BS.cancelScheduling(VL, VL0);
2781 newTreeEntry(VL,
None , S, UserTreeIdx,
2782 ReuseShuffleIndicies);
2784 <<
"SLP: Gathering cmp with different predicate.\n");
2789 TreeEntry *
TE = newTreeEntry(VL, Bundle , S, UserTreeIdx,
2790 ReuseShuffleIndicies);
2797 assert(P0 == SwapP0 &&
"Commutative Predicate mismatch");
2798 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *
this);
2801 for (
Value *V : VL) {
2802 auto *Cmp = cast<CmpInst>(V);
2803 Value *LHS = Cmp->getOperand(0);
2804 Value *RHS = Cmp->getOperand(1);
2805 if (Cmp->getPredicate() != P0)
2811 TE->setOperand(0, Left);
2812 TE->setOperand(1, Right);
2813 buildTree_rec(Left, Depth + 1, {
TE, 0});
2814 buildTree_rec(Right, Depth + 1, {
TE, 1});
2818 case Instruction::FNeg:
2820 case Instruction::FAdd:
2821 case Instruction::Sub:
2822 case Instruction::FSub:
2823 case Instruction::Mul:
2824 case Instruction::FMul:
2825 case Instruction::UDiv:
2826 case Instruction::SDiv:
2827 case Instruction::FDiv:
2828 case Instruction::URem:
2829 case Instruction::SRem:
2830 case Instruction::FRem:
2831 case Instruction::Shl:
2832 case Instruction::LShr:
2833 case Instruction::AShr:
2834 case Instruction::And:
2835 case Instruction::Or:
2836 case Instruction::Xor: {
2837 TreeEntry *
TE = newTreeEntry(VL, Bundle , S, UserTreeIdx,
2838 ReuseShuffleIndicies);
2843 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
2845 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *
this);
2846 TE->setOperand(0, Left);
2847 TE->setOperand(1, Right);
2848 buildTree_rec(Left, Depth + 1, {
TE, 0});
2849 buildTree_rec(Right, Depth + 1, {
TE, 1});
2853 TE->setOperandsInOrder();
2854 for (
unsigned i = 0,
e = VL0->getNumOperands(); i <
e; ++i) {
2858 Operands.
push_back(cast<Instruction>(j)->getOperand(i));
2860 buildTree_rec(Operands, Depth + 1, {
TE, i});
2864 case Instruction::GetElementPtr: {
2866 for (
Value *V : VL) {
2867 if (cast<Instruction>(V)->getNumOperands() != 2) {
2868 LLVM_DEBUG(
dbgs() <<
"SLP: not-vectorizable GEP (nested indexes).\n");
2869 BS.cancelScheduling(VL, VL0);
2870 newTreeEntry(VL,
None , S, UserTreeIdx,
2871 ReuseShuffleIndicies);
2878 Type *Ty0 = VL0->getOperand(0)->getType();
2879 for (
Value *V : VL) {
2880 Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
2883 <<
"SLP: not-vectorizable GEP (different types).\n");
2884 BS.cancelScheduling(VL, VL0);
2885 newTreeEntry(VL,
None , S, UserTreeIdx,
2886 ReuseShuffleIndicies);
2892 Type *Ty1 = VL0->getOperand(1)->getType();
2893 for (
Value *V : VL) {
2894 auto Op = cast<Instruction>(V)->getOperand(1);
2895 if (!isa<ConstantInt>(
Op) ||
2896 (
Op->getType() != Ty1 &&
2897 Op->getType()->getScalarSizeInBits() >
2898 DL->getIndexSizeInBits(
2899 V->getType()->getPointerAddressSpace()))) {
2901 <<
"SLP: not-vectorizable GEP (non-constant indexes).\n");
2902 BS.cancelScheduling(VL, VL0);
2903 newTreeEntry(VL,
None , S, UserTreeIdx,
2904 ReuseShuffleIndicies);
2909 TreeEntry *
TE = newTreeEntry(VL, Bundle , S, UserTreeIdx,
2910 ReuseShuffleIndicies);
2912 TE->setOperandsInOrder();
2913 for (
unsigned i = 0,
e = 2; i <
e; ++i) {
2917 Operands.
push_back(cast<Instruction>(V)->getOperand(i));
2919 buildTree_rec(Operands, Depth + 1, {
TE, i});
2925 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
2930 auto POIter = PointerOps.begin();
2932 for (
Value *V : VL) {
2933 auto *
SI = cast<StoreInst>(V);
2934 if (!
SI->isSimple()) {
2935 BS.cancelScheduling(VL, VL0);
2936 newTreeEntry(VL,
None , S, UserTreeIdx,
2937 ReuseShuffleIndicies);
2941 *POIter =
SI->getPointerOperand();
2942 *OIter =
SI->getValueOperand();
2952 if (CurrentOrder.
empty()) {
2953 Ptr0 = PointerOps.front();
2954 PtrN = PointerOps.back();
2956 Ptr0 = PointerOps[CurrentOrder.
front()];
2957 PtrN = PointerOps[CurrentOrder.
back()];
2959 const SCEV *Scev0 = SE->getSCEV(Ptr0);
2960 const SCEV *ScevN = SE->getSCEV(PtrN);
2963 uint64_t
Size = DL->getTypeAllocSize(ScalarTy);
2965 if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) {
2966 if (CurrentOrder.
empty()) {
2968 ++NumOpsWantToKeepOriginalOrder;
2969 TreeEntry *
TE = newTreeEntry(VL, Bundle , S,
2970 UserTreeIdx, ReuseShuffleIndicies);
2971 TE->setOperandsInOrder();
2976 auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
2979 newTreeEntry(VL, Bundle , S, UserTreeIdx,
2980 ReuseShuffleIndicies,
I->getFirst());
2981 TE->setOperandsInOrder();
2983 LLVM_DEBUG(
dbgs() <<
"SLP: added a vector of jumbled stores.\n");
2989 BS.cancelScheduling(VL, VL0);
2990 newTreeEntry(VL,
None , S, UserTreeIdx,
2991 ReuseShuffleIndicies);
2997 CallInst *CI = cast<CallInst>(VL0);
3002 BS.cancelScheduling(VL, VL0);
3003 newTreeEntry(VL,
None , S, UserTreeIdx,
3004 ReuseShuffleIndicies);
3011 for (
unsigned j = 0; j != NumArgs; ++j)
3014 for (
Value *V : VL) {
3019 BS.cancelScheduling(VL, VL0);
3020 newTreeEntry(VL,
None , S, UserTreeIdx,
3021 ReuseShuffleIndicies);
3022 LLVM_DEBUG(
dbgs() <<
"SLP: mismatched calls:" << *CI <<
"!=" << *V
3028 for (
unsigned j = 0; j != NumArgs; ++j) {
3031 if (ScalarArgs[j] != A1J) {
3032 BS.cancelScheduling(VL, VL0);
3033 newTreeEntry(VL,
None , S, UserTreeIdx,
3034 ReuseShuffleIndicies);
3036 <<
" argument " << ScalarArgs[j] <<
"!=" << A1J
3047 BS.cancelScheduling(VL, VL0);
3048 newTreeEntry(VL,
None , S, UserTreeIdx,
3049 ReuseShuffleIndicies);
3051 << *CI <<
"!=" << *V <<
'\n');
3056 TreeEntry *
TE = newTreeEntry(VL, Bundle , S, UserTreeIdx,
3057 ReuseShuffleIndicies);
3058 TE->setOperandsInOrder();
3062 for (
Value *V : VL) {
3063 auto *CI2 = cast<CallInst>(V);
3064 Operands.
push_back(CI2->getArgOperand(i));
3066 buildTree_rec(Operands, Depth + 1, {
TE, i});
3070 case Instruction::ShuffleVector: {
3073 if (!S.isAltShuffle()) {
3074 BS.cancelScheduling(VL, VL0);
3075 newTreeEntry(VL,
None , S, UserTreeIdx,
3076 ReuseShuffleIndicies);
3077 LLVM_DEBUG(
dbgs() <<
"SLP: ShuffleVector are not vectorized.\n");
3080 TreeEntry *
TE = newTreeEntry(VL, Bundle , S, UserTreeIdx,
3081 ReuseShuffleIndicies);
3085 if (isa<BinaryOperator>(VL0)) {
3087 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *
this);
3088 TE->setOperand(0, Left);
3089 TE->setOperand(1, Right);
3090 buildTree_rec(Left, Depth + 1, {
TE, 0});
3091 buildTree_rec(Right, Depth + 1, {
TE, 1});
3095 TE->setOperandsInOrder();
3096 for (
unsigned i = 0,
e = VL0->getNumOperands(); i <
e; ++i) {
3100 Operands.
push_back(cast<Instruction>(V)->getOperand(i));
3102 buildTree_rec(Operands, Depth + 1, {
TE, i});
3107 BS.cancelScheduling(VL, VL0);
3108 newTreeEntry(VL,
None , S, UserTreeIdx,
3109 ReuseShuffleIndicies);
3119 while (isa<CompositeType>(EltTy)) {
3120 if (
auto *
ST = dyn_cast<StructType>(EltTy)) {
3122 for (
const auto *Ty :
ST->elements())
3123 if (Ty != *
ST->element_begin())
3125 N *=
ST->getNumElements();
3126 EltTy = *
ST->element_begin();
3128 auto *SeqT = cast<SequentialType>(EltTy);
3129 N *= SeqT->getNumElements();
3130 EltTy = SeqT->getElementType();
3146 E0->
getOpcode() == Instruction::ExtractValue);
3152 CurrentOrder.
clear();
3156 if (E0->
getOpcode() == Instruction::ExtractValue) {
3158 NElts = canMapToVector(Vec->getType(), DL);
3166 NElts = Vec->getType()->getVectorNumElements();
3169 if (NElts != VL.
size())
3173 bool ShouldKeepOrder =
true;
3174 unsigned E = VL.
size();
3180 CurrentOrder.
assign(E, E + 1);
3182 for (; I <
E; ++
I) {
3183 auto *Inst = cast<Instruction>(VL[
I]);
3184 if (Inst->getOperand(0) != Vec)
3189 const unsigned ExtIdx = *Idx;
3191 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
3193 ShouldKeepOrder =
false;
3194 CurrentOrder[ExtIdx] =
I;
3196 if (CurrentOrder[I] != E + 1)
3198 CurrentOrder[
I] =
I;
3202 CurrentOrder.
clear();
3206 return ShouldKeepOrder;
3209 bool BoUpSLP::areAllUsersVectorized(
Instruction *
I)
const {
3212 return ScalarToTreeEntry.count(U) > 0;
3216 int BoUpSLP::getEntryCost(TreeEntry *
E) {
3219 Type *ScalarTy = VL[0]->getType();
3221 ScalarTy =
SI->getValueOperand()->getType();
3222 else if (
CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
3223 ScalarTy = CI->getOperand(0)->getType();
3228 if (MinBWs.count(VL[0]))
3232 unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
3233 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
3234 int ReuseShuffleCost = 0;
3235 if (NeedToShuffleReuses) {
3239 if (E->State == TreeEntry::NeedToGather) {
3243 return ReuseShuffleCost +
3246 if (E->getOpcode() == Instruction::ExtractElement &&
3250 int Cost = TTI->getShuffleCost(ShuffleKind.
getValue(), VecTy);
3251 for (
auto *V : VL) {
3256 if (areAllUsersVectorized(cast<Instruction>(V)) &&
3257 !ScalarToTreeEntry.count(V)) {
3258 auto *IO = cast<ConstantInt>(
3259 cast<ExtractElementInst>(V)->getIndexOperand());
3260 Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
3261 IO->getZExtValue());
3264 return ReuseShuffleCost + Cost;
3267 return ReuseShuffleCost + getGatherCost(VL);
3271 unsigned ShuffleOrOp =
3272 E->isAltShuffle() ? (
unsigned)Instruction::ShuffleVector : E->getOpcode();
3273 switch (ShuffleOrOp) {
3274 case Instruction::PHI:
3277 case Instruction::ExtractValue:
3278 case Instruction::ExtractElement:
3279 if (NeedToShuffleReuses) {
3281 for (
unsigned I : E->ReuseShuffleIndices) {
3282 if (ShuffleOrOp == Instruction::ExtractElement) {
3283 auto *IO = cast<ConstantInt>(
3284 cast<ExtractElementInst>(VL[
I])->getIndexOperand());
3285 Idx = IO->getZExtValue();
3286 ReuseShuffleCost -= TTI->getVectorInstrCost(
3287 Instruction::ExtractElement, VecTy, Idx);
3289 ReuseShuffleCost -= TTI->getVectorInstrCost(
3290 Instruction::ExtractElement, VecTy, Idx);
3294 Idx = ReuseShuffleNumbers;
3295 for (
Value *V : VL) {
3296 if (ShuffleOrOp == Instruction::ExtractElement) {
3297 auto *IO = cast<ConstantInt>(
3298 cast<ExtractElementInst>(V)->getIndexOperand());
3299 Idx = IO->getZExtValue();
3304 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
3307 if (E->State == TreeEntry::Vectorize) {
3308 int DeadCost = ReuseShuffleCost;
3309 if (!E->ReorderIndices.empty()) {
3311 DeadCost += TTI->getShuffleCost(
3314 for (
unsigned i = 0,
e = VL.
size(); i <
e; ++i) {
3319 if (areAllUsersVectorized(E)) {
3323 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3325 [](
User *U) {
return isa<GetElementPtrInst>(U); })) {
3328 DeadCost -= TTI->getExtractWithExtendCost(
3331 DeadCost += TTI->getCastInstrCost(
3337 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
3342 return ReuseShuffleCost + getGatherCost(VL);
3344 case Instruction::ZExt:
3345 case Instruction::SExt:
3346 case Instruction::FPToUI:
3347 case Instruction::FPToSI:
3348 case Instruction::FPExt:
3349 case Instruction::PtrToInt:
3350 case Instruction::IntToPtr:
3351 case Instruction::SIToFP:
3352 case Instruction::UIToFP:
3353 case Instruction::Trunc:
3354 case Instruction::FPTrunc:
3355 case Instruction::BitCast: {
3356 Type *SrcTy = VL0->getOperand(0)->getType();
3358 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, VL0);
3359 if (NeedToShuffleReuses) {
3360 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
3364 int ScalarCost = VL.
size() * ScalarEltCost;
3369 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
3370 VecCost = ReuseShuffleCost +
3371 TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy, VL0);
3373 return VecCost - ScalarCost;
3375 case Instruction::FCmp:
3376 case Instruction::ICmp:
3379 int ScalarEltCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
3381 if (NeedToShuffleReuses) {
3382 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
3386 int VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), VecTy, MaskTy, VL0);
3387 return ReuseShuffleCost + VecCost - ScalarCost;
3389 case Instruction::FNeg:
3391 case Instruction::FAdd:
3392 case Instruction::Sub:
3393 case Instruction::FSub:
3394 case Instruction::Mul:
3395 case Instruction::FMul:
3396 case Instruction::UDiv:
3397 case Instruction::SDiv:
3398 case Instruction::FDiv:
3399 case Instruction::URem:
3400 case Instruction::SRem:
3401 case Instruction::FRem:
3402 case Instruction::Shl:
3403 case Instruction::LShr:
3404 case Instruction::AShr:
3405 case Instruction::And:
3406 case Instruction::Or:
3407 case Instruction::Xor: {
3425 for (
unsigned i = 0,
e = VL.
size(); i <
e; ++i) {
3427 unsigned OpIdx = isa<BinaryOperator>(
I) ? 1 : 0;
3435 !CInt->getValue().isPowerOf2())
3446 int ScalarEltCost = TTI->getArithmeticInstrCost(
3447 E->getOpcode(), ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP,
Operands, VL0);
3448 if (NeedToShuffleReuses) {
3449 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
3452 int VecCost = TTI->getArithmeticInstrCost(
3453 E->getOpcode(), VecTy, Op1VK, Op2VK, Op1VP, Op2VP,
Operands, VL0);
3454 return ReuseShuffleCost + VecCost - ScalarCost;
3456 case Instruction::GetElementPtr: {
3464 if (NeedToShuffleReuses) {
3465 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
3470 return ReuseShuffleCost + VecCost - ScalarCost;
3477 if (NeedToShuffleReuses) {
3478 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
3483 if (!E->ReorderIndices.empty()) {
3485 VecLdCost += TTI->getShuffleCost(
3488 return ReuseShuffleCost + VecLdCost - ScalarLdCost;
3492 bool IsReorder = !E->ReorderIndices.empty();
3494 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
3498 if (NeedToShuffleReuses)
3499 ReuseShuffleCost = -(ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
3502 VecTy, Alignment, 0, VL0);
3505 VecStCost += TTI->getShuffleCost(
3508 return ReuseShuffleCost + VecStCost - ScalarStCost;
3511 CallInst *CI = cast<CallInst>(VL0);
3520 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
3521 FMF = FPMO->getFastMathFlags();
3524 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
3525 if (NeedToShuffleReuses) {
3526 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.
size()) * ScalarEltCost;
3531 int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->
getType(),
Args, FMF,
3534 LLVM_DEBUG(
dbgs() <<
"SLP: Call cost " << VecCallCost - ScalarCallCost
3535 <<
" (" << VecCallCost <<
"-" << ScalarCallCost <<
")" 3536 <<
" for " << *CI <<
"\n");
3538 return ReuseShuffleCost + VecCallCost - ScalarCallCost;
3540 case Instruction::ShuffleVector: {
3541 assert(E->isAltShuffle() &&
3546 "Invalid Shuffle Vector Operand");
3548 if (NeedToShuffleReuses) {
3549 for (
unsigned Idx : E->ReuseShuffleIndices) {
3551 ReuseShuffleCost -= TTI->getInstructionCost(
3554 for (
Value *V : VL) {
3556 ReuseShuffleCost += TTI->getInstructionCost(
3560 for (
Value *V : VL) {
3562 assert(E->isOpcodeOrAlt(I) &&
"Unexpected main/alternate opcode");
3563 ScalarCost += TTI->getInstructionCost(
3570 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy);
3571 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy);
3573 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
3574 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
3577 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty);
3578 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty);
3581 return ReuseShuffleCost + VecCost - ScalarCost;
3588 bool BoUpSLP::isFullyVectorizableTinyTree()
const {
3590 << VectorizableTree.size() <<
" is fully vectorizable .\n");
3593 if (VectorizableTree.size() == 1 &&
3594 VectorizableTree[0]->State == TreeEntry::Vectorize)
3597 if (VectorizableTree.size() != 2)
3601 if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
3603 isSplat(VectorizableTree[1]->Scalars)))
3607 if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
3608 VectorizableTree[1]->State == TreeEntry::NeedToGather)
3614 bool BoUpSLP::isLoadCombineReductionCandidate(
unsigned RdxOpcode)
const {
3615 if (RdxOpcode != Instruction::Or)
3618 unsigned NumElts = VectorizableTree[0]->Scalars.size();
3619 Value *FirstReduced = VectorizableTree[0]->Scalars[0];
3624 Value *ZextLoad = FirstReduced;
3627 ZextLoad = cast<BinaryOperator>(ZextLoad)->getOperand(0);
3645 LLVM_DEBUG(
dbgs() <<
"SLP: Assume load combining for scalar reduction of " 3646 << *(cast<Instruction>(FirstReduced)) <<
"\n");
3651 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable()
const {
3659 if (isFullyVectorizableTinyTree())
3662 assert(VectorizableTree.empty()
3663 ? ExternalUses.empty()
3664 :
true &&
"We shouldn't have any external users");
3671 int BoUpSLP::getSpillCost()
const {
3676 unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
3682 for (
const auto &TEPtr : VectorizableTree) {
3693 LiveValues.
erase(PrevInst);
3694 for (
auto &J : PrevInst->
operands()) {
3695 if (isa<Instruction>(&*J) && getTreeEntry(&*J))
3696 LiveValues.
insert(cast<Instruction>(&*J));
3700 dbgs() <<
"SLP: #LV: " << LiveValues.
size();
3701 for (
auto *
X : LiveValues)
3702 dbgs() <<
" " <<
X->getName();
3703 dbgs() <<
", Looking at ";
3708 unsigned NumCalls = 0;
3712 while (InstIt != PrevInstIt) {
3719 if ((isa<CallInst>(&*PrevInstIt) &&
3720 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
3721 &*PrevInstIt != PrevInst)
3729 for (
auto *II : LiveValues)
3731 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
3740 int BoUpSLP::getTreeCost() {
3743 << VectorizableTree.size() <<
".\n");
3745 unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
3747 for (
unsigned I = 0, E = VectorizableTree.size(); I <
E; ++
I) {
3748 TreeEntry &
TE = *VectorizableTree[
I].get();
3762 if (TE.State == TreeEntry::NeedToGather &&
3763 std::any_of(std::next(VectorizableTree.begin(), I + 1),
3764 VectorizableTree.end(),
3765 [
TE](
const std::unique_ptr<TreeEntry> &EntryPtr) {
3766 return EntryPtr->State == TreeEntry::NeedToGather &&
3767 EntryPtr->isSame(TE.Scalars);
3771 int C = getEntryCost(&TE);
3773 <<
" for bundle that starts with " << *TE.Scalars[0]
3779 int ExtractCost = 0;
3780 for (ExternalUser &EU : ExternalUses) {
3782 if (!ExtractCostCalculated.
insert(EU.Scalar).second)
3788 if (EphValues.count(EU.User))
3795 auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
3796 if (MinBWs.count(ScalarRoot)) {
3799 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
3801 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
3805 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
3809 int SpillCost = getSpillCost();
3810 Cost += SpillCost + ExtractCost;
3815 OS <<
"SLP: Spill Cost = " << SpillCost <<
".\n" 3816 <<
"SLP: Extract Cost = " << ExtractCost <<
".\n" 3817 <<
"SLP: Total Cost = " << Cost <<
".\n";
3822 ViewGraph(
this,
"SLP" +
F->getName(),
false, Str);
3827 int BoUpSLP::getGatherCost(
Type *Ty,
3830 for (
unsigned i = 0,
e = cast<VectorType>(Ty)->getNumElements(); i <
e; ++i)
3831 if (!ShuffledIndices.
count(i))
3832 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
3833 if (!ShuffledIndices.
empty())
3840 Type *ScalarTy = VL[0]->getType();
3842 ScalarTy =
SI->getValueOperand()->getType();
3850 for (
unsigned I = VL.
size(); I > 0; --
I) {
3851 unsigned Idx = I - 1;
3852 if (!UniqueElements.
insert(VL[Idx]).second)
3853 ShuffledElements.insert(Idx);
3855 return getGatherCost(VecTy, ShuffledElements);
3871 Left = Ops.
getVL(0);
3872 Right = Ops.
getVL(1);
3875 void BoUpSLP::setInsertPointAfterBundle(TreeEntry *E) {
3878 auto *Front = E->getMainOp();
3879 auto *BB = Front->getParent();
3881 [=](
Value *V) ->
bool {
3882 auto *I = cast<Instruction>(V);
3883 return !E->isOpcodeOrAlt(I) || I->
getParent() == BB;
3893 if (BlocksSchedules.count(BB)) {
3895 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
3896 if (Bundle && Bundle->isPartOfBundle())
3897 for (; Bundle; Bundle = Bundle->NextInBundle)
3898 if (Bundle->OpValue == Bundle->Inst)
3899 LastInst = Bundle->Inst;
3923 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
3929 assert(LastInst &&
"Failed to find last instruction in bundle");
3933 Builder.SetInsertPoint(BB, ++LastInst->
getIterator());
3934 Builder.SetCurrentDebugLocation(Front->getDebugLoc());
3941 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
3942 if (
auto *Insrt = dyn_cast<InsertElementInst>(Vec)) {
3943 GatherSeq.insert(Insrt);
3944 CSEBlocks.insert(Insrt->getParent());
3947 if (TreeEntry *E = getTreeEntry(VL[i])) {
3950 for (
unsigned Lane = 0,
LE = E->Scalars.size(); Lane !=
LE; ++Lane) {
3952 if (E->Scalars[Lane] == VL[i]) {
3957 assert(FoundLane >= 0 &&
"Could not find the correct lane");
3958 if (!E->ReuseShuffleIndices.empty()) {
3960 std::distance(E->ReuseShuffleIndices.begin(),
3961 llvm::find(E->ReuseShuffleIndices, FoundLane));
3963 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
3973 if (S.getOpcode()) {
3974 if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3975 if (E->isSame(VL)) {
3976 Value *V = vectorizeTree(E);
3977 if (VL.
size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
3979 if (
auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
3980 V = SV->getOperand(0);
3985 for(
unsigned Idx : E->ReuseShuffleIndices)
3986 if (UsedIdxs.
insert(Idx).second)
3997 Type *ScalarTy = S.OpValue->getType();
3998 if (
StoreInst *
SI = dyn_cast<StoreInst>(S.OpValue))
3999 ScalarTy =
SI->getValueOperand()->getType();
4004 if (VL.
size() > 2) {
4006 for (
Value *V : VL) {
4009 if (Res.second || isa<Constant>(V))
4014 if (UniqueValues.
size() == VL.size() || UniqueValues.
size() <= 1 ||
4016 ReuseShuffleIndicies.
clear();
4022 Value *V = Gather(VL, VecTy);
4023 if (!ReuseShuffleIndicies.
empty()) {
4025 ReuseShuffleIndicies,
"shuffle");
4026 if (
auto *I = dyn_cast<Instruction>(V)) {
4027 GatherSeq.insert(I);
4037 const unsigned E = Indices.
size();
4039 for (
unsigned I = 0; I <
E; ++
I)
4040 Mask[Indices[I]] = I;
4043 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
4046 if (E->VectorizedValue) {
4047 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *E->Scalars[0] <<
".\n");
4048 return E->VectorizedValue;
4054 ScalarTy =
SI->getValueOperand()->getType();
4057 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4059 if (E->State == TreeEntry::NeedToGather) {
4060 setInsertPointAfterBundle(E);
4061 auto *V = Gather(E->Scalars, VecTy);
4062 if (NeedToShuffleReuses) {
4064 E->ReuseShuffleIndices,
"shuffle");
4065 if (
auto *I = dyn_cast<Instruction>(V)) {
4066 GatherSeq.insert(I);
4070 E->VectorizedValue = V;
4074 unsigned ShuffleOrOp =
4075 E->isAltShuffle() ? (
unsigned)Instruction::ShuffleVector : E->getOpcode();
4076 switch (ShuffleOrOp) {
4077 case Instruction::PHI: {
4078 auto *PH = cast<PHINode>(VL0);
4079 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
4080 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4081 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
4083 if (NeedToShuffleReuses) {
4085 E->ReuseShuffleIndices,
"shuffle");
4087 E->VectorizedValue = V;
4093 for (
unsigned i = 0,
e = PH->getNumIncomingValues(); i <
e; ++i) {
4097 if (!VisitedBBs.
insert(IBB).second) {
4103 Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4104 Value *Vec = vectorizeTree(E->getOperand(i));
4109 "Invalid number of incoming values");
4113 case Instruction::ExtractElement: {
4114 if (E->State == TreeEntry::Vectorize) {
4115 Value *V = E->getSingleOperand(0);
4116 if (!E->ReorderIndices.empty()) {
4119 Builder.SetInsertPoint(VL0);
4123 if (NeedToShuffleReuses) {
4125 if (E->ReorderIndices.empty())
4126 Builder.SetInsertPoint(VL0);
4128 E->ReuseShuffleIndices,
"shuffle");
4130 E->VectorizedValue = V;
4133 setInsertPointAfterBundle(E);
4134 auto *V = Gather(E->Scalars, VecTy);
4135 if (NeedToShuffleReuses) {
4137 E->ReuseShuffleIndices,
"shuffle");
4138 if (
auto *I = dyn_cast<Instruction>(V)) {
4139 GatherSeq.insert(I);
4143 E->VectorizedValue = V;
4146 case Instruction::ExtractValue: {
4147 if (E->State == TreeEntry::Vectorize) {
4148 LoadInst *LI = cast<LoadInst>(E->getSingleOperand(0));
4149 Builder.SetInsertPoint(LI);
4154 if (!E->ReorderIndices.empty()) {
4157 NewV = Builder.CreateShuffleVector(NewV,
UndefValue::get(VecTy), Mask,
4160 if (NeedToShuffleReuses) {
4162 NewV = Builder.CreateShuffleVector(
4165 E->VectorizedValue = NewV;
4168 setInsertPointAfterBundle(E);
4169 auto *V = Gather(E->Scalars, VecTy);
4170 if (NeedToShuffleReuses) {
4172 E->ReuseShuffleIndices,
"shuffle");
4173 if (
auto *I = dyn_cast<Instruction>(V)) {
4174 GatherSeq.insert(I);
4178 E->VectorizedValue = V;
4181 case Instruction::ZExt:
4182 case Instruction::SExt:
4183 case Instruction::FPToUI:
4184 case Instruction::FPToSI:
4185 case Instruction::FPExt:
4186 case Instruction::PtrToInt:
4187 case Instruction::IntToPtr:
4188 case Instruction::SIToFP:
4189 case Instruction::UIToFP:
4190 case Instruction::Trunc:
4191 case Instruction::FPTrunc:
4192 case Instruction::BitCast: {
4193 setInsertPointAfterBundle(E);
4195 Value *InVec = vectorizeTree(E->getOperand(0));
4197 if (E->VectorizedValue) {
4198 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
4199 return E->VectorizedValue;
4202 auto *CI = cast<CastInst>(VL0);
4203 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
4204 if (NeedToShuffleReuses) {
4206 E->ReuseShuffleIndices,
"shuffle");
4208 E->VectorizedValue = V;
4209 ++NumVectorInstructions;
4212 case Instruction::FCmp:
4213 case Instruction::ICmp: {
4214 setInsertPointAfterBundle(E);
4216 Value *L = vectorizeTree(E->getOperand(0));
4217 Value *R = vectorizeTree(E->getOperand(1));
4219 if (E->VectorizedValue) {
4220 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
4221 return E->VectorizedValue;
4226 if (E->getOpcode() == Instruction::FCmp)
4227 V = Builder.CreateFCmp(P0, L, R);
4229 V = Builder.CreateICmp(P0, L, R);
4232 if (NeedToShuffleReuses) {
4234 E->ReuseShuffleIndices,
"shuffle");
4236 E->VectorizedValue = V;
4237 ++NumVectorInstructions;
4241 setInsertPointAfterBundle(E);
4243 Value *Cond = vectorizeTree(E->getOperand(0));
4244 Value *True = vectorizeTree(E->getOperand(1));
4245 Value *False = vectorizeTree(E->getOperand(2));
4247 if (E->VectorizedValue) {
4248 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
4249 return E->VectorizedValue;
4252 Value *V = Builder.CreateSelect(Cond, True, False);
4253 if (NeedToShuffleReuses) {
4255 E->ReuseShuffleIndices,
"shuffle");
4257 E->VectorizedValue = V;
4258 ++NumVectorInstructions;
4261 case Instruction::FNeg: {
4262 setInsertPointAfterBundle(E);
4264 Value *
Op = vectorizeTree(E->getOperand(0));
4266 if (E->VectorizedValue) {
4267 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
4268 return E->VectorizedValue;
4271 Value *V = Builder.CreateUnOp(
4272 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
4274 if (
auto *I = dyn_cast<Instruction>(V))
4277 if (NeedToShuffleReuses) {
4279 E->ReuseShuffleIndices,
"shuffle");
4281 E->VectorizedValue = V;
4282 ++NumVectorInstructions;
4287 case Instruction::FAdd:
4288 case Instruction::Sub:
4289 case Instruction::FSub:
4290 case Instruction::Mul:
4291 case Instruction::FMul:
4292 case Instruction::UDiv:
4293 case Instruction::SDiv:
4294 case Instruction::FDiv:
4295 case Instruction::URem:
4296 case Instruction::SRem:
4297 case Instruction::FRem:
4298 case Instruction::Shl:
4299 case Instruction::LShr:
4300 case Instruction::AShr:
4301 case Instruction::And:
4302 case Instruction::Or:
4303 case Instruction::Xor: {
4304 setInsertPointAfterBundle(E);
4306 Value *LHS = vectorizeTree(E->getOperand(0));
4307 Value *RHS = vectorizeTree(E->getOperand(1));
4309 if (E->VectorizedValue) {
4310 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
4311 return E->VectorizedValue;
4314 Value *V = Builder.CreateBinOp(
4315 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
4318 if (
auto *I = dyn_cast<Instruction>(V))
4321 if (NeedToShuffleReuses) {
4323 E->ReuseShuffleIndices,
"shuffle");
4325 E->VectorizedValue = V;
4326 ++NumVectorInstructions;
4333 bool IsReorder = E->updateStateIfReorder();
4335 VL0 = E->getMainOp();
4336 setInsertPointAfterBundle(E);
4338 LoadInst *LI = cast<LoadInst>(VL0);
4349 if (getTreeEntry(PO))
4350 ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
4353 LI = Builder.CreateLoad(VecTy, VecPtr);
4356 LI->setAlignment(Alignment);
4362 Mask,
"reorder_shuffle");
4364 if (NeedToShuffleReuses) {
4367 E->ReuseShuffleIndices,
"shuffle");
4369 E->VectorizedValue = V;
4370 ++NumVectorInstructions;
4374 bool IsReorder = !E->ReorderIndices.empty();
4375 auto *
SI = cast<StoreInst>(
4376 IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0);
4377 unsigned Alignment =
SI->getAlignment();
4378 unsigned AS =
SI->getPointerAddressSpace();
4380 setInsertPointAfterBundle(E);
4382 Value *VecValue = vectorizeTree(E->getOperand(0));
4386 VecValue = Builder.CreateShuffleVector(
4390 Value *ScalarPtr =
SI->getPointerOperand();
4391 Value *VecPtr = Builder.CreateBitCast(
4393 StoreInst *
ST = Builder.CreateStore(VecValue, VecPtr);
4398 if (getTreeEntry(ScalarPtr))
4399 ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
4406 if (NeedToShuffleReuses) {
4408 E->ReuseShuffleIndices,
"shuffle");
4410 E->VectorizedValue = V;
4411 ++NumVectorInstructions;
4414 case Instruction::GetElementPtr: {
4415 setInsertPointAfterBundle(E);
4417 Value *Op0 = vectorizeTree(E->getOperand(0));
4419 std::vector<Value *> OpVecs;
4420 for (
int j = 1,
e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j <
e;
4422 ValueList &VL = E->getOperand(j);
4427 VL, [VL0Ty](
Value *V) {
return VL0Ty == V->
getType(); })
4430 ->getPointerOperandType()
4432 for (
Value *&V : VL) {
4433 auto *CI = cast<ConstantInt>(V);
4435 CI->getValue().isSignBitSet());
4437 Value *OpVec = vectorizeTree(VL);
4438 OpVecs.push_back(OpVec);
4441 Value *V = Builder.CreateGEP(
4442 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
4446 if (NeedToShuffleReuses) {
4448 E->ReuseShuffleIndices,
"shuffle");
4450 E->VectorizedValue = V;
4451 ++NumVectorInstructions;
4456 CallInst *CI = cast<CallInst>(VL0);
4457 setInsertPointAfterBundle(E);
4461 IID = FI->getIntrinsicID();
4463 Value *ScalarArg =
nullptr;
4464 std::vector<Value *> OpVecs;
4470 CallInst *CEI = cast<CallInst>(VL0);
4476 Value *OpVec = vectorizeTree(E->getOperand(j));
4477 LLVM_DEBUG(
dbgs() <<
"SLP: OpVec[" << j <<
"]: " << *OpVec <<
"\n");
4478 OpVecs.push_back(OpVec);
4487 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
4492 if (ScalarArg && getTreeEntry(ScalarArg))
4493 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
4496 if (NeedToShuffleReuses) {
4498 E->ReuseShuffleIndices,
"shuffle");
4500 E->VectorizedValue = V;
4501 ++NumVectorInstructions;
4504 case Instruction::ShuffleVector: {
4505 assert(E->isAltShuffle() &&
4510 "Invalid Shuffle Vector Operand");
4512 Value *LHS =
nullptr, *RHS =
nullptr;
4514 setInsertPointAfterBundle(E);
4515 LHS = vectorizeTree(E->getOperand(0));
4516 RHS = vectorizeTree(E->getOperand(1));
4518 setInsertPointAfterBundle(E);
4519 LHS = vectorizeTree(E->getOperand(0));
4522 if (E->VectorizedValue) {
4523 LLVM_DEBUG(
dbgs() <<
"SLP: Diamond merged for " << *VL0 <<
".\n");
4524 return E->VectorizedValue;
4529 V0 = Builder.CreateBinOp(
4530 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
4531 V1 = Builder.CreateBinOp(
4532 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
4534 V0 = Builder.CreateCast(
4535 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
4536 V1 = Builder.CreateCast(
4537 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
4543 ValueList OpScalars, AltScalars;
4544 unsigned e = E->Scalars.size();
4546 for (
unsigned i = 0; i <
e; ++i) {
4547 auto *OpInst = cast<Instruction>(E->Scalars[i]);
4548 assert(E->isOpcodeOrAlt(OpInst) &&
"Unexpected main/alternate opcode");
4549 if (OpInst->getOpcode() == E->getAltOpcode()) {
4550 Mask[i] = Builder.getInt32(e + i);
4553 Mask[i] = Builder.getInt32(i);
4562 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
4565 if (NeedToShuffleReuses) {
4567 E->ReuseShuffleIndices,
"shuffle");
4569 E->VectorizedValue = V;
4570 ++NumVectorInstructions;
4582 return vectorizeTree(ExternallyUsedValues);
4588 for (
auto &BSIter : BlocksSchedules) {
4589 scheduleBlock(BSIter.second.get());
4592 Builder.SetInsertPoint(&
F->getEntryBlock().front());
4593 auto *VectorRoot = vectorizeTree(VectorizableTree[0].
get());
4598 auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4599 if (MinBWs.count(ScalarRoot)) {
4600 if (
auto *I = dyn_cast<Instruction>(VectorRoot))
4602 auto BundleWidth = VectorizableTree[0]->Scalars.size();
4605 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
4606 VectorizableTree[0]->VectorizedValue = Trunc;
4614 auto extend = [&](
Value *ScalarRoot,
Value *Ex,
Type *ScalarType) {
4615 if (!MinBWs.count(ScalarRoot))
4617 if (MinBWs[ScalarRoot].
second)
4618 return Builder.CreateSExt(Ex, ScalarType);
4619 return Builder.CreateZExt(Ex, ScalarType);
4623 for (
const auto &ExternalUse : ExternalUses) {
4631 TreeEntry *E = getTreeEntry(Scalar);
4632 assert(E &&
"Invalid scalar");
4633 assert(E->State == TreeEntry::Vectorize &&
"Extracting from a gather list");
4635 Value *Vec = E->VectorizedValue;
4636 assert(Vec &&
"Can't find vectorizable value");
4638 Value *Lane = Builder.getInt32(ExternalUse.Lane);
4644 "Scalar with nullptr as an external user must be registered in " 4645 "ExternallyUsedValues map");
4646 if (
auto *VecI = dyn_cast<Instruction>(Vec)) {
4647 Builder.SetInsertPoint(VecI->getParent(),
4648 std::next(VecI->getIterator()));
4650 Builder.SetInsertPoint(&
F->getEntryBlock().front());
4652 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4653 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
4654 CSEBlocks.insert(cast<Instruction>(Scalar)->
getParent());
4655 auto &Locs = ExternallyUsedValues[
Scalar];
4656 ExternallyUsedValues.
insert({Ex, Locs});
4657 ExternallyUsedValues.
erase(Scalar);
4665 if (
auto *VecI = dyn_cast<Instruction>(Vec)) {
4666 if (
PHINode *PH = dyn_cast<PHINode>(User)) {
4667 for (
int i = 0,
e = PH->getNumIncomingValues(); i !=
e; ++i) {
4668 if (PH->getIncomingValue(i) ==
Scalar) {
4670 PH->getIncomingBlock(i)->getTerminator();
4671 if (isa<CatchSwitchInst>(IncomingTerminator)) {
4672 Builder.SetInsertPoint(VecI->getParent(),
4673 std::next(VecI->getIterator()));
4675 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
4677 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4678 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
4679 CSEBlocks.insert(PH->getIncomingBlock(i));
4680 PH->setOperand(i, Ex);
4684 Builder.SetInsertPoint(cast<Instruction>(User));
4685 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4686 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
4687 CSEBlocks.insert(cast<Instruction>(User)->
getParent());
4691 Builder.SetInsertPoint(&
F->getEntryBlock().front());
4692 Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4693 Ex = extend(ScalarRoot, Ex, Scalar->
getType());
4694 CSEBlocks.insert(&
F->getEntryBlock());
4702 for (
auto &TEPtr : VectorizableTree) {
4703 TreeEntry *
Entry = TEPtr.get();
4706 if (Entry->State == TreeEntry::NeedToGather)
4709 assert(Entry->VectorizedValue &&
"Can't find vectorizable value");
4712 for (
int Lane = 0,
LE = Entry->Scalars.size(); Lane !=
LE; ++Lane) {
4723 "Deleting out-of-tree value");
4727 LLVM_DEBUG(
dbgs() <<
"SLP: \tErasing scalar:" << *Scalar <<
".\n");
4732 Builder.ClearInsertionPoint();
4734 return VectorizableTree[0]->VectorizedValue;
4737 void BoUpSLP::optimizeGatherSequence() {
4739 <<
" gather sequences instructions.\n");
4771 CSEWorkList.
reserve(CSEBlocks.size());
4774 assert(DT->isReachableFromEntry(
N));
4782 return DT->properlyDominates(A, B);
4789 for (
auto I = CSEWorkList.
begin(), E = CSEWorkList.
end(); I !=
E; ++
I) {
4790 assert((I == CSEWorkList.
begin() || !DT->dominates(*I, *std::prev(I))) &&
4791 "Worklist not sorted properly!");
4798 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(
In))
4805 DT->dominates(v->getParent(), In->
getParent())) {
4814 Visited.push_back(In);
4826 const InstructionsState &S) {
4827 if (isa<PHINode>(S.OpValue))
4832 ScheduleData *PrevInBundle =
nullptr;
4833 ScheduleData *Bundle =
nullptr;
4834 bool ReSchedule =
false;
4839 for (
Value *V : VL) {
4840 if (!extendSchedulingRegion(V, S))
4844 for (
Value *V : VL) {
4845 ScheduleData *BundleMember = getScheduleData(V);
4847 "no ScheduleData for bundle member (maybe not in same basic block)");
4848 if (BundleMember->IsScheduled) {
4852 LLVM_DEBUG(
dbgs() <<
"SLP: reset schedule because " << *BundleMember
4853 <<
" was already scheduled\n");
4856 assert(BundleMember->isSchedulingEntity() &&
4857 "bundle member already part of other bundle");
4859 PrevInBundle->NextInBundle = BundleMember;
4861 Bundle = BundleMember;
4863 BundleMember->UnscheduledDepsInBundle = 0;
4864 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
4867 BundleMember->FirstInBundle = Bundle;
4868 PrevInBundle = BundleMember;
4870 if (ScheduleEnd != OldScheduleEnd) {
4876 for (
auto *I = ScheduleStart; I != ScheduleEnd; I = I->
getNextNode()) {
4877 doForAllOpcodes(I, [](ScheduleData *SD) {
4878 SD->clearDependencies();
4885 initialFillReadyList(ReadyInsts);
4887 assert(Bundle &&
"Failed to find schedule bundle");
4889 LLVM_DEBUG(
dbgs() <<
"SLP: try schedule bundle " << *Bundle <<
" in block " 4890 << BB->getName() <<
"\n");
4892 calculateDependencies(Bundle,
true, SLP);
4898 while (!Bundle->isReady() && !ReadyInsts.empty()) {
4900 ScheduleData *pickedSD = ReadyInsts.back();
4901 ReadyInsts.pop_back();
4903 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
4904 schedule(pickedSD, ReadyInsts);
4907 if (!Bundle->isReady()) {
4908 cancelScheduling(VL, S.OpValue);
4916 if (isa<PHINode>(OpValue))
4919 ScheduleData *Bundle = getScheduleData(OpValue);
4920 LLVM_DEBUG(
dbgs() <<
"SLP: cancel scheduling of " << *Bundle <<
"\n");
4921 assert(!Bundle->IsScheduled &&
4922 "Can't cancel bundle which is already scheduled");
4923 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
4924 "tried to unbundle something which is not a bundle");
4927 ScheduleData *BundleMember = Bundle;
4928 while (BundleMember) {
4929 assert(BundleMember->FirstInBundle == Bundle &&
"corrupt bundle links");
4930 BundleMember->FirstInBundle = BundleMember;
4931 ScheduleData *Next = BundleMember->NextInBundle;
4932 BundleMember->NextInBundle =
nullptr;
4933 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
4934 if (BundleMember->UnscheduledDepsInBundle == 0) {
4935 ReadyInsts.insert(BundleMember);
4937 BundleMember = Next;
4941 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
4943 if (ChunkPos >= ChunkSize) {
4944 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
4947 return &(ScheduleDataChunks.back()[ChunkPos++]);
4950 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(
Value *V,
4951 const InstructionsState &S) {
4952 if (getScheduleData(V,
isOneOf(S, V)))
4955 assert(I &&
"bundle member must be an instruction");
4956 assert(!isa<PHINode>(I) &&
"phi nodes don't need to be scheduled");
4957 auto &&CheckSheduleForI = [
this, &S](
Instruction *
I) ->
bool {
4958 ScheduleData *ISD = getScheduleData(I);
4961 assert(isInSchedulingRegion(ISD) &&
4962 "ScheduleData not in scheduling region");
4963 ScheduleData *SD = allocateScheduleDataChunks();
4965 SD->init(SchedulingRegionID, S.OpValue);
4966 ExtraScheduleDataMap[
I][S.OpValue] = SD;
4969 if (CheckSheduleForI(I))
4971 if (!ScheduleStart) {
4973 initScheduleData(I, I->
getNextNode(),
nullptr,
nullptr);
4977 CheckSheduleForI(I);
4978 assert(ScheduleEnd &&
"tried to vectorize a terminator?");
4979 LLVM_DEBUG(
dbgs() <<
"SLP: initialize schedule region to " << *I <<
"\n");
4990 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
4991 LLVM_DEBUG(
dbgs() <<
"SLP: exceeded schedule region size limit\n");
4995 if (UpIter != UpperEnd) {
4996 if (&*UpIter == I) {
4997 initScheduleData(I, ScheduleStart,
nullptr, FirstLoadStoreInRegion);
5000 CheckSheduleForI(I);
5001 LLVM_DEBUG(
dbgs() <<
"SLP: extend schedule region start to " << *I
5007 if (DownIter != LowerEnd) {
5008 if (&*DownIter == I) {
5009 initScheduleData(ScheduleEnd, I->
getNextNode(), LastLoadStoreInRegion,
5013 CheckSheduleForI(I);
5014 assert(ScheduleEnd &&
"tried to vectorize a terminator?");
5021 assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
5022 "instruction not found in block");
5027 void BoUpSLP::BlockScheduling::initScheduleData(
Instruction *FromI,
5029 ScheduleData *PrevLoadStore,
5030 ScheduleData *NextLoadStore) {
5031 ScheduleData *CurrentLoadStore = PrevLoadStore;
5033 ScheduleData *SD = ScheduleDataMap[
I];
5035 SD = allocateScheduleDataChunks();
5036 ScheduleDataMap[
I] = SD;
5039 assert(!isInSchedulingRegion(SD) &&
5040 "new ScheduleData already in scheduling region");
5041 SD->init(SchedulingRegionID, I);
5044 (!isa<IntrinsicInst>(
I) ||
5045 cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
5047 if (CurrentLoadStore) {
5048 CurrentLoadStore->NextLoadStore = SD;
5050 FirstLoadStoreInRegion = SD;
5052 CurrentLoadStore = SD;
5055 if (NextLoadStore) {
5056 if (CurrentLoadStore)
5057 CurrentLoadStore->NextLoadStore = NextLoadStore;
5059 LastLoadStoreInRegion = CurrentLoadStore;
5063 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
5064 bool InsertInReadyList,
5066 assert(SD->isSchedulingEntity());
5071 while (!WorkList.empty()) {
5072 ScheduleData *SD = WorkList.back();
5073 WorkList.pop_back();
5075 ScheduleData *BundleMember = SD;
5076 while (BundleMember) {
5077 assert(isInSchedulingRegion(BundleMember));
5078 if (!BundleMember->hasValidDependencies()) {
5082 BundleMember->Dependencies = 0;
5083 BundleMember->resetUnscheduledDeps();
5086 if (BundleMember->OpValue != BundleMember->Inst) {
5087 ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
5088 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5089 BundleMember->Dependencies++;
5090 ScheduleData *DestBundle = UseSD->FirstInBundle;
5091 if (!DestBundle->IsScheduled)
5092 BundleMember->incrementUnscheduledDeps(1);
5093 if (!DestBundle->hasValidDependencies())
5094 WorkList.push_back(DestBundle);
5097 for (
User *U : BundleMember->Inst->users()) {
5098 if (isa<Instruction>(U)) {
5099 ScheduleData *UseSD = getScheduleData(U);
5100 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5101 BundleMember->Dependencies++;
5102 ScheduleData *DestBundle = UseSD->FirstInBundle;
5103 if (!DestBundle->IsScheduled)
5104 BundleMember->incrementUnscheduledDeps(1);
5105 if (!DestBundle->hasValidDependencies())
5106 WorkList.push_back(DestBundle);
5112 BundleMember->Dependencies++;
5113 BundleMember->incrementUnscheduledDeps(1);
5119 ScheduleData *DepDest = BundleMember->NextLoadStore;
5123 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
5124 unsigned numAliased = 0;
5125 unsigned DistToSrc = 1;
5128 assert(isInSchedulingRegion(DepDest));
5137 if (DistToSrc >= MaxMemDepDistance ||
5138 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
5139 (numAliased >= AliasedCheckLimit ||
5140 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
5147 DepDest->MemoryDependencies.push_back(BundleMember);
5148 BundleMember->Dependencies++;
5149 ScheduleData *DestBundle = DepDest->FirstInBundle;
5150 if (!DestBundle->IsScheduled) {
5151 BundleMember->incrementUnscheduledDeps(1);
5153 if (!DestBundle->hasValidDependencies()) {
5154 WorkList.push_back(DestBundle);
5157 DepDest = DepDest->NextLoadStore;
5172 if (DistToSrc >= 2 * MaxMemDepDistance)
5178 BundleMember = BundleMember->NextInBundle;
5180 if (InsertInReadyList && SD->isReady()) {
5181 ReadyInsts.push_back(SD);
5188 void BoUpSLP::BlockScheduling::resetSchedule() {
5190 "tried to reset schedule on block which has not been scheduled");
5192 doForAllOpcodes(I, [&](ScheduleData *SD) {
5193 assert(isInSchedulingRegion(SD) &&
5194 "ScheduleData not in scheduling region");
5195 SD->IsScheduled =
false;
5196 SD->resetUnscheduledDeps();
5202 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
5203 if (!BS->ScheduleStart)
5206 LLVM_DEBUG(
dbgs() <<
"SLP: schedule block " << BS->BB->getName() <<
"\n");
5208 BS->resetSchedule();
5213 struct ScheduleDataCompare {
5214 bool operator()(ScheduleData *SD1, ScheduleData *SD2)
const {
5215 return SD2->SchedulingPriority < SD1->SchedulingPriority;
5218 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
5223 int NumToSchedule = 0;
5224 for (
auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
5226 BS->doForAllOpcodes(I, [
this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
5227 assert(SD->isPartOfBundle() ==
5228 (getTreeEntry(SD->Inst) !=
nullptr) &&
5229 "scheduler and vectorizer bundle mismatch");
5230 SD->FirstInBundle->SchedulingPriority = Idx++;
5231 if (SD->isSchedulingEntity()) {
5232 BS->calculateDependencies(SD,
false,
this);
5237 BS->initialFillReadyList(ReadyInsts);
5242 while (!ReadyInsts.empty()) {
5243 ScheduleData *picked = *ReadyInsts.begin();
5244 ReadyInsts.erase(ReadyInsts.begin());
5248 ScheduleData *BundleMember = picked;
5249 while (BundleMember) {
5251 if (LastScheduledInst->
getNextNode() != pickedInst) {
5252 BS->BB->getInstList().remove(pickedInst);
5253 BS->BB->getInstList().insert(LastScheduledInst->
getIterator(),
5256 LastScheduledInst = pickedInst;
5257 BundleMember = BundleMember->NextInBundle;
5260 BS->schedule(picked, ReadyInsts);
5263 assert(NumToSchedule == 0 &&
"could not schedule all instructions");
5266 BS->ScheduleStart =
nullptr;
5269 unsigned BoUpSLP::getVectorElementSize(
Value *V)
const {
5272 if (
auto *
Store = dyn_cast<StoreInst>(V))
5281 if (
auto *I = dyn_cast<Instruction>(V))
5287 auto FoundUnknownInst =
false;
5288 while (!Worklist.
empty() && !FoundUnknownInst) {
5295 if (isa<VectorType>(Ty))
5296 FoundUnknownInst =
true;
5300 else if (isa<LoadInst>(I))
5306 else if (isa<PHINode>(I) || isa<CastInst>(
I) || isa<GetElementPtrInst>(I) ||
5307 isa<CmpInst>(
I) || isa<SelectInst>(I) || isa<BinaryOperator>(
I)) {
5309 if (
auto *J = dyn_cast<Instruction>(U.get()))
5310 if (!Visited.
count(J))
5316 FoundUnknownInst =
true;
5321 if (!MaxWidth || FoundUnknownInst)
5335 if (isa<Constant>(V)) {
5350 case Instruction::Trunc:
5353 case Instruction::ZExt:
5354 case Instruction::SExt:
5360 case Instruction::Sub:
5361 case Instruction::Mul:
5362 case Instruction::And:
5363 case Instruction::Or:
5364 case Instruction::Xor:
5381 case Instruction::PHI: {
5402 if (ExternalUses.empty())
5406 auto &TreeRoot = VectorizableTree[0]->Scalars;
5418 for (
auto &EU : ExternalUses)
5419 if (!Expr.erase(EU.Scalar))
5427 for (
auto &EntryPtr : VectorizableTree)
5428 Expr.
insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
5432 for (
auto *Root : TreeRoot)
5433 if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
5441 for (
auto *Root : TreeRoot)
5448 auto MaxBitWidth = 8u;
5452 for (
auto *Root : TreeRoot) {
5453 auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
5454 MaxBitWidth = std::max<unsigned>(
5455 Mask.getBitWidth() -
Mask.countLeadingZeros(), MaxBitWidth);
5461 bool IsKnownPositive =
true;
5475 return isa<GetElementPtrInst>(R->
user_back());
5488 for (
auto *
Scalar : ToDemote) {
5491 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
5509 if (!IsKnownPositive)
5519 if (MaxBitWidth >= TreeRootIT->getBitWidth())
5525 while (!Roots.
empty())
5529 for (
auto *
Scalar : ToDemote)
5530 MinBWs[
Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
5546 bool doInitialization(
Module &M)
override {
5551 if (skipFunction(F))
5554 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5555 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5556 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5557 auto *TLI = TLIP ? &TLIP->getTLI(F) :
nullptr;
5558 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5559 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5560 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5561 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5562 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
5563 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5565 return Impl.
runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5599 bool Changed =
runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5628 bool Changed =
false;
5632 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(
true)))
5643 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
5650 collectSeedInstructions(BB);
5653 if (!Stores.empty()) {
5655 <<
" underlying objects.\n");
5656 Changed |= vectorizeStoreChains(R);
5660 Changed |= vectorizeChainsInBlock(BB, R);
5665 if (!GEPs.empty()) {
5667 <<
" underlying objects.\n");
5668 Changed |= vectorizeGEPIndices(BB, R);
5673 R.optimizeGatherSequence();
5680 bool SLPVectorizerPass::vectorizeStoreChain(
ArrayRef<Value *> Chain, BoUpSLP &R,
5684 const unsigned Sz = R.getVectorElementSize(Chain[0]);
5685 const unsigned MinVF = R.getMinVecRegSize() / Sz;
5686 unsigned VF = Chain.
size();
5691 LLVM_DEBUG(
dbgs() <<
"SLP: Analyzing " << VF <<
" stores at offset " << Idx
5697 if (Order && Order->size() == Chain.
size()) {
5701 [Chain](
const unsigned Idx) {
return Chain[Idx]; });
5702 R.buildTree(ReorderedOps);
5704 if (R.isTreeTinyAndNotFullyVectorizable())
5707 R.computeMinimumValueSizes();
5709 int Cost = R.getTreeCost();
5711 LLVM_DEBUG(
dbgs() <<
"SLP: Found cost=" << Cost <<
" for VF=" << VF <<
"\n");
5713 LLVM_DEBUG(
dbgs() <<
"SLP: Decided to vectorize cost=" << Cost <<
"\n");
5715 using namespace ore;
5718 cast<StoreInst>(Chain[0]))
5719 <<
"Stores SLP vectorized with cost " <<
NV(
"Cost", Cost)
5720 <<
" and with tree size " 5721 <<
NV(
"TreeSize", R.getTreeSize()));
5734 BoUpSLP::ValueSet VectorizedStores;
5735 bool Changed =
false;
5737 int E = Stores.
size();
5742 auto &&FindConsecutiveAccess = [
this, &Stores, &Tails, &IterCnt, MaxIter,
5743 &ConsecutiveChain](
int K,
int Idx) {
5744 if (IterCnt >= MaxIter)
5751 ConsecutiveChain[K] = Idx;
5756 for (
int Idx = E - 1; Idx >= 0; --Idx) {
5761 const int MaxLookDepth =
std::max(E - Idx, Idx + 1);
5764 if ((Idx >=
Offset && FindConsecutiveAccess(Idx -
Offset, Idx)) ||
5765 (Idx +
Offset < E && FindConsecutiveAccess(Idx +
Offset, Idx)))
5770 for (
int Cnt = E; Cnt > 0; --Cnt) {
5772 if (ConsecutiveChain[I] == E + 1 || Tails.test(I))
5778 while (I != E + 1 && !VectorizedStores.count(Stores[I])) {
5779 Operands.push_back(Stores[I]);
5781 I = ConsecutiveChain[
I];
5785 unsigned MaxVecRegSize = R.getMaxVecRegSize();
5786 unsigned EltSize = R.getVectorElementSize(Stores[0]);
5787 if (MaxVecRegSize % EltSize != 0)
5790 unsigned MaxElts = MaxVecRegSize / EltSize;
5793 unsigned StartIdx = 0;
5795 for (
unsigned Cnt = StartIdx, E = Operands.size(); Cnt +
Size <=
E;) {
5797 if (!VectorizedStores.count(Slice.
front()) &&
5798 !VectorizedStores.count(Slice.
back()) &&
5799 vectorizeStoreChain(Slice, R, Cnt)) {
5801 VectorizedStores.insert(Slice.
begin(), Slice.
end());
5805 if (Cnt == StartIdx)
5813 if (StartIdx >= Operands.size())
5821 void SLPVectorizerPass::collectSeedInstructions(
BasicBlock *BB) {
5832 if (
auto *
SI = dyn_cast<StoreInst>(&I)) {
5833 if (!
SI->isSimple())
5843 else if (
auto *
GEP = dyn_cast<GetElementPtrInst>(&I)) {
5844 auto Idx =
GEP->idx_begin()->get();
5845 if (
GEP->getNumIndices() > 1 || isa<Constant>(Idx))
5849 if (
GEP->getType()->isVectorTy())
5851 GEPs[
GEP->getPointerOperand()].push_back(
GEP);
5856 bool SLPVectorizerPass::tryToVectorizePair(
Value *A,
Value *
B, BoUpSLP &R) {
5859 Value *VL[] = { A, B };
5860 return tryToVectorizeList(VL, R, 0,
true);
5864 int UserCost,
bool AllowReorder) {
5868 LLVM_DEBUG(
dbgs() <<
"SLP: Trying to vectorize a list of length = " 5869 << VL.
size() <<
".\n");
5878 unsigned Sz = R.getVectorElementSize(I0);
5879 unsigned MinVF =
std::max(2U, R.getMinVecRegSize() / Sz);
5882 R.getORE()->emit([&]() {
5884 <<
"Cannot SLP vectorize list: vectorization factor " 5885 <<
"less than 2 is not supported";
5890 for (
Value *V : VL) {
5895 R.getORE()->emit([&]() {
5896 std::string type_str;
5900 <<
"Cannot SLP vectorize list: type " 5901 << rso.
str() +
" is unsupported by vectorizer";
5907 bool Changed =
false;
5908 bool CandidateFound =
false;
5911 unsigned NextInst = 0, MaxInst = VL.size();
5912 for (
unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
5917 if (TTI->getNumberOfParts(VecTy) == VF)
5919 for (
unsigned I = NextInst; I < MaxInst; ++
I) {
5920 unsigned OpsWidth = 0;
5922 if (I + VF > MaxInst)
5923 OpsWidth = MaxInst -
I;
5934 return I && R.isDeleted(I);
5938 LLVM_DEBUG(
dbgs() <<
"SLP: Analyzing " << OpsWidth <<
" operations " 5944 if (AllowReorder && Order) {
5951 Value *ReorderedOps[] = {Ops[1], Ops[0]};
5952 R.buildTree(ReorderedOps,
None);
5954 if (R.isTreeTinyAndNotFullyVectorizable())
5957 R.computeMinimumValueSizes();
5958 int Cost = R.getTreeCost() - UserCost;
5959 CandidateFound =
true;
5960 MinCost = std::min(MinCost, Cost);
5963 LLVM_DEBUG(
dbgs() <<
"SLP: Vectorizing list at cost:" << Cost <<
".\n");
5965 cast<Instruction>(Ops[0]))
5966 <<
"SLP vectorized with cost " <<
ore::NV(
"Cost", Cost)
5967 <<
" and with tree size " 5968 <<
ore::NV(
"TreeSize", R.getTreeSize()));
5979 if (!Changed && CandidateFound) {
5980 R.getORE()->emit([&]() {
5982 <<
"List vectorization was possible but not beneficial with cost " 5983 <<
ore::NV(
"Cost", MinCost) <<
" >= " 5986 }
else if (!Changed) {
5987 R.getORE()->emit([&]() {
5989 <<
"Cannot SLP vectorize list: vectorization was impossible" 5990 <<
" with available vectorization factors";
5996 bool SLPVectorizerPass::tryToVectorize(
Instruction *I, BoUpSLP &R) {
6000 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
6008 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() !=
P)
6012 if (tryToVectorizePair(Op0, Op1, R))
6018 if (B && B->hasOneUse()) {
6021 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
6023 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
6031 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
6033 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
6050 bool IsPairwise,
bool IsLeft,
6052 assert((IsPairwise || !IsLeft) &&
"Don't support a <0,1,undef,...> mask");
6059 for (
unsigned i = 0; i != NumEltsToRdx; ++i)
6060 ShuffleMask[i] = Builder.
getInt32(2 * i + !IsLeft);
6063 for (
unsigned i = 0; i != NumEltsToRdx; ++i)
6064 ShuffleMask[i] = Builder.
getInt32(NumEltsToRdx + i);
6098 class HorizontalReduction {
6101 ReductionOpsListType ReductionOps;
6117 class OperationData {
6119 unsigned Opcode = 0;
6122 Value *LHS =
nullptr;
6125 Value *RHS =
nullptr;
6134 bool isVectorizable()
const {
6135 return LHS && RHS &&
6137 ((Kind == RK_Arithmetic &&
6139 Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
6140 Opcode == Instruction::And || Opcode == Instruction::Or ||
6141 Opcode == Instruction::Xor)) ||
6142 ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
6143 (Kind == RK_Min || Kind == RK_Max)) ||
6144 (Opcode == Instruction::ICmp &&
6145 (Kind == RK_UMin || Kind == RK_UMax)));
6150 assert(isVectorizable() &&
6151 "Expected add|fadd or min/max reduction operation.");
6152 Value *Cmp =
nullptr;
6158 Cmp = Opcode == Instruction::ICmp ? Builder.
CreateICmpSLT(LHS, RHS)
6162 Cmp = Opcode == Instruction::ICmp ? Builder.
CreateICmpSGT(LHS, RHS)
6166 assert(Opcode == Instruction::ICmp &&
"Expected integer types.");
6170 assert(Opcode == Instruction::ICmp &&
"Expected integer types.");
6180 explicit OperationData() =
default;
6184 explicit OperationData(
Value *V) {
6185 if (
auto *I = dyn_cast<Instruction>(V))
6193 : Opcode(Opcode), LHS(LHS), RHS(RHS),
Kind(Kind), NoNaN(NoNaN) {
6194 assert(Kind != RK_None &&
"One of the reduction operations is expected.");
6197 explicit operator bool()
const {
return Opcode; }
6200 bool isMinMax()
const {
6216 unsigned getFirstOperandIndex()
const {
6217 assert(!!*
this &&
"The opcode is not set.");
6219 if (Kind == RK_None)
6221 return isMinMax() ? 1 : 0;
6225 unsigned getNumberOfOperands()
const {
6226 assert(Kind != RK_None && !!*
this && LHS && RHS &&
6227 "Expected reduction operation.");
6228 return isMinMax() ? 3 : 2;
6233 assert(Kind != RK_None && !!*
this && LHS && RHS &&
6234 "Expected reduction operation.");
6240 auto *Cmp = cast<Instruction>(cast<SelectInst>(
I)->getCondition());
6241 return I->
getParent() == P && Cmp && Cmp->getParent() ==
P;
6248 bool hasRequiredNumberOfUses(
Instruction *I,
bool IsReductionOp)
const {
6249 assert(Kind != RK_None && !!*
this && LHS && RHS &&
6250 "Expected reduction operation.");
6254 cast<SelectInst>(
I)->getCondition()->hasOneUse());
6259 void initReductionOps(ReductionOpsListType &ReductionOps) {
6260 assert(Kind != RK_None && !!*
this && LHS && RHS &&
6261 "Expected reduction operation.");
6263 ReductionOps.assign(2, ReductionOpsType());
6265 ReductionOps.assign(1, ReductionOpsType());
6269 void addReductionOps(
Instruction *I, ReductionOpsListType &ReductionOps) {
6270 assert(Kind != RK_None && !!*
this && LHS && RHS &&
6271 "Expected reduction operation.");
6273 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
6274 ReductionOps[1].emplace_back(I);
6276 ReductionOps[0].emplace_back(I);
6282 assert(Kind != RK_None && *
this && LHS && RHS &&
6283 "Expected reduction operation.");
6289 return Opcode == Instruction::ICmp ||
6290 cast<Instruction>(I->
getOperand(0))->isFast();
6293 assert(Opcode == Instruction::ICmp &&
6294 "Only integer compare operation is expected.");
6309 bool operator==(
const OperationData &OD)
const {
6310 assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
6311 "One of the comparing operations is incorrect.");
6312 return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
6314 bool operator!=(
const OperationData &OD)
const {
return !(*
this == OD); }
6325 assert(isVectorizable() &&
"Expected vectorizable operation.");
6331 Value *getLHS()
const {
return LHS; }
6332 Value *getRHS()
const {
return RHS; }
6333 Type *getConditionType()
const {
6340 const ReductionOpsListType &ReductionOps)
const {
6341 assert(isVectorizable() &&
6342 "Expected add|fadd or min/max reduction operation.");
6343 auto *
Op = createOp(Builder, Name);
6352 if (
auto *
SI = dyn_cast<SelectInst>(
Op))
6365 assert(isVectorizable() &&
6366 "Expected add|fadd or min/max reduction operation.");
6367 auto *
Op = createOp(Builder, Name);
6376 if (
auto *
SI = dyn_cast<SelectInst>(
Op)) {
6378 cast<SelectInst>(
I)->getCondition());
6390 Flags.
NoNaN = NoNaN;
6395 Flags.
IsSigned = Opcode == Instruction::ICmp;
6399 Flags.
IsSigned = Opcode == Instruction::ICmp;
6420 OperationData ReductionData;
6423 OperationData ReducedValueData;
6427 bool IsPairwiseReduction =
false;
6431 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
6433 if (ExtraArgs.
count(ParentStackElem.first)) {
6434 ExtraArgs[ParentStackElem.first] =
nullptr;
6441 ParentStackElem.second = ParentStackElem.first->getNumOperands();
6445 ExtraArgs[ParentStackElem.first] = ExtraArg;
6449 static OperationData getOperationData(
Value *V) {
6451 return OperationData();
6456 return OperationData(cast<BinaryOperator>(V)->
getOpcode(), LHS, RHS,
6459 if (
auto *
Select = dyn_cast<SelectInst>(V)) {
6462 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6464 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6467 return OperationData(
6468 Instruction::FCmp, LHS, RHS, RK_Min,
6469 cast<Instruction>(
Select->getCondition())->hasNoNaNs());
6471 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6473 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6476 return OperationData(
6477 Instruction::FCmp, LHS, RHS, RK_Max,
6478 cast<Instruction>(
Select->getCondition())->hasNoNaNs());
6495 LHS =
Select->getTrueValue();
6496 RHS =
Select->getFalseValue();
6501 if (!isa<ExtractElementInst>(RHS) ||
6503 return OperationData(V);
6505 if (!isa<ExtractElementInst>(LHS) ||
6507 return OperationData(V);
6509 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
6510 return OperationData(V);
6514 return OperationData(V);
6518 return OperationData(V);
6522 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6526 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6532 return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
6533 cast<Instruction>(Cond)->hasNoNaNs());
6537 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6541 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6547 return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
6548 cast<Instruction>(Cond)->hasNoNaNs());
6552 return OperationData(V);
6556 HorizontalReduction() =
default;
6561 "Thi phi needs to use the binary operator");
6563 ReductionData = getOperationData(B);
6569 if (ReductionData.getLHS() == Phi) {
6572 ReductionData = getOperationData(B);
6573 }
else if (ReductionData.getRHS() == Phi) {
6576 ReductionData = getOperationData(B);
6580 if (!ReductionData.isVectorizable(B))
6589 ReducedValueData.clear();
6595 Stack.
push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
6596 ReductionData.initReductionOps(ReductionOps);
6597 while (!Stack.
empty()) {
6599 unsigned EdgeToVist = Stack.
back().second++;
6600 OperationData OpData = getOperationData(TreeN);
6601 bool IsReducedValue = OpData != ReductionData;
6604 if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
6608 auto I = ExtraArgs.
find(TreeN);
6609 if (I != ExtraArgs.
end() && !I->second) {
6611 if (Stack.
size() <= 1) {
6619 markExtraArg(Stack[Stack.
size() - 2], TreeN);
6620 ExtraArgs.
erase(TreeN);
6622 ReductionData.addReductionOps(TreeN, ReductionOps);
6633 OpData = getOperationData(I);
6638 if (I && (!ReducedValueData || OpData == ReducedValueData ||
6639 OpData == ReductionData)) {
6640 const bool IsReductionOperation = OpData == ReductionData;
6642 if (!ReductionData.hasSameParent(I, B->
getParent(),
6643 IsReductionOperation)) {
6645 markExtraArg(Stack.
back(),
I);
6651 if (!ReductionData.hasRequiredNumberOfUses(I,
6652 OpData == ReductionData) &&
6655 markExtraArg(Stack.
back(),
I);
6659 if (IsReductionOperation) {
6661 if (!OpData.isAssociative(I)) {
6663 markExtraArg(Stack.
back(),
I);
6666 }
else if (ReducedValueData &&
6667 ReducedValueData != OpData) {
6671 markExtraArg(Stack.
back(),
I);
6673 }
else if (!ReducedValueData)
6674 ReducedValueData = OpData;
6676 Stack.
push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
6681 markExtraArg(Stack.
back(), NextV);
6689 if (ReducedVals.
empty())
6695 unsigned NumReducedVals = ReducedVals.
size();
6696 if (NumReducedVals < 4)
6701 Value *VectorizedTree =
nullptr;
6705 IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
6711 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
6714 for (
auto &Pair : ExtraArgs) {
6715 assert(Pair.first &&
"DebugLoc must be set.");
6716 ExternallyUsedValues[Pair.second].push_back(Pair.first);
6721 auto getCmpForMinMaxReduction = [](
Instruction *RdxRootInst) {
6722 assert(isa<SelectInst>(RdxRootInst) &&
6723 "Expected min/max reduction to have select root instruction");
6724 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
6725 assert(isa<Instruction>(ScalarCond) &&
6726 "Expected min/max reduction to have compare condition");
6727 return cast<Instruction>(ScalarCond);
6732 ExternallyUsedValues[ReductionRoot];
6734 for (
auto &V : ReductionOps)
6735 IgnoreList.
append(V.begin(), V.end());
6736 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
6738 V.buildTree(VL, ExternallyUsedValues, IgnoreList);
6741 if (Order && Order->size() == VL.
size()) {
6745 [VL](
const unsigned Idx) {
return VL[Idx]; });
6746 V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
6748 if (V.isTreeTinyAndNotFullyVectorizable())
6750 if (V.isLoadCombineReductionCandidate(ReductionData.getOpcode()))
6753 V.computeMinimumValueSizes();
6756 int TreeCost = V.getTreeCost();
6757 int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
6758 int Cost = TreeCost + ReductionCost;
6760 V.getORE()->emit([&]() {
6762 SV_NAME,
"HorSLPNotBeneficial", cast<Instruction>(VL[0]))
6763 <<
"Vectorizing horizontal reduction is possible" 6764 <<
"but not beneficial with cost " 6765 <<
ore::NV(
"Cost", Cost) <<
" and threshold " 6771 LLVM_DEBUG(
dbgs() <<
"SLP: Vectorizing horizontal reduction at cost:" 6772 << Cost <<
". (HorRdx)\n");
6773 V.getORE()->emit([&]() {
6775 SV_NAME,
"VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
6776 <<
"Vectorized horizontal reduction with cost " 6777 <<
ore::NV(
"Cost", Cost) <<
" and with tree size " 6778 <<
ore::NV(
"TreeSize", V.getTreeSize());
6783 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
6787 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
6788 if (ReductionData.isMinMax())
6793 Value *ReducedSubTree =
6794 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
6795 if (VectorizedTree) {
6797 OperationData VectReductionData(ReductionData.getOpcode(),
6798 VectorizedTree, ReducedSubTree,
6799 ReductionData.getKind());
6801 VectReductionData.createOp(Builder,
"op.rdx", ReductionOps);
6803 VectorizedTree = ReducedSubTree;
6808 if (VectorizedTree) {
6810 for (; i < NumReducedVals; ++i) {
6811 auto *I = cast<Instruction>(ReducedVals[i]);
6813 OperationData VectReductionData(ReductionData.getOpcode(),
6815 ReductionData.getKind());
6816 VectorizedTree = VectReductionData.createOp(Builder,
"", ReductionOps);
6818 for (
auto &Pair : ExternallyUsedValues) {
6820 for (
auto *I : Pair.second) {
6822 OperationData VectReductionData(ReductionData.getOpcode(),
6823 VectorizedTree, Pair.first,
6824 ReductionData.getKind());
6825 VectorizedTree = VectReductionData.createOp(Builder,
"op.extra", I);
6833 if (ReductionData.isMinMax()) {
6834 if (
auto *VecSelect = dyn_cast<SelectInst>(VectorizedTree)) {
6836 getCmpForMinMaxReduction(cast<Instruction>(ReductionRoot));
6840 ReductionRoot->replaceAllUsesWith(VectorizedTree);
6844 V.eraseInstructions(IgnoreList);
6846 return VectorizedTree !=
nullptr;
6849 unsigned numReductionValues()
const {
6850 return ReducedVals.
size();
6856 unsigned ReduxWidth) {
6860 int PairwiseRdxCost;
6861 int SplittingRdxCost;
6862 switch (ReductionData.getKind()) {
6876 bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
6877 ReductionData.getKind() == RK_UMax;
6890 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
6891 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
6893 int ScalarReduxCost = 0;
6894 switch (ReductionData.getKind()) {
6911 ScalarReduxCost *= (ReduxWidth - 1);
6913 LLVM_DEBUG(
dbgs() <<
"SLP: Adding cost " << VecReduxCost - ScalarReduxCost
6914 <<
" for reduction that starts with " << *FirstReducedVal
6916 << (IsPairwiseReduction ?
"pairwise" :
"splitting")
6917 <<
" reduction)\n");
6919 return VecReduxCost - ScalarReduxCost;
6925 assert(VectorizedValue &&
"Need to have a vectorized tree node");
6927 "We only handle power-of-two reductions for now");
6929 if (!IsPairwiseReduction) {
6934 Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
6935 ReductionData.getFlags(), ReductionOps.back());
6938 Value *TmpVec = VectorizedValue;
6939 for (
unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
6950 OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
6951 RightShuf, ReductionData.getKind());
6952 TmpVec = VectReductionData.createOp(Builder,
"op.rdx", ReductionOps);
6979 assert((isa<InsertElementInst>(LastInsertInst) ||
6980 isa<InsertValueInst>(LastInsertInst)) &&
6981 "Expected insertelement or insertvalue instruction!");
6984 Value *InsertedOperand;
6985 if (
auto *
IE = dyn_cast<InsertElementInst>(LastInsertInst)) {
6986 InsertedOperand =
IE->getOperand(1);
6987 LastInsertInst =
IE->getOperand(0);
6988 if (
auto *CI = dyn_cast<ConstantInt>(
IE->getOperand(2))) {
6990 IE->getType(), CI->getZExtValue());
6993 auto *IV = cast<InsertValueInst>(LastInsertInst);
6994 InsertedOperand = IV->getInsertedValueOperand();
6995 LastInsertInst = IV->getAggregateOperand();
6997 if (isa<InsertElementInst>(InsertedOperand) ||
6998 isa<InsertValueInst>(InsertedOperand)) {
7005 TmpBuildVectorOpds.
rend());
7006 UserCost += TmpUserCost;
7008 BuildVectorOpds.
push_back(InsertedOperand);
7010 if (isa<UndefValue>(LastInsertInst))
7012 if ((!isa<InsertValueInst>(LastInsertInst) &&
7013 !isa<InsertElementInst>(LastInsertInst)) ||
7037 auto DominatedReduxValue = [&](
Value *R) {
7038 return isa<Instruction>(R) &&
7042 Value *Rdx =
nullptr;
7051 if (Rdx && DominatedReduxValue(Rdx))
7070 if (Rdx && DominatedReduxValue(Rdx))
7097 if (Root->
getParent() != BB || isa<PHINode>(Root))
7111 while (!Stack.empty()) {
7114 std::tie(Inst, Level) = Stack.pop_back_val();
7118 HorizontalReduction HorRdx;
7119 if (HorRdx.matchAssociativeReduction(P, Inst)) {
7120 if (HorRdx.tryToReduce(R, TTI)) {
7143 if (Vectorize(Inst, R)) {
7153 if (VisitedInstrs.
insert(
Op).second)
7154 if (
auto *I = dyn_cast<Instruction>(
Op))
7155 if (!isa<PHINode>(I) && !R.isDeleted(I) && I->
getParent() == BB)
7156 Stack.emplace_back(I, Level);
7161 bool SLPVectorizerPass::vectorizeRootInstruction(
PHINode *P,
Value *V,
7170 if (!isa<BinaryOperator>(I))
7173 auto &&ExtraVectorization = [
this](
Instruction *
I, BoUpSLP &R) ->
bool {
7174 return tryToVectorize(I, R);
7177 ExtraVectorization);
7180 bool SLPVectorizerPass::vectorizeInsertValueInst(
InsertValueInst *IVI,
7184 if (!R.canMapToVector(IVI->
getType(), DL))
7191 LLVM_DEBUG(
dbgs() <<
"SLP: array mappable to vector: " << *IVI <<
"\n");
7194 return tryToVectorizeList(BuildVectorOpds, R, UserCost);
7203 [](
Value *V) {
return isa<ExtractElementInst>(V); }) &&
7209 return tryToVectorizeList(BuildVectorOpds, R, UserCost);
7217 bool OpsChanged =
false;
7218 for (
int Idx = 0; Idx < 2; ++Idx) {
7220 vectorizeRootInstruction(
nullptr, CI->
getOperand(Idx), BB, R, TTI);
7225 bool SLPVectorizerPass::vectorizeSimpleInstructions(
7227 bool OpsChanged =
false;
7228 for (
auto *I :
reverse(Instructions)) {
7231 if (
auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
7232 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
7233 else if (
auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
7234 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
7235 else if (
auto *CI = dyn_cast<CmpInst>(I))
7236 OpsChanged |= vectorizeCmpInst(CI, BB, R);
7238 Instructions.
clear();
7242 bool SLPVectorizerPass::vectorizeChainsInBlock(
BasicBlock *BB, BoUpSLP &R) {
7243 bool Changed =
false;
7247 bool HaveVectorizedPhiNodes =
true;
7248 while (HaveVectorizedPhiNodes) {
7249 HaveVectorizedPhiNodes =
false;
7258 if (!VisitedInstrs.
count(P) && !R.isDeleted(P))
7272 while (SameTypeIt != E &&
7273 (*SameTypeIt)->getType() == (*IncIt)->getType()) {
7274 VisitedInstrs.
insert(*SameTypeIt);
7279 unsigned NumElts = (SameTypeIt - IncIt);
7280 LLVM_DEBUG(
dbgs() <<
"SLP: Trying to vectorize starting at PHIs (" 7281 << NumElts <<
")\n");
7286 bool AllowReorder = NumElts == 2;
7287 if (NumElts > 1 && tryToVectorizeList(
makeArrayRef(IncIt, NumElts), R,
7290 HaveVectorizedPhiNodes =
true;
7300 VisitedInstrs.
clear();
7306 if (R.isDeleted(&*it))
7309 if (!VisitedInstrs.
insert(&*it).second) {
7310 if (it->use_empty() && KeyNodes.
count(&*it) > 0 &&
7311 vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
7321 if (isa<DbgInfoIntrinsic>(it))
7325 if (
PHINode *P = dyn_cast<PHINode>(it)) {
7344 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
7345 isa<InvokeInst>(it))) {
7347 bool OpsChanged =
false;
7349 for (
auto *V : it->operand_values()) {
7351 OpsChanged |= vectorizeRootInstruction(
nullptr, V, BB, R, TTI);
7357 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
7368 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
7369 isa<InsertValueInst>(it))
7370 PostProcessInstructions.
push_back(&*it);
7376 bool SLPVectorizerPass::vectorizeGEPIndices(
BasicBlock *BB, BoUpSLP &R) {
7377 auto Changed =
false;
7378 for (
auto &
Entry : GEPs) {
7381 if (
Entry.second.size() < 2)
7384 LLVM_DEBUG(
dbgs() <<
"SLP: Analyzing a getelementptr list of length " 7385 <<
Entry.second.size() <<
".\n");
7389 unsigned MaxVecRegSize = R.getMaxVecRegSize();
7390 unsigned EltSize = R.getVectorElementSize(
Entry.second[0]);
7391 if (MaxVecRegSize < EltSize)
7394 unsigned MaxElts = MaxVecRegSize / EltSize;
7395 for (
unsigned BI = 0, BE =
Entry.second.size(); BI < BE; BI += MaxElts) {
7396 auto Len = std::min<unsigned>(BE - BI, MaxElts);
7409 [&R](
Value *I) {
return R.isDeleted(cast<Instruction>(I)); });
7416 for (
int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++
I) {
7417 auto *GEPI = GEPList[
I];
7418 if (!Candidates.count(GEPI))
7420 auto *SCEVI = SE->
getSCEV(GEPList[I]);
7421 for (
int J = I + 1; J < E && Candidates.size() > 1; ++J) {
7422 auto *GEPJ = GEPList[J];
7423 auto *SCEVJ = SE->
getSCEV(GEPList[J]);
7424 if (isa<SCEVConstant>(SE->
getMinusSCEV(SCEVI, SCEVJ))) {
7425 Candidates.remove(GEPI);
7426 Candidates.remove(GEPJ);
7427 }
else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
7428 Candidates.remove(GEPJ);
7435 if (Candidates.size() < 2)
7442 auto BundleIndex = 0u;
7443 for (
auto *V : Candidates) {
7444 auto *
GEP = cast<GetElementPtrInst>(V);
7445 auto *GEPIdx =
GEP->idx_begin()->get();
7446 assert(
GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
7447 Bundle[BundleIndex++] = GEPIdx;
7459 Changed |= tryToVectorizeList(Bundle, R);
7465 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
7466 bool Changed =
false;
7468 for (StoreListMap::iterator it = Stores.
begin(),
e = Stores.
end(); it !=
e;
7470 if (it->second.size() < 2)
7474 << it->second.size() <<
".\n");
7476 Changed |= vectorizeStores(it->second, R);
Legacy wrapper pass to provide the GlobalsAAResult object.
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
Pass interface - Implemented by all 'passes'.
const T & front() const
front - Get the first element.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, AliasSetTracker *AST, MemorySSAUpdater *MSSAU)
bool hasOperandBundles() const
Return true if this User has any operand bundles.
static cl::opt< bool > ViewSLPTree("view-slp-tree", cl::Hidden, cl::desc("Display the SLP trees with Graphviz"))
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static std::string getNodeAttributes(const TreeEntry *Entry, const BoUpSLP *)
static cl::opt< int > SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, cl::desc("Only vectorize if you gain more than this " "number "))
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
reference emplace_back(ArgTypes &&... Args)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
ValueList getVL(unsigned OpIdx) const
a value vector with the operands across all lanes for the opearnd at OpIdx.
This class is the base class for the comparison instructions.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
LLVM_DUMP_METHOD raw_ostream & print(raw_ostream &OS) const
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static bool allConstant(ArrayRef< Value *> VL)
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
FastMathFlags getFastMathFlags() const
Get the flags to be applied to created floating point ops.
MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock *> Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
const T & back() const
back - Get the last element.
void setFast(bool B=true)
DiagnosticInfoOptimizationBase::Argument NV
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
OptimizationRemarkEmitter * getORE()
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
This structure holds any data we need about the edges being traversed during buildTree_rec().
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static InstructionsState getSameOpcode(ArrayRef< Value *> VL, unsigned BaseIndex=0)
static Value * getReductionValue(const DominatorTree *DT, PHINode *P, BasicBlock *ParentBB, LoopInfo *LI)
Try and get a reduction value from a phi node.
static LLVM_DUMP_METHOD void dumpMode(ReorderingMode RMode)
Debug print.
void push_back(const T &Elt)
static cl::opt< int > MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, cl::desc("Attempt to vectorize for this register size in bits"))
static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, TargetLibraryInfo *TLI)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
unsigned getBundleOperandsStartIndex() const
Return the index of the first bundle operand in the Use array.
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value *> VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal, MD_access_group].
The main scalar evolution driver.
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
This class represents a function call, abstracting a target machine's calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void dump(raw_ostream &OS) const
Debug print.
An immutable pass that tracks lazily created AssumptionCache objects.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
reverse_iterator rbegin() const
const Value * getTrueValue() const
An efficient, type-erasing, non-owning reference to a callable.
static const unsigned MaxMemDepDistance
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
0 1 0 0 True if ordered and less than
static bool collectValuesToDemote(Value *V, SmallPtrSetImpl< Value *> &Expr, SmallVectorImpl< Value *> &ToDemote, SmallVectorImpl< Value *> &Roots)
Value * createSimpleTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, unsigned Opcode, Value *Src, TargetTransformInfo::ReductionFlags Flags=TargetTransformInfo::ReductionFlags(), ArrayRef< Value *> RedOps=None)
Create a target reduction of the given vector.
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
reverse_iterator rbegin()
MaxMin_match< FCmpInst, LHS, RHS, ufmax_pred_ty > m_UnordFMax(const LHS &L, const RHS &R)
Match an 'unordered' floating point maximum function.
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
DOTGraphTraits(bool isSimple=false)
This defines the Use class.
void reserve(size_type N)
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
nodes_iterator(const ItTy &It2)
static cl::opt< int > LookAheadMaxDepth("slp-max-look-ahead-depth", cl::init(2), cl::Hidden, cl::desc("The maximum look-ahead depth for operand reordering scores"))
BoUpSLP::TreeEntry::VecTreeTy ContainerTy
TypeSize getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
*ViewGraph Emit a dot run run gv on the postscript *then cleanup For use from the debugger *void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
static bool isValidForAlternation(unsigned Opcode)
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
LLVM_DUMP_METHOD void dump() const
Debug print.
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
static nodes_iterator nodes_end(BoUpSLP *R)
Value * getArgOperand(unsigned i) const
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
static uint32_t getAlignment(const MCSectionCOFF &Sec)
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
static cl::opt< unsigned > RecursionMaxDepth("slp-recursion-max-depth", cl::init(12), cl::Hidden, cl::desc("Limit the recursion depth when building a vectorizable tree"))
static void inversePermutation(ArrayRef< unsigned > Indices, SmallVectorImpl< unsigned > &Mask)
Type * getIndexType(Type *PtrTy) const
Returns the type of a GEP index.
static Optional< TargetTransformInfo::ShuffleKind > isShuffle(ArrayRef< Value *> VL)
Checks if the vector of instructions can be represented as a shuffle, like: x0 = extractelement <4 x ...
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElement(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
This class represents the LLVM 'select' instruction.
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
ChildIteratorType(SmallVector< BoUpSLP::EdgeInfo, 1 >::iterator W, ContainerTy &VT)
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
unsigned getTreeSize() const
An analysis that produces DemandedBits for a function.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
0 1 0 1 True if ordered and less than or equal
This file contains the simple types necessary to represent the attributes associated with functions a...
Direction
An enum for the direction of the loop.
MaxMin_match< FCmpInst, LHS, RHS, ufmin_pred_ty > m_UnordFMin(const LHS &L, const RHS &R)
Match an 'unordered' floating point minimum function.
static const unsigned AliasedCheckLimit
Analysis pass that exposes the LoopInfo for a function.
mir Rename Register Operands
Value * CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name="")
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
static cl::opt< bool > ShouldStartVectorizeHorAtStore("slp-vectorize-hor-store", cl::init(false), cl::Hidden, cl::desc("Attempt to vectorize horizontal reductions feeding into a store"))
void assign(size_type NumElts, const T &Elt)
static ChildIteratorType child_end(NodeRef N)
static bool allSameBlock(ArrayRef< Value *> VL)
static bool isSimple(Instruction *I)
bool isDeleted(Instruction *I) const
Checks if the instruction is marked for deletion.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
Value * CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name="")
TreeEntry * NodeRef
NodeRef has to be a pointer per the GraphWriter.
BoUpSLP::TreeEntry TreeEntry
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
static cl::opt< unsigned > LookAheadUsersBudget("slp-look-ahead-users-budget", cl::init(2), cl::Hidden, cl::desc("The maximum number of users to visit while visiting the " "predecessors. This prevents compilation time increase."))
const T & getValue() const LLVM_LVALUE_FUNCTION
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
MaxMin_match< FCmpInst, LHS, RHS, ofmin_pred_ty > m_OrdFMin(const LHS &L, const RHS &R)
Match an 'ordered' floating point minimum function.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
void insert(ScheduleData *SD)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
iterator_range< User::op_iterator > arg_operands()
static Value * createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx, bool IsPairwise, bool IsLeft, IRBuilder<> &Builder)
Generate a shuffle mask to be used in a reduction tree.
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator find(const KeyT &Key)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
Class to represent pointers.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
static ChildIteratorType child_begin(NodeRef N)
unsigned getMinVecRegSize() const
friend raw_ostream & operator<<(raw_ostream &OS, ReorderingMode RMode)
iterator find(const_arg_type_t< KeyT > Val)
bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
cl::opt< bool > RunSLPVectorization
static bool runOnFunction(Function &F, bool PostInlining)
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R)
initializer< Ty > init(const Ty &Val)
This instruction inserts a single (scalar) element into a VectorType value.
static const int MinScheduleRegionSize
If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling regions to be handled...
typename GraphType::UnknownGraphTypeError NodeRef
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
BoUpSLP::TreeEntry TreeEntry
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
This is an important class for using LLVM in a threaded context.
static bool tryToVectorizeHorReductionOrInstOperands(PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, TargetTransformInfo *TTI, const function_ref< bool(Instruction *, BoUpSLP &)> Vectorize)
Attempt to reduce a horizontal reduction.
CRTP base class for adapting an iterator to a different type.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
ContainerTy & VectorizableTree
EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
Value * CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
static LLVM_DUMP_METHOD raw_ostream & printMode(ReorderingMode RMode, raw_ostream &OS)
friend raw_ostream & operator<<(raw_ostream &OS, const BoUpSLP::EdgeInfo &EI)
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
bool isFast() const
'Fast' means all bits are set.
Represent the analysis usage information of a pass.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
TreeEntry * UserTE
The user TreeEntry.
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
FunctionPass class - This class is used to implement most global optimizations.
LLVM_DUMP_METHOD void dump() const
Value * getPointerOperand()
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
unsigned getBundleOperandsEndIndex() const
Return the index of the last bundle operand in the Use array.
iterator_range< po_iterator< T > > post_order(const T &G)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Class to represent integer types.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
nodes_iterator operator++()
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
Used in the streaming interface as the general argument type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static Optional< unsigned > getExtractIndex(Instruction *E)
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
1 1 0 1 True if unordered, less than, or equal
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void propagateIRFlags(Value *I, ArrayRef< Value *> VL, Value *OpValue=nullptr)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
deferredval_ty< Value > m_Deferred(Value *const &V)
A commutative-friendly version of m_Specific().
static Value * isOneOf(const InstructionsState &S, Value *Op)
Chooses the correct key for scheduling data.
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
Value * CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
0 0 1 0 True if ordered and greater than
A function analysis which provides an AssumptionCache.
static cl::opt< int > MinVectorRegSizeOption("slp-min-reg-size", cl::init(128), cl::Hidden, cl::desc("Attempt to vectorize for this register size in bits"))
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
print lazy value Lazy Value Info Printer Pass
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Align max(MaybeAlign Lhs, Align Rhs)
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
testing::Matcher< const detail::ErrorHolder & > Failed()
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
1 1 0 0 True if unordered or less than
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
void setAlignment(MaybeAlign Alignment)
size_type count(const KeyT &Key) const
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
User(Type *ty, unsigned vty, Use *, unsigned NumOps)
static bool findBuildAggregate(Value *LastInsertInst, TargetTransformInfo *TTI, SmallVectorImpl< Value *> &BuildVectorOpds, int &UserCost)
Recognize construction of vectors like ra = insertelement <4 x float> undef, float s0...
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static nodes_iterator nodes_begin(BoUpSLP *R)
static uint32_t getFlags(const Symbol *Sym)
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Optional< ArrayRef< unsigned > > bestOrder() const
void setPreservesCFG()
This function should be called by the pass, iff they do not:
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the vector form of the intrinsic has a scalar operand.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool isCommutative() const
Return true if the instruction is commutative:
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Implements a dense probed hash-table based set with some number of buckets stored inline...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static bool allSameType(ArrayRef< Value *> VL)
iterator_range< user_iterator > users()
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
unsigned getMaxVecRegSize() const
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
Represents analyses that only rely on functions' control flow.
static void clear(coro::Shape &Shape)
iterator insert(iterator I, T &&Elt)
const Value * getFalseValue() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static cl::opt< int > ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, cl::desc("Limit the size of the SLP scheduling region per block"))
Limits the size of scheduling regions in a block.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Analysis pass that exposes the ScalarEvolution for a function.
bool operator!=(uint64_t V1, const APInt &V2)
reverse_iterator rend() const
Predicate getPredicate() const
Return the predicate for this instruction.
static unsigned size(BoUpSLP *R)
unsigned getNumArgOperands() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void initializeSLPVectorizerPass(PassRegistry &)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
This class represents an analyzed expression in the program.
unsigned getIntegerBitWidth() const
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
LLVM_NODISCARD bool empty() const
unsigned greater or equal
Represents a single loop in the control flow graph.
This file provides utility analysis objects describing memory locations.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
void preserveSet()
Mark an analysis set as preserved.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
bool runImpl(Function &F, ScalarEvolution *SE_, TargetTransformInfo *TTI_, TargetLibraryInfo *TLI_, AliasAnalysis *AA_, LoopInfo *LI_, DominatorTree *DT_, AssumptionCache *AC_, DemandedBits *DB_, OptimizationRemarkEmitter *ORE_)
static bool isValidElementType(Type *Ty)
Predicate for the element types that the SLP vectorizer supports.
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
VLOperands(ArrayRef< Value *> RootVL, const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R)
Initialize with all the operands of the instruction vector RootVL.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
iterator_range< value_op_iterator > operand_values()
friend raw_ostream & operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
ilist_iterator< OptionsT, !IsReverse, IsConst > getReverse() const
Get a reverse iterator to the same node.
void preserve()
Mark an analysis as preserved.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
static cl::opt< bool > ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, cl::desc("Attempt to vectorize horizontal reductions"))
1 0 1 0 True if unordered or greater than
bool hasIdenticalOperandBundleSchema(const CallBase &Other) const
Return true if Other has the same sequence of operand bundle tags with the same number of operands on...
Pass * createSLPVectorizerPass()
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
Loop::LoopBounds::Direction Direction
const std::string to_string(const T &Value)
Analysis pass providing the TargetLibraryInfo.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA)
static NodeRef getEntryNode(BoUpSLP &R)
reverse_iterator rbegin()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
static const char lv_name[]
static bool PhiTypeSorterFunc(Value *V, Value *V2)
void stable_sort(R &&Range)
A raw_ostream that writes to an std::string.
MaxMin_match< FCmpInst, LHS, RHS, ofmax_pred_ty > m_OrdFMax(const LHS &L, const RHS &R)
Match an 'ordered' floating point maximum function.
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
1 0 1 1 True if unordered, greater than, or equal
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
static cl::opt< int > MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, cl::desc("Maximum depth of the lookup for consecutive stores."))
A vector that has set insertion semantics.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static bool isCommutative(Instruction *I)
This class implements an extremely fast bulk output stream that can only output to a stream...
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
The legacy pass manager's analysis pass to compute loop information.
bool hasOneUse() const
Return true if there is exactly one user of this value.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
bool isNonNegative() const
Returns true if this value is known to be non-negative.
A container for analyses that lazily runs them and caches their results.
static bool isSplat(ArrayRef< Value *> VL)
Legacy analysis pass which computes a DominatorTree.
void deleteTree()
Clear the internal data structures that are created by 'buildTree'.
bool operator==(uint64_t V1, const APInt &V2)
static LLVM_DUMP_METHOD StringRef getModeStr(ReorderingMode RMode)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
This header defines various interfaces for pass management in LLVM.
static bool isAssociative(const COFFSection &Section)
op_range incoming_values()
bool operator!=(const nodes_iterator &N2) const
0 0 1 1 True if ordered and greater than or equal
Bottom Up SLP Vectorizer.
A helper data structure to hold the operands of a vector of instructions.
static cl::opt< unsigned > MinTreeSize("slp-min-tree-size", cl::init(3), cl::Hidden, cl::desc("Only vectorize small trees if they are fully vectorizable"))
bool sortPtrAccesses(ArrayRef< Value *> VL, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< unsigned > &SortedIndices)
Attempt to sort the pointers in VL and return the sorted indices in SortedIndices, if reordering is required.
Value * getPointerOperand()
static Constant * get(ArrayRef< Constant *> V)
BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, const DataLayout *DL, OptimizationRemarkEmitter *ORE)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
bool empty() const
empty - Check if the array is empty.
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
const BasicBlock * getParent() const
This class represents a constant integer value.
This instruction inserts a struct field of array element value into an aggregate value.
bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.