66 #include "llvm/Config/llvm-config.h" 95 #define DEBUG_TYPE "pipeliner" 97 STATISTIC(NumTrytoPipeline,
"Number of loops that we attempt to pipeline");
98 STATISTIC(NumPipelined,
"Number of loops software pipelined");
99 STATISTIC(NumNodeOrderIssues,
"Number of node order issues found");
100 STATISTIC(NumFailBranch,
"Pipeliner abort due to unknown branch");
101 STATISTIC(NumFailLoop,
"Pipeliner abort due to unsupported loop");
102 STATISTIC(NumFailPreheader,
"Pipeliner abort due to missing preheader");
103 STATISTIC(NumFailLargeMaxMII,
"Pipeliner abort due to MaxMII too large");
104 STATISTIC(NumFailZeroMII,
"Pipeliner abort due to zero MII");
105 STATISTIC(NumFailNoSchedule,
"Pipeliner abort due to no schedule found");
106 STATISTIC(NumFailZeroStage,
"Pipeliner abort due to zero stage");
107 STATISTIC(NumFailLargeMaxStage,
"Pipeliner abort due to too many stages");
112 cl::desc(
"Enable Software Pipelining"));
121 cl::desc(
"Size limit for the MII."),
127 cl::desc(
"Maximum stages allowed in the generated scheduled."),
134 cl::desc(
"Prune dependences between unrelated Phi nodes."),
141 cl::desc(
"Prune loop carried order dependences."),
159 cl::desc(
"Instead of emitting the pipelined code, annotate instructions " 160 "with the generated schedule for feeding into the " 161 "-modulo-schedule-test pass"));
166 "Use the experimental peeling code generator for software pipelining"));
174 cl::desc(
"Enable CopyToPhi DAG Mutation"));
178 unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
186 "Modulo Software Pipelining",
false,
false)
196 if (skipFunction(mf.getFunction()))
202 if (mf.getFunction().getAttributes().hasAttribute(
207 if (!mf.getSubtarget().enableMachinePipeliner())
212 if (mf.getSubtarget().useDFAforSMS() &&
213 (!mf.getSubtarget().getInstrItineraryData() ||
214 mf.getSubtarget().getInstrItineraryData()->isEmpty()))
218 MLI = &getAnalysis<MachineLoopInfo>();
219 MDT = &getAnalysis<MachineDominatorTree>();
220 TII = MF->getSubtarget().getInstrInfo();
221 RegClassInfo.runOnMachineFunction(*MF);
233 bool MachinePipeliner::scheduleLoop(
MachineLoop &L) {
234 bool Changed =
false;
235 for (
auto &InnerLoop : L)
236 Changed |= scheduleLoop(*InnerLoop);
248 setPragmaPipelineOptions(L);
249 if (!canPipelineLoop(L)) {
256 Changed = swingModuloScheduler(L);
261 void MachinePipeliner::setPragmaPipelineOptions(
MachineLoop &L) {
276 if (LoopID ==
nullptr)
293 if (S->
getString() ==
"llvm.loop.pipeline.initiationinterval") {
295 "Pipeline initiation interval hint metadata should have two operands.");
297 mdconst::extract<ConstantInt>(MD->
getOperand(1))->getZExtValue();
298 assert(II_setByPragma >= 1 &&
"Pipeline initiation interval must be positive.");
299 }
else if (S->
getString() ==
"llvm.loop.pipeline.disable") {
308 bool MachinePipeliner::canPipelineLoop(
MachineLoop &L) {
322 dbgs() <<
"Unable to analyzeBranch, can NOT pipeline current Loop\n");
331 dbgs() <<
"Unable to analyzeLoop, can NOT pipeline current Loop\n");
338 dbgs() <<
"Preheader not found, can NOT pipeline current Loop\n");
350 SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
357 for (
unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
368 auto Copy =
BuildMI(PredB, At, DL,
TII->
get(TargetOpcode::COPY), NewReg)
382 bool MachinePipeliner::swingModuloScheduler(
MachineLoop &L) {
383 assert(L.
getBlocks().size() == 1 &&
"SMS works on single blocks only.");
406 return SMS.hasNewSchedule();
409 void SwingSchedulerDAG::setMII(
unsigned ResMII,
unsigned RecMII) {
416 void SwingSchedulerDAG::setMAX_II() {
428 addLoopCarriedDependences(AA);
429 updatePhiDependences();
430 Topo.InitDAGTopologicalSorting();
436 findCircuits(NodeSets);
440 unsigned ResMII = calculateResMII();
441 unsigned RecMII = calculateRecMII(NodeSets);
449 setMII(ResMII, RecMII);
453 <<
" (rec=" << RecMII <<
", res=" << ResMII <<
")\n");
459 <<
"0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
467 <<
", we don't pipleline large loops\n");
468 NumFailLargeMaxMII++;
472 computeNodeFunctions(NodeSets);
474 registerPressureFilter(NodeSets);
476 colocateNodeSets(NodeSets);
478 checkNodeSets(NodeSets);
481 for (
auto &
I : NodeSets) {
482 dbgs() <<
" Rec NodeSet ";
489 groupRemainingNodes(NodeSets);
491 removeDuplicateNodes(NodeSets);
494 for (
auto &
I : NodeSets) {
495 dbgs() <<
" NodeSet ";
500 computeNodeOrder(NodeSets);
503 checkValidNodeOrder(Circuits);
506 Scheduled = schedulePipeline(Schedule);
516 if (numStages == 0) {
518 dbgs() <<
"No overlapped iterations, no need to generate pipeline\n");
525 <<
" : too many stages, abort\n");
526 NumFailLargeMaxStage++;
532 std::vector<MachineInstr *> OrderedInsts;
536 OrderedInsts.push_back(SU->getInstr());
537 Cycles[SU->getInstr()] = Cycle;
542 for (
auto &KV : NewMIs) {
543 Cycles[KV.first] = Cycles[KV.second];
544 Stages[KV.first] = Stages[KV.second];
545 NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
552 "Cannot serialize a schedule with InstrChanges!");
571 for (
auto &KV : NewMIs)
582 unsigned &InitVal,
unsigned &LoopVal) {
593 assert(InitVal != 0 && LoopVal != 0 &&
"Unexpected Phi structure.");
609 while (!Worklist.
empty()) {
614 if (Visited.
count(SuccSU))
647 for (
const Value *V : Objs) {
660 void SwingSchedulerDAG::addLoopCarriedDependences(
AliasAnalysis *AA) {
662 Value *UnknownValue =
664 for (
auto &SU : SUnits) {
667 PendingLoads.
clear();
673 for (
auto V : Objs) {
682 for (
auto V : Objs) {
684 PendingLoads.
find(V);
685 if (I == PendingLoads.
end())
687 for (
auto Load : I->second) {
695 int64_t Offset1, Offset2;
699 (int)Offset1 < (
int)Offset2) {
701 "What happened to the chain edge?");
755 void SwingSchedulerDAG::updatePhiDependences() {
763 unsigned HasPhiUse = 0;
764 unsigned HasPhiDef = 0;
776 UI =
MRI.use_instr_begin(Reg),
777 UE =
MRI.use_instr_end();
780 SUnit *SU = getSUnit(UseMI);
781 if (SU !=
nullptr && UseMI->
isPHI()) {
790 if (SU->
NodeNum <
I.NodeNum && !
I.isPred(SU))
795 }
else if (MOI->isUse()) {
798 if (DefMI ==
nullptr)
800 SUnit *SU = getSUnit(DefMI);
801 if (SU !=
nullptr && DefMI->
isPHI()) {
811 if (SU->
NodeNum <
I.NodeNum && !
I.isPred(SU))
820 for (
auto &PI :
I.Preds) {
823 if (
I.getInstr()->isPHI()) {
832 for (
int i = 0,
e = RemoveDeps.
size(); i !=
e; ++i)
833 I.removePred(RemoveDeps[i]);
839 void SwingSchedulerDAG::changeDependences() {
844 unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
845 int64_t NewOffset = 0;
846 if (!canUseLastOffsetValue(
I.getInstr(), BasePos, OffsetPos, NewBase,
851 Register OrigBase =
I.getInstr()->getOperand(BasePos).getReg();
855 SUnit *DefSU = getSUnit(DefMI);
862 SUnit *LastSU = getSUnit(LastMI);
866 if (Topo.IsReachable(&
I, LastSU))
873 if (
P->getSUnit() == DefSU)
875 for (
int i = 0,
e = Deps.
size(); i !=
e; i++) {
876 Topo.RemovePred(&
I, Deps[i].getSUnit());
877 I.removePred(Deps[i]);
881 for (
auto &
P : LastSU->
Preds)
884 for (
int i = 0,
e = Deps.
size(); i !=
e; i++) {
885 Topo.RemovePred(LastSU, Deps[i].getSUnit());
892 Topo.AddPred(LastSU, &
I);
897 InstrChanges[&
I] = std::make_pair(NewBase, NewOffset);
905 struct FuncUnitSorter {
916 unsigned minFuncUnits(
const MachineInstr *Inst,
unsigned &
F)
const {
918 unsigned min = UINT_MAX;
919 if (InstrItins && !InstrItins->
isEmpty()) {
922 InstrItins->
endStage(SchedClass))) {
923 unsigned funcUnits = IS.getUnits();
925 if (numAlternatives < min) {
926 min = numAlternatives;
947 unsigned NumUnits = ProcResource->
NumUnits;
948 if (NumUnits < min) {
950 F = PRE.ProcResourceIdx;
955 llvm_unreachable(
"Should have non-empty InstrItins or hasInstrSchedModel!");
965 if (InstrItins && !InstrItins->
isEmpty()) {
968 InstrItins->
endStage(SchedClass))) {
969 unsigned FuncUnits = IS.getUnits();
971 Resources[FuncUnits]++;
988 Resources[PRE.ProcResourceIdx]++;
992 llvm_unreachable(
"Should have non-empty InstrItins or hasInstrSchedModel!");
997 unsigned F1 = 0, F2 = 0;
998 unsigned MFUs1 = minFuncUnits(IS1, F1);
999 unsigned MFUs2 = minFuncUnits(IS2, F2);
1002 return MFUs1 > MFUs2;
1014 unsigned SwingSchedulerDAG::calculateResMII() {
1027 FUS.calcCriticalResources(*
I);
1034 FuncUnitOrder.push(&*
I);
1036 while (!FuncUnitOrder.empty()) {
1038 FuncUnitOrder.pop();
1043 unsigned NumCycles = getSUnit(MI)->Latency;
1044 unsigned ReservedCycles = 0;
1048 dbgs() <<
"Trying to reserve resource for " << NumCycles
1049 <<
" cycles for \n";
1052 for (
unsigned C = 0;
C < NumCycles; ++
C)
1054 if ((*RI)->canReserveResources(*MI)) {
1055 (*RI)->reserveResources(*MI);
1062 <<
", NumCycles:" << NumCycles <<
"\n");
1064 for (
unsigned C = ReservedCycles;
C < NumCycles; ++
C) {
1066 <<
"NewResource created to reserve resources" 1074 int Resmii = Resources.
size();
1091 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1092 unsigned RecMII = 0;
1094 for (
NodeSet &Nodes : NodeSets) {
1098 unsigned Delay = Nodes.getLatency();
1099 unsigned Distance = 1;
1102 unsigned CurMII = (Delay + Distance - 1) / Distance;
1103 Nodes.setRecMII(CurMII);
1104 if (CurMII > RecMII)
1115 for (
unsigned i = 0,
e = SUnits.size(); i !=
e; ++i) {
1116 SUnit *SU = &SUnits[i];
1121 DepsAdded.
push_back(std::make_pair(SU, *IP));
1125 E = DepsAdded.
end();
1141 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1145 for (
int i = 0,
e = SUnits.size(); i !=
e; ++i) {
1148 for (
auto &
SI : SUnits[i].Succs) {
1152 int N =
SI.getSUnit()->NodeNum;
1154 auto Dep = OutputDeps.find(BackEdge);
1155 if (Dep != OutputDeps.end()) {
1156 BackEdge = Dep->second;
1157 OutputDeps.erase(Dep);
1159 OutputDeps[
N] = BackEdge;
1163 if (
SI.getSUnit()->isBoundaryNode() ||
SI.isArtificial() ||
1164 (
SI.getKind() ==
SDep::Anti && !
SI.getSUnit()->getInstr()->isPHI()))
1166 int N =
SI.getSUnit()->NodeNum;
1167 if (!Added.test(N)) {
1168 AdjK[i].push_back(N);
1174 for (
auto &PI : SUnits[i].Preds) {
1175 if (!SUnits[i].getInstr()->mayStore() ||
1178 if (PI.getKind() ==
SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1179 int N = PI.getSUnit()->NodeNum;
1180 if (!Added.test(N)) {
1181 AdjK[i].push_back(N);
1188 for (
auto &OD : OutputDeps)
1189 if (!Added.test(OD.second)) {
1190 AdjK[OD.first].push_back(OD.second);
1191 Added.set(OD.second);
1197 bool SwingSchedulerDAG::Circuits::circuit(
int V,
int S, NodeSetType &NodeSets,
1199 SUnit *SV = &SUnits[V];
1204 for (
auto W : AdjK[V]) {
1205 if (NumPaths > MaxPaths)
1211 NodeSets.push_back(
NodeSet(Stack.begin(), Stack.end()));
1215 }
else if (!Blocked.test(
W)) {
1216 if (circuit(
W, S, NodeSets,
1217 Node2Idx->at(
W) < Node2Idx->at(V) ?
true : HasBackedge))
1225 for (
auto W : AdjK[V]) {
1237 void SwingSchedulerDAG::Circuits::unblock(
int U) {
1240 while (!BU.
empty()) {
1242 assert(SI != BU.
end() &&
"Invalid B set.");
1245 if (Blocked.test(W->NodeNum))
1246 unblock(W->NodeNum);
1252 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1257 Circuits Cir(SUnits, Topo);
1259 Cir.createAdjacencyStructure(
this);
1260 for (
int i = 0,
e = SUnits.size(); i !=
e; ++i) {
1262 Cir.circuit(i, i, NodeSets);
1298 for (
auto &Dep : SU.
Preds) {
1299 SUnit *TmpSU = Dep.getSUnit();
1311 if (PHISUs.
size() == 0 || SrcSUs.
size() == 0)
1319 for (
auto &Dep : PHISUs[
Index]->Succs) {
1323 SUnit *TmpSU = Dep.getSUnit();
1333 if (UseSUs.
size() == 0)
1338 for (
auto I : UseSUs) {
1339 for (
auto Src : SrcSUs) {
1364 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1365 ScheduleInfo.resize(SUnits.size());
1371 const SUnit &SU = SUnits[*
I];
1382 int zeroLatencyDepth = 0;
1385 EP = SU->
Preds.end();
1388 if (IP->getLatency() == 0)
1390 std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1393 asap =
std::max(asap, (
int)(getASAP(pred) + IP->getLatency() -
1394 getDistance(pred, SU, *IP) * MII));
1397 ScheduleInfo[*
I].ASAP = asap;
1398 ScheduleInfo[*
I].ZeroLatencyDepth = zeroLatencyDepth;
1406 int zeroLatencyHeight = 0;
1409 ES = SU->
Succs.end();
1411 SUnit *succ = IS->getSUnit();
1412 if (IS->getLatency() == 0)
1414 std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1417 alap = std::min(alap, (
int)(getALAP(succ) - IS->getLatency() +
1418 getDistance(SU, succ, *IS) * MII));
1421 ScheduleInfo[*
I].ALAP = alap;
1422 ScheduleInfo[*
I].ZeroLatencyHeight = zeroLatencyHeight;
1427 I.computeNodeSetInfo(
this);
1430 for (
unsigned i = 0; i < SUnits.size(); i++) {
1431 dbgs() <<
"\tNode " << i <<
":\n";
1432 dbgs() <<
"\t ASAP = " << getASAP(&SUnits[i]) <<
"\n";
1433 dbgs() <<
"\t ALAP = " << getALAP(&SUnits[i]) <<
"\n";
1434 dbgs() <<
"\t MOV = " << getMOV(&SUnits[i]) <<
"\n";
1436 dbgs() <<
"\t H = " << getHeight(&SUnits[i]) <<
"\n";
1437 dbgs() <<
"\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) <<
"\n";
1438 dbgs() <<
"\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) <<
"\n";
1454 if (S && S->count(PI->getSUnit()) == 0)
1458 if (NodeOrder.
count(PI->getSUnit()) == 0)
1459 Preds.
insert(PI->getSUnit());
1463 ES = (*I)->Succs.end();
1467 if (S && S->count(IS->getSUnit()) == 0)
1469 if (NodeOrder.
count(IS->getSUnit()) == 0)
1470 Preds.
insert(IS->getSUnit());
1473 return !Preds.
empty();
1487 if (S && S->count(
SI->getSUnit()) == 0)
1491 if (NodeOrder.
count(
SI->getSUnit()) == 0)
1495 PE = (*I)->Preds.end();
1499 if (S && S->count(PI->getSUnit()) == 0)
1501 if (NodeOrder.
count(PI->getSUnit()) == 0)
1502 Succs.
insert(PI->getSUnit());
1505 return !Succs.
empty();
1516 if (Exclude.
count(Cur) != 0)
1518 if (DestNodes.
count(Cur) != 0)
1520 if (!Visited.
insert(Cur).second)
1521 return Path.
count(Cur) != 0;
1522 bool FoundPath =
false;
1524 FoundPath |=
computePath(
SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1525 for (
auto &PI : Cur->
Preds)
1528 computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1535 template <
class S1Ty,
class S2Ty>
static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1536 for (
typename S1Ty::iterator
I = Set1.begin(),
E = Set1.end();
I !=
E; ++
I)
1537 if (Set2.count(*
I) == 0)
1551 for (
SUnit *SU : NS) {
1556 if (MO.isReg() && MO.isUse()) {
1565 for (
SUnit *SU : NS)
1567 if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1570 if (!Uses.
count(Reg))
1575 if (!Uses.
count(*Units))
1585 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1586 for (
auto &NS : NodeSets) {
1596 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1601 for (
auto &SU : SUnits) {
1607 RecRPTracker.
setPos(std::next(CurInstI));
1616 dbgs() <<
"Excess register pressure: SU(" << SU->NodeNum <<
") " 1619 NS.setExceedPressure(SU);
1629 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1630 unsigned Colocate = 0;
1631 for (
int i = 0,
e = NodeSets.size(); i <
e; ++i) {
1636 for (
int j = i + 1; j <
e; ++j) {
1657 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1662 for (
auto &NS : NodeSets) {
1663 if (NS.getRecMII() > 2)
1665 if (NS.getMaxDepth() > MII)
1675 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1685 for (
SUnit *NI : N) {
1694 if (
succ_L(NodesAdded, N)) {
1696 for (
SUnit *NI : N) {
1703 NodesAdded.
insert(
I.begin(),
I.end());
1710 if (
succ_L(NodesAdded, N))
1712 addConnectedNodes(
I, NewSet, NodesAdded);
1713 if (!NewSet.
empty())
1714 NodeSets.push_back(NewSet);
1719 if (
pred_L(NodesAdded, N))
1721 addConnectedNodes(
I, NewSet, NodesAdded);
1722 if (!NewSet.
empty())
1723 NodeSets.push_back(NewSet);
1727 for (
unsigned i = 0; i < SUnits.size(); ++i) {
1728 SUnit *SU = &SUnits[i];
1729 if (NodesAdded.
count(SU) == 0) {
1731 addConnectedNodes(SU, NewSet, NodesAdded);
1732 if (!NewSet.
empty())
1733 NodeSets.push_back(NewSet);
1739 void SwingSchedulerDAG::addConnectedNodes(
SUnit *SU,
NodeSet &NewSet,
1745 if (!
SI.isArtificial() && NodesAdded.
count(Successor) == 0)
1746 addConnectedNodes(Successor, NewSet, NodesAdded);
1748 for (
auto &PI : SU->
Preds) {
1749 SUnit *Predecessor = PI.getSUnit();
1750 if (!PI.isArtificial() && NodesAdded.
count(Predecessor) == 0)
1751 addConnectedNodes(Predecessor, NewSet, NodesAdded);
1760 for (
unsigned i = 0,
e = Set1.
size(); i !=
e; ++i) {
1761 SUnit *SU = Set1[i];
1762 if (Set2.
count(SU) != 0)
1765 return !Result.
empty();
1769 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1770 for (NodeSetType::iterator
I = NodeSets.begin(),
E = NodeSets.end();
I !=
E;
1773 for (NodeSetType::iterator J =
I + 1; J !=
E;) {
1791 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1792 for (NodeSetType::iterator
I = NodeSets.begin(),
E = NodeSets.end();
I !=
E;
1794 for (NodeSetType::iterator J =
I + 1; J !=
E;) {
1795 J->remove_if([&](
SUnit *SUJ) {
return I->count(SUJ); });
1810 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1814 for (
auto &Nodes : NodeSets) {
1831 }
else if (NodeSets.size() == 1) {
1832 for (
auto &N : Nodes)
1833 if (N->Succs.
size() == 0)
1839 SUnit *maxASAP =
nullptr;
1840 for (
SUnit *SU : Nodes) {
1841 if (maxASAP ==
nullptr || getASAP(SU) > getASAP(maxASAP) ||
1842 (getASAP(SU) == getASAP(maxASAP) && SU->
NodeNum > maxASAP->
NodeNum))
1850 while (!R.
empty()) {
1851 if (Order == TopDown) {
1855 while (!R.
empty()) {
1856 SUnit *maxHeight =
nullptr;
1858 if (maxHeight ==
nullptr || getHeight(
I) > getHeight(maxHeight))
1860 else if (getHeight(
I) == getHeight(maxHeight) &&
1861 getZeroLatencyHeight(
I) > getZeroLatencyHeight(maxHeight))
1863 else if (getHeight(
I) == getHeight(maxHeight) &&
1864 getZeroLatencyHeight(
I) ==
1865 getZeroLatencyHeight(maxHeight) &&
1866 getMOV(
I) < getMOV(maxHeight))
1871 R.remove(maxHeight);
1872 for (
const auto &
I : maxHeight->
Succs) {
1873 if (Nodes.count(
I.getSUnit()) == 0)
1879 R.insert(
I.getSUnit());
1882 for (
const auto &
I : maxHeight->
Preds) {
1885 if (Nodes.count(
I.getSUnit()) == 0)
1889 R.insert(
I.getSUnit());
1901 while (!R.
empty()) {
1902 SUnit *maxDepth =
nullptr;
1907 getZeroLatencyDepth(
I) > getZeroLatencyDepth(maxDepth))
1910 getZeroLatencyDepth(
I) == getZeroLatencyDepth(maxDepth) &&
1911 getMOV(
I) < getMOV(maxDepth))
1917 if (Nodes.isExceedSU(maxDepth)) {
1920 R.insert(Nodes.getNode(0));
1923 for (
const auto &
I : maxDepth->
Preds) {
1924 if (Nodes.count(
I.getSUnit()) == 0)
1928 R.insert(
I.getSUnit());
1931 for (
const auto &
I : maxDepth->
Succs) {
1934 if (Nodes.count(
I.getSUnit()) == 0)
1938 R.insert(
I.getSUnit());
1952 dbgs() <<
"Node order: ";
1954 dbgs() <<
" " <<
I->NodeNum <<
" ";
1961 bool SwingSchedulerDAG::schedulePipeline(
SMSchedule &Schedule) {
1968 bool scheduleFound =
false;
1971 for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
1983 int EarlyStart = INT_MIN;
1984 int LateStart = INT_MAX;
1987 int SchedEnd = INT_MAX;
1988 int SchedStart = INT_MIN;
1989 Schedule.
computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1998 dbgs() <<
format(
"\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
1999 LateStart, SchedEnd, SchedStart);
2002 if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2003 SchedStart > LateStart)
2004 scheduleFound =
false;
2005 else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2006 SchedEnd = std::min(SchedEnd, EarlyStart + (
int)II - 1);
2007 scheduleFound = Schedule.
insert(SU, EarlyStart, SchedEnd, II);
2008 }
else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2009 SchedStart =
std::max(SchedStart, LateStart - (
int)II + 1);
2010 scheduleFound = Schedule.
insert(SU, LateStart, SchedStart, II);
2011 }
else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2013 std::min(SchedEnd, std::min(LateStart, EarlyStart + (
int)II - 1));
2018 scheduleFound = Schedule.
insert(SU, SchedEnd, EarlyStart, II);
2020 scheduleFound = Schedule.
insert(SU, EarlyStart, SchedEnd, II);
2023 scheduleFound = Schedule.
insert(SU, FirstCycle + getASAP(SU),
2024 FirstCycle + getASAP(SU) + II - 1, II);
2031 scheduleFound =
false;
2035 dbgs() <<
"\tCan't schedule\n";
2037 }
while (++NI != NE && scheduleFound);
2044 LLVM_DEBUG(
dbgs() <<
"Schedule Found? " << scheduleFound <<
" (II=" << II
2057 bool SwingSchedulerDAG::computeDelta(
MachineInstr &
MI,
unsigned &Delta) {
2064 if (!BaseOp->
isReg())
2072 if (BaseDef && BaseDef->
isPHI()) {
2094 bool SwingSchedulerDAG::canUseLastOffsetValue(
MachineInstr *MI,
2096 unsigned &OffsetPos,
2102 unsigned BasePosLd, OffsetPosLd;
2110 if (!Phi || !Phi->
isPHI())
2119 if (!PrevDef || PrevDef == MI)
2125 unsigned BasePos1 = 0, OffsetPos1 = 0;
2141 BasePos = BasePosLd;
2142 OffsetPos = OffsetPosLd;
2144 Offset = StoreOffset;
2152 SUnit *SU = getSUnit(MI);
2154 InstrChanges.
find(SU);
2155 if (It != InstrChanges.
end()) {
2156 std::pair<unsigned, int64_t> RegAndOffset = It->second;
2157 unsigned BasePos, OffsetPos;
2166 if (BaseStageNum < DefStageNum) {
2168 int OffsetDiff = DefStageNum - BaseStageNum;
2169 if (DefCycleNum < BaseCycleNum) {
2178 MISUnitMap[NewMI] = SU;
2190 while (Def->
isPHI()) {
2191 if (!Visited.
insert(Def).second)
2221 assert(SI !=
nullptr && DI !=
nullptr &&
"Expecting SUnit with an MI.");
2233 unsigned DeltaS, DeltaD;
2238 int64_t OffsetS, OffsetD;
2250 if (!Def || !Def->
isPHI())
2252 unsigned InitVal = 0;
2253 unsigned LoopVal = 0;
2269 if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
2272 return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
2275 void SwingSchedulerDAG::postprocessDAG() {
2276 for (
auto &M : Mutations)
2286 bool forward =
true;
2288 dbgs() <<
"Trying to insert node between " << StartCycle <<
" and " 2289 << EndCycle <<
" II: " << II <<
"\n";
2291 if (StartCycle > EndCycle)
2295 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2296 for (
int curCycle = StartCycle; curCycle != termCycle;
2297 forward ? ++curCycle : --curCycle) {
2301 ProcItinResources.clearResources();
2302 for (
int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
2303 checkCycle <= LastCycle; checkCycle += II) {
2304 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
2306 for (std::deque<SUnit *>::iterator
I = cycleInstrs.begin(),
2307 E = cycleInstrs.end();
2309 if (
ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
2311 assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
2312 "These instructions have already been scheduled.");
2313 ProcItinResources.reserveResources(*(*I)->getInstr());
2317 ProcItinResources.canReserveResources(*SU->
getInstr())) {
2319 dbgs() <<
"\tinsert at cycle " << curCycle <<
" ";
2323 ScheduledInstrs[curCycle].push_back(SU);
2324 InstrToCycle.insert(std::make_pair(SU, curCycle));
2325 if (curCycle > LastCycle)
2326 LastCycle = curCycle;
2327 if (curCycle < FirstCycle)
2328 FirstCycle = curCycle;
2332 dbgs() <<
"\tfailed to insert at cycle " << curCycle <<
" ";
2344 int EarlyCycle = INT_MAX;
2345 while (!Worklist.
empty()) {
2348 if (Visited.
count(PrevSU))
2350 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2351 if (it == InstrToCycle.end())
2353 EarlyCycle = std::min(EarlyCycle, it->second);
2354 for (
const auto &PI : PrevSU->
Preds)
2367 int LateCycle = INT_MIN;
2368 while (!Worklist.
empty()) {
2371 if (Visited.
count(SuccSU))
2373 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2374 if (it == InstrToCycle.end())
2376 LateCycle =
std::max(LateCycle, it->second);
2377 for (
const auto &
SI : SuccSU->
Succs)
2389 for (
auto &
P : SU->
Preds)
2390 if (DAG->
isBackedge(SU,
P) &&
P.getSUnit()->getInstr()->isPHI())
2391 for (
auto &S :
P.getSUnit()->Succs)
2392 if (S.getKind() ==
SDep::Data && S.getSUnit()->getInstr()->isPHI())
2393 return P.getSUnit();
2400 int *MinEnd,
int *MaxStart,
int II,
2405 for (
int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2408 for (
SUnit *
I : getInstructions(cycle)) {
2411 for (
unsigned i = 0,
e = (
unsigned)SU->
Preds.size(); i !=
e; ++i) {
2417 *MaxEarlyStart =
std::max(*MaxEarlyStart, EarlyStart);
2419 int End = earliestCycleInChain(Dep) + (II - 1);
2420 *MinEnd = std::min(*MinEnd, End);
2425 *MinLateStart = std::min(*MinLateStart, LateStart);
2433 *MinLateStart = std::min(*MinLateStart, cycle);
2435 for (
unsigned i = 0,
e = (
unsigned)SU->
Succs.size(); i !=
e; ++i) {
2436 if (SU->
Succs[i].getSUnit() ==
I) {
2441 *MinLateStart = std::min(*MinLateStart, LateStart);
2443 int Start = latestCycleInChain(Dep) + 1 - II;
2444 *MaxStart =
std::max(*MaxStart, Start);
2449 *MaxEarlyStart =
std::max(*MaxEarlyStart, EarlyStart);
2461 std::deque<SUnit *> &Insts) {
2463 bool OrderBeforeUse =
false;
2464 bool OrderAfterDef =
false;
2465 bool OrderBeforeDef =
false;
2466 unsigned MoveDef = 0;
2467 unsigned MoveUse = 0;
2468 int StageInst1 = stageScheduled(SU);
2471 for (std::deque<SUnit *>::iterator
I = Insts.begin(),
E = Insts.end();
I !=
E;
2479 unsigned BasePos, OffsetPos;
2480 if (
ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2485 std::tie(Reads, Writes) =
2486 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
2487 if (MO.
isDef() && Reads && stageScheduled(*
I) <= StageInst1) {
2488 OrderBeforeUse =
true;
2491 }
else if (MO.
isDef() && Reads && stageScheduled(*
I) > StageInst1) {
2493 OrderAfterDef =
true;
2495 }
else if (MO.
isUse() && Writes && stageScheduled(*
I) == StageInst1) {
2496 if (cycleScheduled(*
I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
2497 OrderBeforeUse =
true;
2501 OrderAfterDef =
true;
2504 }
else if (MO.
isUse() && Writes && stageScheduled(*
I) > StageInst1) {
2505 OrderBeforeUse =
true;
2509 OrderAfterDef =
true;
2512 }
else if (MO.
isUse() && Writes && stageScheduled(*
I) < StageInst1) {
2514 OrderBeforeUse =
true;
2517 }
else if (MO.
isUse() && stageScheduled(*
I) == StageInst1 &&
2518 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
2520 OrderBeforeDef =
true;
2527 for (
auto &S : SU->
Succs) {
2528 if (S.getSUnit() != *
I)
2530 if (S.getKind() ==
SDep::Order && stageScheduled(*
I) == StageInst1) {
2531 OrderBeforeUse =
true;
2538 else if (S.getKind() ==
SDep::Anti && stageScheduled(*
I) == StageInst1) {
2539 OrderBeforeUse =
true;
2540 if ((MoveUse == 0) || (Pos < MoveUse))
2544 for (
auto &
P : SU->
Preds) {
2545 if (
P.getSUnit() != *
I)
2547 if (
P.getKind() ==
SDep::Order && stageScheduled(*
I) == StageInst1) {
2548 OrderAfterDef =
true;
2555 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
2556 OrderBeforeUse =
false;
2561 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
2565 if (OrderBeforeUse && OrderAfterDef) {
2566 SUnit *UseSU = Insts.at(MoveUse);
2567 SUnit *DefSU = Insts.at(MoveDef);
2568 if (MoveUse > MoveDef) {
2569 Insts.erase(Insts.begin() + MoveUse);
2570 Insts.erase(Insts.begin() + MoveDef);
2572 Insts.erase(Insts.begin() + MoveDef);
2573 Insts.erase(Insts.begin() + MoveUse);
2575 orderDependence(SSD, UseSU, Insts);
2576 orderDependence(SSD, SU, Insts);
2577 orderDependence(SSD, DefSU, Insts);
2583 Insts.push_front(SU);
2585 Insts.push_back(SU);
2594 unsigned DefCycle = cycleScheduled(DefSU);
2595 int DefStage = stageScheduled(DefSU);
2597 unsigned InitVal = 0;
2598 unsigned LoopVal = 0;
2603 if (UseSU->getInstr()->isPHI())
2605 unsigned LoopCycle = cycleScheduled(UseSU);
2606 int LoopStage = stageScheduled(UseSU);
2607 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
2626 if (!isLoopCarried(SSD, *Phi))
2633 if (DMO.
getReg() == LoopReg)
2644 for (
int i = 0,
e = SSD->
SUnits.size(); i <
e; ++i) {
2648 int StageDef = stageScheduled(&SU);
2649 assert(StageDef != -1 &&
"Instruction should have been scheduled.");
2651 if (
SI.isAssignedRegDep())
2653 if (stageScheduled(
SI.getSUnit()) != StageDef)
2669 void SwingSchedulerDAG::checkValidNodeOrder(
const NodeSetType &Circuits)
const {
2672 typedef std::pair<SUnit *, unsigned> UnitIndex;
2673 std::vector<UnitIndex> Indices(
NodeOrder.size(), std::make_pair(
nullptr, 0));
2675 for (
unsigned i = 0, s =
NodeOrder.size(); i < s; ++i)
2676 Indices.push_back(std::make_pair(
NodeOrder[i], i));
2678 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
2679 return std::get<0>(i1) < std::get<0>(i2);
2692 for (
unsigned i = 0, s =
NodeOrder.size(); i < s; ++i) {
2696 bool PredBefore =
false;
2697 bool SuccBefore =
false;
2706 unsigned PredIndex = std::get<1>(
2722 unsigned SuccIndex = std::get<1>(
2735 Circuits, [SU](
const NodeSet &Circuit) {
return Circuit.
count(SU); });
2740 NumNodeOrderIssues++;
2744 <<
" are scheduled before node " << SU->
NodeNum 2751 dbgs() <<
"Invalid node order found!\n";
2762 unsigned OverlapReg = 0;
2763 unsigned NewBaseReg = 0;
2764 for (
SUnit *SU : Instrs) {
2774 InstrChanges.
find(SU);
2775 if (It != InstrChanges.
end()) {
2776 unsigned BasePos, OffsetPos;
2785 MISUnitMap[NewMI] = SU;
2795 unsigned TiedUseIdx = 0;
2812 for (
int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2813 for (
int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
2815 std::deque<SUnit *> &cycleInstrs =
2816 ScheduledInstrs[cycle + (stage * InitiationInterval)];
2817 for (std::deque<SUnit *>::reverse_iterator
I = cycleInstrs.rbegin(),
2818 E = cycleInstrs.rend();
2820 ScheduledInstrs[cycle].push_front(*
I);
2826 for (
int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
2827 ScheduledInstrs.erase(cycle);
2831 for (
int i = 0,
e = SSD->
SUnits.size(); i !=
e; ++i) {
2838 for (
int Cycle = getFirstCycle(),
E = getFinalCycle(); Cycle <=
E; ++Cycle) {
2839 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
2840 std::deque<SUnit *> newOrderPhi;
2841 for (
unsigned i = 0,
e = cycleInstrs.size(); i <
e; ++i) {
2842 SUnit *SU = cycleInstrs[i];
2844 newOrderPhi.push_back(SU);
2846 std::deque<SUnit *> newOrderI;
2847 for (
unsigned i = 0, e = cycleInstrs.size(); i <
e; ++i) {
2848 SUnit *SU = cycleInstrs[i];
2850 orderDependence(SSD, SU, newOrderI);
2853 cycleInstrs.swap(newOrderPhi);
2854 cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
2862 os <<
"Num nodes " <<
size() <<
" rec " << RecMII <<
" mov " << MaxMOV
2863 <<
" depth " <<
MaxDepth <<
" col " << Colocate <<
"\n";
2864 for (
const auto &
I : Nodes)
2865 os <<
" SU(" <<
I->NodeNum <<
") " << *(
I->getInstr());
2869 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2873 for (
int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
2876 for (
SUnit *CI : cycleInstrs->second) {
2877 os <<
"cycle " << cycle <<
" (" << stageScheduled(CI) <<
") ";
2878 os <<
"(" << CI->
NodeNum <<
") ";
2893 unsigned ProcResourceID = 0;
2898 "Too many kinds of resources, unsupported");
2906 Masks[
I] = 1ULL << ProcResourceID;
2914 Masks[
I] = 1ULL << ProcResourceID;
2915 for (
unsigned U = 0; U < Desc.
NumUnits; ++U)
2921 dbgs() <<
"ProcResourceDesc:\n";
2924 dbgs() <<
format(
" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
2925 ProcResource->
Name,
I, Masks[
I],
2928 dbgs() <<
" -----------------\n";
2937 dbgs() <<
"canReserveResources:\n";
2940 return DFAResources->canReserveResources(MID);
2946 dbgs() <<
"No valid Schedule Class Desc for schedClass!\n";
2954 for (; I !=
E; ++
I) {
2959 unsigned NumUnits = ProcResource->
NumUnits;
2962 dbgs() <<
format(
" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
2977 dbgs() <<
"reserveResources:\n";
2980 return DFAResources->reserveResources(MID);
2986 dbgs() <<
"No valid Schedule Class Desc for schedClass!\n";
2992 make_range(STI->getWriteProcResBegin(SCDesc),
2993 STI->getWriteProcResEnd(SCDesc))) {
2996 ++ProcResourceCount[PRE.ProcResourceIdx];
3000 SM.getProcResource(PRE.ProcResourceIdx);
3001 dbgs() <<
format(
" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
3002 ProcResource->
Name, PRE.ProcResourceIdx,
3003 ProcResourceCount[PRE.ProcResourceIdx],
3004 ProcResource->
NumUnits, PRE.Cycles);
3010 dbgs() <<
"reserveResources: done!\n\n";
3015 return canReserveResources(&MI.
getDesc());
3019 return reserveResources(&MI.
getDesc());
3024 return DFAResources->clearResources();
3025 std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
Pass interface - Implemented by all 'passes'.
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
virtual std::unique_ptr< PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const
Analyze loop L, which must be a single-basic-block loop, and if the conditions can be understood enou...
std::vector< int >::const_reverse_iterator const_reverse_iterator
A parsed version of the target data layout string in and methods for querying it. ...
static cl::opt< bool > SwpIgnoreRecMII("pipeliner-ignore-recmii", cl::ReallyHidden, cl::init(false), cl::ZeroOrMore, cl::desc("Ignore RecMII"))
virtual void finishBlock()
Cleans up after scheduling in the given block.
mop_iterator operands_end()
RegisterClassInfo RegClassInfo
A common definition of LaneBitmask for use in TableGen and CodeGen.
MachineInstr * LoopInductionVar
static bool pred_L(SetVector< SUnit *> &NodeOrder, SmallSetVector< SUnit *, 8 > &Preds, const NodeSet *S=nullptr)
Compute the Pred_L(O) set, as defined in the paper.
static cl::opt< bool > SwpPruneDeps("pipeliner-prune-deps", cl::desc("Prune dependences between unrelated Phi nodes."), cl::Hidden, cl::init(true))
A command line option to disable the pruning of chain dependences due to an unrelated Phi...
static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker, NodeSet &NS)
Compute the live-out registers for the instructions in a node-set.
bool isCall(QueryType Type=AnyInBundle) const
instr_iterator instr_end()
MachineBasicBlock * getMBB() const
unsigned NumPreds
of SDep::Data preds.
unsigned getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
bool isAllocatable(unsigned PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
This class represents lattice values for constants.
A reimplementation of ModuloScheduleExpander.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
const InstrStage * beginStage(unsigned ItinClassIndx) const
Return the first stage of the itinerary.
The ModuloScheduleExpander takes a ModuloSchedule and expands it in-place, rewriting the old loop and...
size_type size() const
Determine the number of elements in the SetVector.
virtual bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const
Sometimes, it is possible for the target to tell, even without aliasing information, that two MIs access different memory addresses.
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static constexpr LocationSize unknown()
Represents a schedule for a single-block loop.
static cl::opt< bool > ExperimentalCodeGen("pipeliner-experimental-cg", cl::Hidden, cl::init(false), cl::desc("Use the experimental peeling code generator for software pipelining"))
cl::opt< bool > SwpEnableCopyToPhi
void push_back(const T &Elt)
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Describe properties that are true of each instruction in the target description file.
bool isValidSchedule(SwingSchedulerDAG *SSD)
virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const
If the instruction is an increment of a constant value, return the amount.
unsigned getSubReg() const
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
const MCProcResourceDesc * getProcResource(unsigned ProcResourceIdx) const
The two locations do not alias at all.
static cl::opt< bool > EnableSWPOptSize("enable-pipeliner-opt-size", cl::desc("Enable SWP at Os."), cl::Hidden, cl::init(false))
A command line option to enable SWP at -Os.
static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop, unsigned &InitVal, unsigned &LoopVal)
Return the register values for the operands of a Phi instruction.
bool isRegSequence() const
This class implements a map that also provides access to all stored values in a deterministic order...
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
Expander that simply annotates each scheduled instruction with a post-instr symbol that can be consum...
void removePred(const SDep &D)
Removes the specified edge as a pred of the current node if it exists.
const MDOperand & getOperand(unsigned I) const
block Block Frequency true
bool isPseudo() const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction...
static void getUnderlyingObjects(const MachineInstr *MI, SmallVectorImpl< const Value *> &Objs, const DataLayout &DL)
Return the underlying objects for the memory references of an instruction.
unsigned getReg() const
Returns the register associated with this edge.
const MCSchedClassDesc * getSchedClassDesc(unsigned SchedClassIdx) const
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...
Kind
These are the different kinds of scheduling dependencies.
iterator_range< mop_iterator > operands()
iterator end()
Get an iterator to the end of the SetVector.
SmallVectorImpl< SDep >::iterator succ_iterator
SUnit * getNode(unsigned i) const
SmallVector< SDep, 4 > Preds
All sunit predecessors.
bool canReserveResources(const MCInstrDesc *MID) const
Check if the resources occupied by a MCInstrDesc are available in the current state.
virtual void adjustSchedDependency(SUnit *def, SUnit *use, SDep &dep) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
A register anti-dependence (aka WAR).
void recede(SmallVectorImpl< RegisterMaskPair > *LiveUses=nullptr)
Recede across the previous instruction.
int compareRecMII(NodeSet &RHS)
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
#define INITIALIZE_PASS_DEPENDENCY(depName)
A description of a memory reference used in the backend.
SmallVectorImpl< SDep >::iterator pred_iterator
MachineBasicBlock * getTopBlock()
Return the "top" block in the loop, which is the first block in the linear layout, ignoring any parts of the loop not contiguous with the part that contains the header.
static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA)
Return true if the instruction causes a chain between memory references before and after it...
void closeBottom()
Set the boundary for the bottom of the region and summarize live outs.
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
void setInstr(MachineInstr *MI)
Assigns the instruction for the SUnit.
SmallVectorImpl< SDep >::const_iterator const_pred_iterator
Modulo Software Pipelining
Regular data dependence (aka true-dependence).
void reserveResources(const MCInstrDesc *MID)
Reserve the resources occupied by a MCInstrDesc and change the current state to reflect that change...
void apply(Opt *O, const Mod &M, const Mods &... Ms)
This file contains the simple types necessary to represent the attributes associated with functions a...
bool hasPhysRegDefs
Has physreg defs that are being used.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart, int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG)
Compute the scheduling start slot for the instruction.
unsigned cycleScheduled(SUnit *SU) const
Return the cycle for a scheduled instruction.
static constexpr LaneBitmask getNone()
static bool ignoreDependence(const SDep &D, bool isPred)
Return true for DAG nodes that we ignore when computing the cost functions.
bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
BlockT * getHeader() const
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
defusechain_iterator - This class provides iterator support for machine operands in the function that...
A register output-dependence (aka WAW).
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
bool insert(SUnit *SU, int StartCycle, int EndCycle, int II)
Try to schedule the node at the specified StartCycle and continue until the node is schedule or the E...
bool insert(const value_type &X)
Insert a new element into the SetVector.
void expand()
Performs the actual expansion.
bool mayRaiseFPException() const
Return true if this instruction could possibly raise a floating-point exception.
const MCWriteProcResEntry * getWriteProcResEnd(const MCSchedClassDesc *SC) const
static void swapAntiDependences(std::vector< SUnit > &SUnits)
Swap all the anti dependences in the DAG.
unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep)
The distance function, which indicates that operation V of iteration I depends on operations U of ite...
static bool succ_L(SetVector< SUnit *> &NodeOrder, SmallSetVector< SUnit *, 8 > &Succs, const NodeSet *S=nullptr)
Compute the Succ_L(O) set, as defined in the paper.
static bool isSubset(S1Ty &Set1, S2Ty &Set2)
Return true if Set1 is a subset of Set2.
iterator begin()
Get an iterator to the beginning of the SetVector.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Itinerary data supplied by a subtarget to be used by a target.
static cl::opt< bool > EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::desc("Enable Software Pipelining"))
A command line option to turn software pipelining on or off.
virtual bool getBaseAndOffsetPosition(const MachineInstr &MI, unsigned &BasePos, unsigned &OffsetPos) const
Return true if the instruction contains a base register and offset.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
void setReg(Register Reg)
Change the register this operand corresponds to.
unsigned count(SUnit *SU) const
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator find(const KeyT &Key)
void schedule() override
We override the schedule function in ScheduleDAGInstrs to implement the scheduling part of the Swing ...
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
virtual const InstrItineraryData * getInstrItineraryData() const
getInstrItineraryData - Returns instruction itinerary data for the target or specific subtarget...
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
AliasResult
The possible results of an alias query.
const Value * getValue() const
Return the base address of the memory access.
iterator find(const_arg_type_t< KeyT > Val)
bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
StringRef getString() const
void initProcResourceVectors(const MCSchedModel &SM, SmallVectorImpl< uint64_t > &Masks)
void addLiveRegs(ArrayRef< RegisterMaskPair > Regs)
Force liveness of virtual registers or physical register units.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
unsigned getSchedClass() const
Return the scheduling class for this instruction.
void finishBlock() override
Clean up after the software pipeliner runs.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
initializer< Ty > init(const Ty &Val)
bool isLoopCarriedDep(SUnit *Source, const SDep &Dep, bool isSucc=true)
Return true for an order or output dependence that is loop carried potentially.
int getFirstCycle() const
Return the first cycle in the completed schedule.
void print(raw_ostream &os) const
Print the schedule information to the given output.
void GetUnderlyingObjects(const Value *V, SmallVectorImpl< const Value *> &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
The main class in the implementation of the target independent software pipeliner pass...
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for c...
unsigned const MachineRegisterInfo * MRI
void clearResources()
Reset the state.
RegisterPressure computed within a region of instructions delimited by TopIdx and BottomIdx...
LLVM Basic Block Representation.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const unsigned * SubUnitsIdxBegin
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
void finalizeSchedule(SwingSchedulerDAG *SSD)
After the schedule has been formed, call this function to combine the instructions from the different...
MachineInstrBuilder & UseMI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_NODISCARD bool empty() const
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE and DBG_LABEL instructions...
static int64_t computeDelta(SectionEntry *A, SectionEntry *B)
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Summarize the scheduling resources required for an instruction of a particular scheduling class...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static bool isIntersect(SmallSetVector< SUnit *, 8 > &Set1, const NodeSet &Set2, SmallSetVector< SUnit *, 8 > &Result)
Return true if Set1 contains elements in Set2.
int stageScheduled(SUnit *SU) const
Return the stage for a scheduled instruction.
static Type * getVoidTy(LLVMContext &C)
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
unsigned getInstrBaseReg(SUnit *SU)
Return the new base register that was stored away for the changed instruction.
Track the current register pressure at some position in the instruction stream, and remember the high...
void setImm(int64_t immVal)
void dump() const
Utility function used for debugging to print the schedule.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void cleanup()
Performs final cleanup after expansion.
const TargetInstrInfo * TII
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
void print(raw_ostream &os) const
int latestCycleInChain(const SDep &Dep)
Return the cycle of the latest scheduled instruction in the dependence chain.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
void fixupRegisterOverlaps(std::deque< SUnit *> &Instrs)
Attempt to fix the degenerate cases when the instruction serialization causes the register lifetimes ...
LLVM_DUMP_METHOD void dump() const
void DeleteMachineInstr(MachineInstr *MI)
DeleteMachineInstr - Delete the given MachineInstr.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Any other ordering dependency.
INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE, "Modulo Software Pipelining", false, false) INITIALIZE_PASS_END(MachinePipeliner
const InstrItineraryData * InstrItins
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.
static cl::opt< bool > SwpShowResMask("pipeliner-show-mask", cl::Hidden, cl::init(false))
void sort(IteratorTy Start, IteratorTy End)
An unknown scheduling barrier.
Representation for a specific memory location.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.
SetVector< SUnit * >::const_iterator iterator
virtual bool getMemOperandWithOffset(const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset, const TargetRegisterInfo *TRI) const
Get the base operand and byte offset of an instruction that reads/writes memory.
typename vector_type::const_iterator iterator
A SetVector that performs no allocations if smaller than a certain size.
bool hasInstrSchedModel() const
Does this machine model include instruction-level scheduling.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
unsigned countPopulation(T Value)
Count the number of set bits in a value.
static cl::opt< bool > SwpDebugResource("pipeliner-dbg-res", cl::Hidden, cl::init(false))
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.
static cl::opt< int > SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1))
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...
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
This class builds the dependence graph for the instructions in a loop, and attempts to schedule the i...
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
Create a new MachineInstr which is a copy of Orig, identical in all ways except the instruction has n...
bool isDereferenceableInvariantLoad(AAResults *AA) const
Return true if this load instruction never traps and points to a memory location whose value doesn't ...
static cl::opt< int > SwpMaxStages("pipeliner-max-stages", cl::desc("Maximum stages allowed in the generated scheduled."), cl::Hidden, cl::init(3))
A command line argument to limit the number of stages in the pipeline.
MachineOperand class - Representation of each machine instruction operand.
static cl::opt< int > SwpMaxMii("pipeliner-max-mii", cl::desc("Size limit for the MII."), cl::Hidden, cl::init(27))
A command line argument to limit minimum initial interval for pipelining.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static unsigned getDepth(const SmallVectorImpl< const MachineBasicBlock *> &Stack, const MachineBasicBlock *MBB)
Define a kind of processor resource that will be modeled by the scheduler.
MachineInstrBuilder MachineInstrBuilder & DefMI
char & MachinePipelinerID
This pass performs software pipelining on machine instructions.
void setRecMII(unsigned mii)
LLVM_NODISCARD T pop_back_val()
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
const Function & getFunction() const
Return the LLVM function that this machine code represents.
MachineInstr * LoopCompare
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
int earliestCycleInChain(const SDep &Dep)
Return the cycle of the earliest scheduled instruction in the dependence chain.
static bool isSuccOrder(SUnit *SUa, SUnit *SUb)
Return true if SUb can be reached from SUa following the chain edges.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
std::vector< int >::const_iterator const_iterator
void clear()
Completely clear the SetVector.
bool IsReachable(const SUnit *SU, const SUnit *TargetSU)
Checks if SU is reachable from TargetSU.
static SUnit * multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG)
If an instruction has a use that spans multiple iterations, then return true.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
typename SuperClass::iterator iterator
This class represents the scheduled code.
SmallVectorImpl< SDep >::const_iterator const_succ_iterator
bool isEmpty() const
Returns true if there are no itineraries.
void setLatency(unsigned Lat)
Sets the latency for this edge.
const MachineBasicBlock * getParent() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
TargetSubtargetInfo - Generic base class for all target subtargets.
void setColocate(unsigned c)
std::set< NodeId > NodeSet
A ScheduleDAG for scheduling lists of MachineInstr.
Representation of each machine instruction.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
static cl::opt< bool > EmitTestAnnotations("pipeliner-annotate-for-testing", cl::Hidden, cl::init(false), cl::desc("Instead of emitting the pipelined code, annotate instructions " "with the generated schedule for feeding into the " "-modulo-schedule-test pass"))
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
These values represent a non-pipelined step in the execution of an instruction.
Represents a single loop in the control flow graph.
int getFinalCycle() const
Return the last cycle in the finalized schedule.
void orderDependence(SwingSchedulerDAG *SSD, SUnit *SU, std::deque< SUnit *> &Insts)
Order the instructions within a cycle so that the definitions occur before the uses.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
This file provides utility analysis objects describing memory locations.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
const InstrStage * endStage(unsigned ItinClassIndx) const
Return the last+1 stage of the itinerary.
bool empty() const
Determine if the SetVector is empty or not.
void setSubReg(unsigned subReg)
bool isZeroCost(unsigned Opcode) const
Return true for pseudo instructions that don't consume any machine resources in their current form...
Generic base class for all target subtargets.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
void getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction bottom-up.
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi)
Return true if the scheduled Phi has a loop carried operand.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Kind getKind() const
Returns an enum value representing the kind of the dependence.
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
const MCWriteProcResEntry * getWriteProcResBegin(const MCSchedClassDesc *SC) const
Return an iterator at the first process resource consumed by the given scheduling class...
LLVM_NODISCARD bool empty() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void init(const MachineFunction *mf, const RegisterClassInfo *rci, const LiveIntervals *lis, const MachineBasicBlock *mbb, MachineBasicBlock::const_iterator pos, bool TrackLaneMasks, bool TrackUntiedDefs)
Setup the RegPressureTracker.
void setInitiationInterval(int ii)
Set the initiation interval for this schedule.
unsigned NodeNum
Entry # of node in the node vector.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Store the effects of a change in pressure on things that MI scheduler cares about.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
void stable_sort(R &&Range)
bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Def, MachineOperand &MO)
Return true if the instruction is a definition that is loop carried and defines the use on the next i...
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
LLVM Value Representation.
mop_iterator operands_begin()
A vector that has set insertion semantics.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
SmallVector< SDep, 4 > Succs
All sunit successors.
Arbitrary strong DAG edge (no real dependence).
This class implements an extremely fast bulk output stream that can only output to a stream...
static cl::opt< bool > SwpPruneLoopCarried("pipeliner-prune-loop-carried", cl::desc("Prune loop carried order dependences."), cl::Hidden, cl::init(true))
A command line option to disable the pruning of loop carried order dependences.
void AddPred(SUnit *Y, SUnit *X)
Updates the topological ordering to accommodate an edge to be added from SUnit X to SUnit Y...
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
SmallVector< MachineOperand, 4 > BrCond
virtual bool isPostIncrement(const MachineInstr &MI) const
Return true for post-incremented instructions.
void setPos(MachineBasicBlock::const_iterator Pos)
Register getReg() const
getReg - Returns the register number.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
static bool computePath(SUnit *Cur, SetVector< SUnit *> &Path, SetVector< SUnit *> &DestNodes, SetVector< SUnit *> &Exclude, SmallPtrSet< SUnit *, 8 > &Visited)
Return true if there is a path from the specified node to any of the nodes in DestNodes.
std::vector< SUnit > SUnits
The scheduling units.
unsigned getNumOperands() const
Return number of MDNode operands.
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
const MachineOperand & getOperand(unsigned i) const
unsigned getMaxStageCount()
Return the maximum stage count needed for this schedule.
Machine model for scheduling, bundling, and heuristics.
std::deque< SUnit * > & getInstructions(int cycle)
Return the instructions that are scheduled at the specified cycle.
static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB)
Return the Phi register value that comes the loop block.
void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule)
Apply changes to the instruction if needed.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
Scheduling unit. This is a node in the scheduling DAG.
Wrapper class representing virtual and physical registers.
unsigned getNumProcResourceKinds() const
bool isBackedge(SUnit *Source, const SDep &Dep)
Return true if the dependence is a back-edge in the data dependence graph.
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
bool isPred(const SUnit *N) const
Tests if node N is a predecessor of this node.