72 #define DEBUG_TYPE "machine-scheduler"
77 cl::desc(
"Force top-down list scheduling"));
79 cl::desc(
"Force bottom-up list scheduling"));
82 cl::desc(
"Print critical path length to stdout"));
88 cl::desc(
"Pop up a window to show MISched dags after they are processed"));
93 cl::desc(
"Hide nodes with more predecessor/successor than cutoff"));
99 cl::desc(
"Only schedule this function"));
101 cl::desc(
"Only schedule this MBB#"));
118 cl::desc(
"Enable memop clustering."),
122 cl::desc(
"Verify machine instrs before and after machine scheduling"));
128 void MachineSchedStrategy::anchor() {}
130 void ScheduleDAGMutation::anchor() {}
159 class MachineScheduler :
public MachineSchedulerBase {
174 class PostMachineScheduler :
public MachineSchedulerBase {
176 PostMachineScheduler();
195 "Machine Instruction Scheduler",
false,
false)
203 MachineScheduler::MachineScheduler()
204 : MachineSchedulerBase(
ID) {
208 void MachineScheduler::getAnalysisUsage(
AnalysisUsage &AU)
const {
226 "PostRA Machine Instruction Scheduler",
false,
false)
228 PostMachineScheduler::PostMachineScheduler()
229 : MachineSchedulerBase(
ID) {
233 void PostMachineScheduler::getAnalysisUsage(
AnalysisUsage &AU)
const {
254 cl::desc(
"Machine instruction scheduler to use"));
262 cl::desc(
"Enable the machine instruction scheduling pass."),
cl::init(
true),
266 "enable-post-misched",
267 cl::desc(
"Enable the post-ra machine instruction scheduling pass."),
274 assert(I != Beg &&
"reached the top of the region, cannot decrement");
276 if (!I->isDebugValue())
295 for(; I !=
End; ++
I) {
296 if (!I->isDebugValue())
369 MLI = &getAnalysis<MachineLoopInfo>();
370 MDT = &getAnalysis<MachineDominatorTree>();
371 PassConfig = &getAnalysis<TargetPassConfig>();
372 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
374 LIS = &getAnalysis<LiveIntervals>();
378 MF->verify(
this,
"Before machine scheduling.");
380 RegClassInfo->runOnMachineFunction(*MF);
384 std::unique_ptr<ScheduleDAGInstrs>
Scheduler(createMachineScheduler());
385 scheduleRegions(*Scheduler,
false);
389 MF->verify(
this,
"After machine scheduling.");
401 DEBUG(
dbgs() <<
"Subtarget disables post-MI-sched.\n");
408 PassConfig = &getAnalysis<TargetPassConfig>();
411 MF->
verify(
this,
"Before post machine scheduling.");
415 std::unique_ptr<ScheduleDAGInstrs>
Scheduler(createPostMachineScheduler());
416 scheduleRegions(*Scheduler,
true);
419 MF->verify(
this,
"After post machine scheduling.");
450 MBB != MBBEnd; ++MBB) {
476 RegionEnd != MBB->begin(); RegionEnd = Scheduler.
begin()) {
479 if (RegionEnd != MBB->end() ||
486 unsigned NumRegionInstrs = 0;
488 for (; I != MBB->begin(); --
I) {
497 Scheduler.
enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
500 if (I == RegionEnd || I == std::prev(RegionEnd)) {
506 DEBUG(
dbgs() <<
"********** MI Scheduling **********\n");
508 <<
":BB#" << MBB->getNumber() <<
" " << MBB->getName()
509 <<
"\n From: " << *I <<
" To: ";
510 if (RegionEnd != MBB->end())
dbgs() << *RegionEnd;
511 else dbgs() <<
"End";
512 dbgs() <<
" RegionInstrs: " << NumRegionInstrs <<
'\n');
514 errs() << MF->getName();
515 errs() <<
":BB# " << MBB->getNumber();
516 errs() <<
" " << MBB->getName() <<
" \n";
528 RegionEnd = Scheduler.
begin();
544 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
546 dbgs() <<
"Queue " << Name <<
": ";
547 for (
const SUnit *SU : Queue)
548 dbgs() << SU->NodeNum <<
" ";
594 dbgs() <<
"*** Scheduling failed! ***\n";
596 dbgs() <<
" has been released too many times!\n";
631 dbgs() <<
"*** Scheduling failed! ***\n";
633 dbgs() <<
" has been released too many times!\n";
660 unsigned regioninstrs)
664 SchedImpl->initPolicy(begin, end, regioninstrs);
703 DEBUG(
dbgs() <<
"ScheduleDAGMI::schedule starting\n");
733 bool IsTopNode =
false;
735 DEBUG(
dbgs() <<
"** ScheduleDAGMI::schedule picking next node\n");
776 unsigned BBNum =
begin()->getParent()->getNumber();
777 dbgs() <<
"*** Final schedule for BB#" << BBNum <<
" ***\n";
793 assert(!SU.isBoundaryNode() &&
"Boundary node should not be in SUnits");
796 SU.biasCriticalPath();
799 if (!SU.NumPredsLeft)
802 if (!SU.NumSuccsLeft)
818 for (
SUnit *SU : TopRoots)
857 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
859 std::pair<MachineInstr *, MachineInstr *>
P = *std::prev(DI);
872 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
878 dbgs() <<
"Missing SUnit\n";
902 unsigned Reg = MO.getReg();
908 bool FoundDef =
false;
910 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
937 unsigned regioninstrs)
951 "ShouldTrackLaneMasks requires ShouldTrackPressure");
1001 dbgs() <<
"Top Pressure:\n";
1003 dbgs() <<
"Bottom Pressure:\n";
1014 for (
unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
1016 if (RegionPressure[i] > Limit) {
1018 <<
" Limit " << Limit
1019 <<
" Actual " << RegionPressure[i] <<
"\n");
1026 RCPS.getPSet()) <<
" ";
1032 const std::vector<unsigned> &NewMaxPressure) {
1038 unsigned ID = PC.getPSet();
1047 if (NewMaxPressure[ID] >= Limit - 2) {
1049 << NewMaxPressure[
ID]
1050 << ((NewMaxPressure[
ID] > Limit) ?
" > " :
" <= ") << Limit
1061 unsigned Reg =
P.RegUnit;
1071 bool Decrement =
P.LaneMask.any();
1075 SUnit &SU = *V2SU.SU;
1082 dbgs() <<
" UpdateRegP: SU(" << SU.
NodeNum <<
") "
1107 assert(VNI &&
"No live value at use.");
1110 SUnit *SU = V2SU.SU;
1120 dbgs() <<
" UpdateRegP: SU(" << SU->
NodeNum <<
") "
1143 DEBUG(
dbgs() <<
"ScheduleDAGMILive::schedule starting\n");
1164 dbgs() <<
" Pressure Diff : ";
1167 dbgs() <<
" Single Issue : ";
1183 bool IsTopNode =
false;
1185 DEBUG(
dbgs() <<
"** ScheduleDAGMILive::schedule picking next node\n");
1214 unsigned BBNum =
begin()->getParent()->getNumber();
1215 dbgs() <<
"*** Final schedule for BB#" << BBNum <<
" ***\n";
1286 unsigned MaxCyclicLatency = 0;
1289 unsigned Reg =
P.RegUnit;
1302 unsigned LiveOutHeight = DefSU->
getHeight();
1307 SUnit *SU = V2SU.SU;
1319 unsigned CyclicLatency = 0;
1321 CyclicLatency = LiveOutDepth - SU->
getDepth();
1324 if (LiveInHeight > LiveOutHeight) {
1325 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1326 CyclicLatency = LiveInHeight - LiveOutHeight;
1331 << SU->
NodeNum <<
") = " << CyclicLatency <<
"c\n");
1332 if (CyclicLatency > MaxCyclicLatency)
1333 MaxCyclicLatency = CyclicLatency;
1336 DEBUG(
dbgs() <<
"Cyclic Critical Path: " << MaxCyclicLatency <<
"c\n");
1337 return MaxCyclicLatency;
1381 dbgs() <<
"Top Pressure:\n";
1391 if (&*priorII == MI)
1418 dbgs() <<
"Bottom Pressure:\n";
1442 MemOpInfo(
SUnit *su,
unsigned reg, int64_t ofs)
1443 : SU(su), BaseReg(reg),
Offset(ofs) {}
1445 bool operator<(
const MemOpInfo&RHS)
const {
1446 return std::tie(BaseReg,
Offset, SU->NodeNum) <
1447 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
1458 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
1466 class StoreClusterMutation :
public BaseMemOpClusterMutation {
1470 : BaseMemOpClusterMutation(tii, tri,
false) {}
1473 class LoadClusterMutation :
public BaseMemOpClusterMutation {
1476 : BaseMemOpClusterMutation(tii, tri,
true) {}
1483 std::unique_ptr<ScheduleDAGMutation>
1490 std::unique_ptr<ScheduleDAGMutation>
1499 void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1502 for (
SUnit *SU : MemOps) {
1506 MemOpRecords.
push_back(MemOpInfo(SU, BaseReg, Offset));
1508 if (MemOpRecords.
size() < 2)
1512 unsigned ClusterLength = 1;
1513 for (
unsigned Idx = 0,
End = MemOpRecords.
size(); Idx < (
End - 1); ++Idx) {
1514 if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
1519 SUnit *SUa = MemOpRecords[Idx].SU;
1520 SUnit *SUb = MemOpRecords[Idx+1].SU;
1556 unsigned ChainPredID = DAG->
SUnits.size();
1565 unsigned NumChains = StoreChainDependents.
size();
1566 std::pair<DenseMap<unsigned, unsigned>::iterator,
bool> Result =
1567 StoreChainIDs.
insert(std::make_pair(ChainPredID, NumChains));
1569 StoreChainDependents.
resize(NumChains + 1);
1570 StoreChainDependents[Result.first->second].
push_back(&SU);
1574 for (
auto &SCD : StoreChainDependents)
1575 clusterNeighboringMemOps(SCD, DAG);
1607 std::unique_ptr<ScheduleDAGMutation>
1610 return llvm::make_unique<CopyConstrain>(
TII, TRI);
1640 unsigned SrcReg = SrcOp.
getReg();
1645 unsigned DstReg = DstOp.
getReg();
1655 unsigned LocalReg = SrcReg;
1656 unsigned GlobalReg = DstReg;
1658 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx)) {
1662 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx))
1673 if (GlobalSegment == GlobalLI->
end())
1680 if (GlobalSegment->contains(LocalLI->
beginIndex()))
1683 if (GlobalSegment == GlobalLI->
end())
1687 if (GlobalSegment != GlobalLI->
begin()) {
1690 GlobalSegment->start)) {
1701 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1702 "Disconnected LRG within the scheduling region.");
1718 for (
const SDep &Succ : LastLocalSU->
Succs) {
1733 for (
const SDep &Pred : GlobalSU->
Preds) {
1736 if (Pred.
getSUnit() == FirstLocalSU)
1745 I = LocalUses.
begin(),
E = LocalUses.
end(); I !=
E; ++
I) {
1746 DEBUG(
dbgs() <<
" Local use SU(" << (*I)->NodeNum <<
") -> SU("
1747 << GlobalSU->
NodeNum <<
")\n");
1751 I = GlobalUses.
begin(),
E = GlobalUses.
end(); I !=
E; ++
I) {
1752 DEBUG(
dbgs() <<
" Global use SU(" << (*I)->NodeNum <<
") -> SU("
1753 << FirstLocalSU->
NodeNum <<
")\n");
1765 if (FirstPos == DAG->
end())
1775 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
1798 CheckPending =
false;
1802 ExpectedLatency = 0;
1803 DependentLatency = 0;
1805 MaxExecutedResCount = 0;
1807 IsResourceLimited =
false;
1808 ReservedCycles.
clear();
1813 MaxObservedStall = 0;
1816 ExecutedResCounts.
resize(1);
1817 assert(!ExecutedResCounts[0] &&
"nonzero count for bad resource");
1833 unsigned PIdx = PI->ProcResourceIdx;
1864 if (ReadyCycle > CurrCycle)
1865 return ReadyCycle - CurrCycle;
1873 unsigned NextUnreserved = ReservedCycles[PIdx];
1879 NextUnreserved += Cycles;
1880 return NextUnreserved;
1913 << (
isTop()?
"begin" :
"end") <<
" group\n");
1923 if (NRCycle > CurrCycle) {
1925 MaxObservedStall =
std::max(PI->Cycles, MaxObservedStall);
1929 <<
"=" << NRCycle <<
"c\n");
1940 SUnit *LateSU =
nullptr;
1941 unsigned RemLatency = 0;
1942 for (
SUnit *SU : ReadySUs) {
1944 if (L > RemLatency) {
1951 << LateSU->
NodeNum <<
") " << RemLatency <<
"c\n");
1970 PIdx != PEnd; ++PIdx) {
1972 if (OtherCount > OtherCritCount) {
1973 OtherCritCount = OtherCount;
1974 OtherCritIdx = PIdx;
1982 return OtherCritCount;
1992 if (ReadyCycle > CurrCycle)
1993 MaxObservedStall =
std::max(ReadyCycle - CurrCycle, MaxObservedStall);
1996 if (ReadyCycle < MinReadyCycle)
1997 MinReadyCycle = ReadyCycle;
2002 if ((!IsBuffered && ReadyCycle > CurrCycle) ||
checkHazard(SU) ||
2013 "MinReadyCycle uninitialized");
2014 if (MinReadyCycle > NextCycle)
2015 NextCycle = MinReadyCycle;
2019 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2022 if ((NextCycle - CurrCycle) > DependentLatency)
2023 DependentLatency = 0;
2025 DependentLatency -= (NextCycle - CurrCycle);
2029 CurrCycle = NextCycle;
2032 for (; CurrCycle != NextCycle; ++CurrCycle) {
2039 CheckPending =
true;
2049 ExecutedResCounts[PIdx] += Count;
2050 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2051 MaxExecutedResCount = ExecutedResCounts[PIdx];
2064 unsigned Count = Factor * Cycles;
2066 <<
" +" << Cycles <<
"x" << Factor <<
"u\n");
2076 ZoneCritResIdx = PIdx;
2077 DEBUG(
dbgs() <<
" *** Critical resource "
2083 if (NextAvailable > CurrCycle) {
2086 << NextAvailable <<
"\n");
2088 return NextAvailable;
2108 "Cannot schedule this instruction's MicroOps in the current cycle.");
2111 DEBUG(
dbgs() <<
" Ready @" << ReadyCycle <<
"c\n");
2113 unsigned NextCycle = CurrCycle;
2116 assert(ReadyCycle <= CurrCycle &&
"Broken PendingQueue");
2119 if (ReadyCycle > NextCycle) {
2120 NextCycle = ReadyCycle;
2121 DEBUG(
dbgs() <<
" *** Stall until: " << ReadyCycle <<
"\n");
2130 NextCycle = ReadyCycle;
2133 RetiredMOps += IncMOps;
2140 if (ZoneCritResIdx) {
2142 unsigned ScaledMOps =
2150 DEBUG(
dbgs() <<
" *** Critical resource NumMicroOps: "
2159 if (RCycle > NextCycle)
2170 unsigned PIdx = PI->ProcResourceIdx;
2173 ReservedCycles[PIdx] =
2177 ReservedCycles[PIdx] = NextCycle;
2183 unsigned &TopLatency =
isTop() ? ExpectedLatency : DependentLatency;
2184 unsigned &BotLatency =
isTop() ? DependentLatency : ExpectedLatency;
2188 <<
" TopLatency SU(" << SU->
NodeNum <<
") " << TopLatency <<
"c\n");
2193 <<
" BotLatency SU(" << SU->
NodeNum <<
") " << BotLatency <<
"c\n");
2196 if (NextCycle > CurrCycle) {
2210 CurrMOps += IncMOps;
2219 << (
isTop() ?
"end" :
"begin") <<
" group\n");
2224 DEBUG(
dbgs() <<
" *** Max MOps " << CurrMOps
2225 <<
" at cycle " << CurrCycle <<
'\n');
2241 for (
unsigned i = 0, e =
Pending.
size(); i != e; ++i) {
2245 if (ReadyCycle < MinReadyCycle)
2246 MinReadyCycle = ReadyCycle;
2248 if (!IsBuffered && ReadyCycle > CurrCycle)
2261 CheckPending =
false;
2309 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2315 if (ZoneCritResIdx) {
2324 <<
" Retired: " << RetiredMOps;
2326 dbgs() <<
"\n Critical: " << ResCount / LFactor <<
"c, "
2327 << ResCount / ResFactor <<
" "
2329 <<
"\n ExpectedLatency: " << ExpectedLatency <<
"c\n"
2330 << (IsResourceLimited ?
" - Resource" :
" - Latency")
2385 unsigned OtherCritIdx = 0;
2386 unsigned OtherCount =
2389 bool OtherResLimited =
false;
2392 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (
int)LFactor;
2397 if (!OtherResLimited) {
2401 <<
" RemainingLatency " << RemLatency <<
" + "
2416 if (OtherResLimited)
2417 dbgs() <<
" RemainingLimit: "
2420 dbgs() <<
" Latency limited both directions.\n");
2425 if (OtherResLimited)
2433 case NoCand:
return "NOCAND ";
2434 case Only1:
return "ONLY1 ";
2438 case Stall:
return "STALL ";
2439 case Cluster:
return "CLUSTER ";
2440 case Weak:
return "WEAK ";
2441 case RegMax:
return "REG-MAX ";
2456 unsigned ResIdx = 0;
2500 dbgs() <<
" " << Latency <<
" cycles ";
2512 if (TryVal < CandVal) {
2516 if (TryVal > CandVal) {
2517 if (Cand.
Reason > Reason)
2528 if (TryVal > CandVal) {
2532 if (TryVal < CandVal) {
2533 if (Cand.
Reason > Reason)
2566 DEBUG(
dbgs() <<
"Pick " << (IsTop ?
"Top " :
"Bot ")
2576 "(PreRA)GenericScheduler needs vreg liveness");
2590 if (!Top.HazardRec) {
2592 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2595 if (!Bot.HazardRec) {
2597 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2600 TopCand.SU =
nullptr;
2601 BotCand.SU =
nullptr;
2607 unsigned NumRegionInstrs) {
2614 RegionPolicy.ShouldTrackPressure =
true;
2620 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2626 RegionPolicy.OnlyBottomUp =
true;
2633 RegionPolicy.ShouldTrackPressure =
false;
2638 "-misched-topdown incompatible with -misched-bottomup");
2641 if (RegionPolicy.OnlyBottomUp)
2642 RegionPolicy.OnlyTopDown =
false;
2646 if (RegionPolicy.OnlyTopDown)
2647 RegionPolicy.OnlyBottomUp =
false;
2653 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2654 dbgs() <<
"GenericScheduler RegionPolicy: "
2655 <<
" ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2656 <<
" OnlyTopDown=" << RegionPolicy.OnlyTopDown
2657 <<
" OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2676 unsigned IterCount =
2682 unsigned InFlightCount =
2684 unsigned BufferLimit =
2692 <<
"c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2696 dbgs() <<
" ACYCLIC LATENCY LIMIT\n");
2703 for (
const SUnit *SU : Bot.Available) {
2714 checkAcyclicLatency();
2733 if (Cand.AtTop != TryCand.
AtTop)
2740 if (TryPSet == CandPSet) {
2754 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2773 unsigned ScheduledOper = isTop ? 1 : 0;
2774 unsigned UnscheduledOper = isTop ? 0 : 1;
2785 return AtBoundary ? -1 : 1;
2795 if (DAG->isTrackingPressure()) {
2800 DAG->getRegionCriticalPSets(),
2801 DAG->getRegPressure().MaxSetPressure);
2806 &DAG->getPressureDiff(Cand.
SU),
2808 DAG->getRegionCriticalPSets(),
2809 DAG->getRegPressure().MaxSetPressure);
2813 DAG->getPressureDiff(Cand.
SU),
2815 DAG->getRegionCriticalPSets(),
2816 DAG->getRegPressure().MaxSetPressure);
2869 bool SameBoundary = Zone !=
nullptr;
2890 const SUnit *CandNextClusterSU =
2892 const SUnit *TryCandNextClusterSU =
2895 Cand.
SU == CandNextClusterSU,
2903 TryCand, Cand,
Weak))
2952 for (
SUnit *SU : Q) {
2955 initCandidate(TryCand, SU, Zone.
isTop(), RPTracker, TempTracker);
2958 tryCandidate(Cand, TryCand, ZoneArg);
2973 if (
SUnit *SU = Bot.pickOnlyChoice()) {
2978 if (
SUnit *SU = Top.pickOnlyChoice()) {
2994 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
2995 BotCand.Policy != BotPolicy) {
2997 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
2998 assert(BotCand.Reason !=
NoCand &&
"failed to find the first candidate");
3005 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3007 "Last pick result should correspond to re-picking right now");
3014 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3015 TopCand.Policy != TopPolicy) {
3017 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3018 assert(TopCand.Reason !=
NoCand &&
"failed to find the first candidate");
3025 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3027 "Last pick result should correspond to re-picking right now");
3033 assert(BotCand.isValid());
3034 assert(TopCand.isValid());
3037 tryCandidate(Cand, TopCand,
nullptr);
3038 if (TopCand.Reason !=
NoCand) {
3039 Cand.setBest(TopCand);
3043 IsTopNode = Cand.AtTop;
3051 assert(Top.Available.empty() && Top.Pending.empty() &&
3052 Bot.Available.empty() && Bot.Pending.empty() &&
"ReadyQ garbage");
3057 if (RegionPolicy.OnlyTopDown) {
3058 SU = Top.pickOnlyChoice();
3061 TopCand.reset(NoPolicy);
3062 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
3063 assert(TopCand.Reason !=
NoCand &&
"failed to find a candidate");
3068 }
else if (RegionPolicy.OnlyBottomUp) {
3069 SU = Bot.pickOnlyChoice();
3072 BotCand.reset(NoPolicy);
3073 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
3074 assert(BotCand.Reason !=
NoCand &&
"failed to find a candidate");
3080 SU = pickNodeBidirectional(IsTopNode);
3085 Top.removeReady(SU);
3087 Bot.removeReady(SU);
3101 for (
SDep &Dep : Deps) {
3104 SUnit *DepSU = Dep.getSUnit();
3105 if (isTop ? DepSU->
Succs.size() > 1 : DepSU->
Preds.size() > 1)
3110 DEBUG(
dbgs() <<
" Rescheduling physreg copy ";
3111 Dep.getSUnit()->dump(DAG));
3128 reschedulePhysRegCopies(SU,
true);
3133 reschedulePhysRegCopies(SU,
false);
3175 if (!Top.HazardRec) {
3186 for (
const SUnit *SU : BotRoots) {
3210 if (
tryLess(Top.getLatencyStallCycles(TryCand.
SU),
3211 Top.getLatencyStallCycles(Cand.
SU), TryCand, Cand,
Stall))
3225 Cand.ResDelta.DemandedResources,
3230 if (Cand.Policy.ReduceLatency &&
tryLatency(TryCand, Cand, Top)) {
3235 if (TryCand.
SU->
NodeNum < Cand.SU->NodeNum)
3241 for (
SUnit *SU : Q) {
3244 TryCand.
AtTop =
true;
3246 tryCandidate(Cand, TryCand);
3257 assert(Top.Available.empty() && Top.Pending.empty() &&
"ReadyQ garbage");
3262 SU = Top.pickOnlyChoice();
3271 pickNodeFromQueue(TopCand);
3279 Top.removeReady(SU);
3293 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
3306 const BitVector *ScheduledTrees =
nullptr;
3309 ILPOrder(
bool MaxILP) : MaximizeILP(MaxILP) {}
3314 bool operator()(
const SUnit *
A,
const SUnit *
B)
const {
3315 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3316 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3317 if (SchedTreeA != SchedTreeB) {
3319 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3320 return ScheduledTrees->test(SchedTreeB);
3323 if (DFSResult->getSubtreeLevel(SchedTreeA)
3324 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3325 return DFSResult->getSubtreeLevel(SchedTreeA)
3326 < DFSResult->getSubtreeLevel(SchedTreeB);
3330 return DFSResult->getILP(A) < DFSResult->getILP(B);
3332 return DFSResult->getILP(A) > DFSResult->getILP(B);
3341 std::vector<SUnit*> ReadyQ;
3344 ILPScheduler(
bool MaximizeILP) : Cmp(MaximizeILP) {}
3350 Cmp.DFSResult = DAG->getDFSResult();
3351 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3357 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3365 if (ReadyQ.empty())
return nullptr;
3366 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3367 SUnit *SU = ReadyQ.back();
3370 DEBUG(
dbgs() <<
"Pick node " <<
"SU(" << SU->NodeNum <<
") "
3371 <<
" ILP: " << DAG->getDFSResult()->getILP(SU)
3372 <<
" Tree: " << DAG->getDFSResult()->getSubtreeID(SU) <<
" @"
3373 << DAG->getDFSResult()->getSubtreeLevel(
3374 DAG->getDFSResult()->getSubtreeID(SU)) <<
'\n'
3375 <<
"Scheduling " << *SU->getInstr());
3381 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3387 assert(!IsTopNode &&
"SchedDFSResult needs bottom-up");
3393 ReadyQ.push_back(SU);
3394 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3421 template<
bool IsReverse>
3446 InstructionShuffler(
bool alternate,
bool topdown)
3447 : IsAlternating(alternate), IsTopDown(topdown) {}
3461 if (TopQ.empty())
return nullptr;
3468 if (BottomQ.empty())
return nullptr;
3475 IsTopDown = !IsTopDown;
3495 "-misched-topdown incompatible with -misched-bottomup");
3497 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
3501 "shuffle",
"Shuffle machine instructions alternating directions",
3540 return "color=cyan,style=dashed";
3542 return "color=blue,style=dashed";
3562 std::string Str(
"shape=Mrecord");
3567 Str +=
",style=filled,fillcolor=\"#";
3585 errs() <<
"ScheduleDAGMI::viewGraph is only available in debug builds on "
3586 <<
"systems with Graphviz or gv!\n";
3592 viewGraph(getDAGName(),
"Scheduling-Units Graph for " + getDAGName());
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
iterator end()
Returns an iterator past this container.
virtual ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *, const ScheduleDAG *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
VReg2SUnitMultiMap VRegUses
Maps vregs to the SUnits of their uses in the current scheduling region.
void computeDFSResult()
Compute a DFSResult after DAG building is complete, and before any queue comparisons.
std::reverse_iterator< const_iterator > const_reverse_iterator
void releaseSucc(SUnit *SU, SDep *SuccEdge)
ReleaseSucc - Decrement the NumPredsLeft count of a successor.
static int biasPhysRegCopy(const SUnit *SU, bool isTop)
Minimize physical register live ranges.
Weak DAG edge linking a chain of clustered instrs.
void push_back(const T &Elt)
bool isCtrl() const
Shorthand for getKind() != SDep::Data.
void schedNode(SUnit *SU, bool IsTopNode) override
Called after ScheduleDAGMI has scheduled an instruction and updated scheduled/remaining flags in the ...
const_iterator end(StringRef path)
Get end iterator over path.
virtual void finishBlock()
Cleans up after scheduling in the given block.
virtual void initialize(ScheduleDAGMI *DAG)=0
Initialize the strategy after building the DAG for a new region.
A common definition of LaneBitmask for use in TableGen and CodeGen.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use...
virtual bool enableMachineScheduler() const
True if the subtarget should run MachineScheduler after aggressive coalescing.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static cl::opt< bool > ViewMISchedDAGs("view-misched-dags", cl::Hidden, cl::desc("Pop up a window to show MISched dags after they are processed"))
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G)
static cl::opt< bool > EnablePostRAMachineSched("enable-post-misched", cl::desc("Enable the post-ra machine instruction scheduling pass."), cl::init(true), cl::Hidden)
void clear()
Clear the results.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isArtificialDep() const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
iterator_base< SparseMultiSet * > iterator
void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS)
Use liveness information to find dead defs not marked with a dead flag and move them to the DeadDefs ...
typename SuperClass::const_iterator const_iterator
virtual ~MachineSchedContext()
Each Scheduling boundary is associated with ready queues.
SlotIndex def
The index of the defining instruction.
iterator insert(const ValueT &Val)
Insert a new element at the tail of the subset list.
void dumpSchedule() const
dump the scheduled Sequence.
void addPressureChange(unsigned RegUnit, bool IsDec, const MachineRegisterInfo *MRI)
Add a change in pressure to the pressure diff of a given instruction.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
const MachineSchedContext * Context
SUnit * pickNodeBidirectional(bool &IsTopNode)
Pick the best candidate node from either the top or bottom queue.
bool mustEndGroup(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return true if current group must end.
static bool tryPressure(const PressureChange &TryP, const PressureChange &CandP, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason, const TargetRegisterInfo *TRI, const MachineFunction &MF)
virtual void releaseTopNode(SUnit *SU)=0
When all predecessor dependencies have been resolved, free this node for top-down scheduling...
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
A Module instance is used to store all the information related to an LLVM module. ...
bool isInQueue(SUnit *SU) const
unsigned getCurrCycle() const
Number of cycles to issue the instructions scheduled in this zone.
static MachineSchedRegistry ILPMaxRegistry("ilpmax","Schedule bottom-up for max ILP", createILPMaxScheduler)
ScheduleDAGTopologicalSort Topo
Topo - A topological ordering for SUnits which permits fast IsReachable and similar queries...
static bool tryGreater(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
MachineBasicBlock::iterator CurrentTop
The top of the unscheduled zone.
bool TrackLaneMasks
Whether lane masks should get tracked.
Segments::iterator iterator
bool mustBeginGroup(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return true if new group must begin.
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
static cl::opt< std::string > SchedOnlyFunc("misched-only-func", cl::Hidden, cl::desc("Only schedule this function"))
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
unsigned computeCyclicCriticalPath()
Compute the cyclic critical path through the DAG.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
TargetSchedModel SchedModel
TargetSchedModel provides an interface to the machine model.
void dumpAll(const ScheduleDAG *G) const
void fixupKills(MachineBasicBlock &MBB)
Fixes register kill flags that scheduling has made invalid.
virtual void overrideSchedPolicy(MachineSchedPolicy &Policy, unsigned NumRegionInstrs) const
Override generic scheduling policy within a region.
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
void traceCandidate(const SchedCandidate &Cand)
unsigned DemandedResources
static bool renderGraphFromBottomUp()
bool ShouldTrackPressure
Register pressure in this region computed by initRegPressure.
bool isLocal(SlotIndex Start, SlotIndex End) const
True iff this segment is a single segment that lies between the specified boundaries, exclusively.
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
ScheduleDAGMI * createGenericSchedPostRA(MachineSchedContext *C)
Create a generic scheduler with no vreg liveness or DAG mutation passes.
unsigned getMicroOpBufferSize() const
Number of micro-ops that may be buffered for OOO execution.
Mutate the DAG as a postpass after normal DAG building.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
static ScheduleDAGInstrs * createILPMaxScheduler(MachineSchedContext *C)
virtual std::string getGraphNodeLabel(const SUnit *SU) const =0
Returns a label for an SUnit node in a visualization of the ScheduleDAG.
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
static ScheduleDAGInstrs * createInstructionShuffler(MachineSchedContext *C)
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
void closeRegion()
Finalize the region boundaries and recored live ins and live outs.
Summarize the unscheduled region.
virtual bool enablePostRAScheduler() const
True if the subtarget should run a scheduler after register allocation.
void reset(const CandPolicy &NewPolicy)
unsigned getResourceFactor(unsigned ResIdx) const
Multiply the number of units consumed for a resource by this factor to normalize it relative to other...
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
RegisterPassParser class - Handle the addition of new machine passes.
MachineSchedRegistry provides a selection of available machine instruction schedulers.
RegisterClassInfo * RegClassInfo
MachineBasicBlock::iterator top() const
VNInfo - Value Number Information.
iterator_range< mop_iterator > operands()
static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G)
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
std::unique_ptr< MachineSchedStrategy > SchedImpl
unsigned BotReadyCycle
Cycle relative to end when node is ready.
virtual bool shouldClusterMemOps(MachineInstr &FirstLdSt, MachineInstr &SecondLdSt, unsigned NumLoads) const
Returns true if the two given memory operations should be scheduled adjacent.
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for...
nonconst_iterator getNonConstIterator() const
virtual void AdvanceCycle()
AdvanceCycle - This callback is invoked whenever the next top-down instruction to be scheduled cannot...
void updateQueues(SUnit *SU, bool IsTopNode)
Update scheduler DAG and queues after scheduling an instruction.
virtual void schedNode(SUnit *SU, bool IsTopNode)=0
Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an instruction and updated scheduled/rem...
SmallVector< SDep, 4 > Preds
All sunit predecessors.
virtual void startBlock(MachineBasicBlock *BB)
Prepares to perform scheduling in the given block.
MachineBasicBlock::const_iterator getPos() const
Get the MI position corresponding to this register pressure.
A register anti-dependence (aka WAR).
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
unsigned getDependentLatency() const
void recede(SmallVectorImpl< RegisterMaskPair > *LiveUses=nullptr)
Recede across the previous instruction.
MachineFunction & MF
Machine function.
const TargetSchedModel * getSchedModel() const
Gets the machine model for instruction scheduling.
unsigned NumInstrsScheduled
The number of instructions scheduled so far.
bool isScheduled
True once scheduled.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
unsigned getNumSubtrees() const
The number of subtrees detected in this DAG.
unsigned getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
ArrayRef< SUnit * > elements()
void buildSchedGraph(AliasAnalysis *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
void closeBottom()
Set the boundary for the bottom of the region and summarize live outs.
unsigned NumSuccsLeft
of succs not scheduled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
bool isWeak() const
Tests if this a weak dependence.
Provide an instruction scheduling machine model to CodeGen passes.
const HexagonInstrInfo * TII
static std::string getEdgeAttributes(const SUnit *Node, SUnitIterator EI, const ScheduleDAG *Graph)
If you want to override the dot attributes printed for a particular edge, override this method...
Kind getKind() const
Returns an enum value representing the kind of the dependence.
An individual mapping from virtual register number to SUnit.
static MachineSchedRegistry DefaultSchedRegistry("default","Use the target's default scheduler choice.", useDefaultMachineSched)
static cl::opt< MachineSchedRegistry::ScheduleDAGCtor, false, RegisterPassParser< MachineSchedRegistry > > MachineSchedOpt("misched", cl::init(&useDefaultMachineSched), cl::Hidden, cl::desc("Machine instruction scheduler to use"))
MachineSchedOpt allows command line selection of the scheduler.
virtual const char * getRegPressureSetName(unsigned Idx) const =0
Get the name of this register unit pressure set.
static unsigned getWeakLeft(const SUnit *SU, bool isTop)
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Regular data dependence (aka true-dependence).
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Result of a LiveRange query.
bool hasPhysRegUses
Has physreg uses.
Reg
All possible values of the reg field in the ModR/M byte.
bool hasPhysRegDefs
Has physreg defs that are being used.
PressureDiff & getPressureDiff(const SUnit *SU)
std::vector< std::unique_ptr< ScheduleDAGMutation > > Mutations
Ordered list of DAG postprocessing steps.
DbgValueVector DbgValues
Remember instruction that precedes DBG_VALUE.
void InitDAGTopologicalSorting()
Creates the initial topological ordering from the DAG to be scheduled.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Target-Independent Code Generator Pass Configuration Options.
bool IsAcyclicLatencyLimited
static MachineSchedRegistry ShufflerRegistry("shuffle","Shuffle machine instructions alternating directions", createInstructionShuffler)
void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs) override
Initialize the per-region scheduling policy.
static bool isSimple(Instruction *I)
bool ShouldTrackLaneMasks
Compute the values of each DAG node for various metrics during DFS.
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
static const unsigned InvalidCycle
MachineBasicBlock::iterator LiveRegionEnd
unsigned getCriticalCount() const
Get the scaled count of scheduled micro-ops and resources, including executed resources.
static cl::opt< bool > VerifyScheduling("verify-misched", cl::Hidden, cl::desc("Verify machine instrs before and after machine scheduling"))
void bumpCycle(unsigned NextCycle)
Move the boundary of scheduled code by one cycle.
unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle)
Add the given processor resource to this scheduled zone.
static MachineBasicBlock::const_iterator priorNonDebug(MachineBasicBlock::const_iterator I, MachineBasicBlock::const_iterator Beg)
Decrement this iterator until reaching the top or a non-debug instr.
bool hasReservedResource
Uses a reserved resource.
void scheduleMI(SUnit *SU, bool IsTopNode)
Move an instruction and update register pressure.
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
reverse_iterator rbegin() const
RegPressureTracker BotRPTracker
void buildDAGWithRegPressure()
Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking enabled.
unsigned WeakSuccsLeft
of weak succs not scheduled.
virtual unsigned getRegPressureSetScore(const MachineFunction &MF, unsigned PSetID) const
Return a heuristic for the machine scheduler to compare the profitability of increasing one register ...
virtual void RecedeCycle()
RecedeCycle - This callback is invoked whenever the next bottom-up instruction to be scheduled cannot...
void dump(const ScheduleDAG *G) const
SmallVector< RegisterMaskPair, 8 > LiveInRegs
List of live in virtual registers or physical register units.
std::vector< PressureChange > RegionCriticalPSets
List of pressure sets that exceed the target's pressure limit before scheduling, listed in increasing...
static const char * getReasonStr(GenericSchedulerBase::CandReason Reason)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static std::string getGraphName(const ScheduleDAG *G)
Itinerary data supplied by a subtarget to be used by a target.
unsigned NumPredsLeft
of preds not scheduled.
static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop)
void releasePending()
Release pending ready nodes in to the available queue.
void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
ScheduleDAGMILive * createGenericSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
MachinePassRegistry - Track the registration of machine passes.
List of registers defined and used by a machine instruction.
std::vector< SUnit * >::iterator iterator
void collectVRegUses(SUnit &SU)
virtual void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs)
Initialize the DAG and common scheduler state for a new scheduling region.
void bumpNode(SUnit *SU)
Move the boundary of scheduled code by one SUnit.
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
SUnit * pickNode(bool &IsTopNode) override
Pick the next node to schedule.
void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, RegPressureTracker &TempTracker)
void checkAcyclicLatency()
Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic critical path by more cycle...
static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G)
void incExecutedResources(unsigned PIdx, unsigned Count)
TargetInstrInfo - Interface to description of machine instruction set.
virtual void registerRoots()
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
bool isDebugValue() const
void resize(unsigned NumSUnits)
Initialize the result data with the size of the DAG.
void recedeSkipDebugValues()
Recede until we find an instruction which is not a DebugValue.
SmallVector< RegisterMaskPair, 8 > LiveOutRegs
bool isUnbuffered
Uses an unbuffered resource.
void addLiveRegs(ArrayRef< RegisterMaskPair > Regs)
Force liveness of virtual registers or physical register units.
reverse_iterator rend() const
RegisterClassInfo * RegClassInfo
void getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction top-down.
iterator remove(iterator I)
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
initializer< Ty > init(const Ty &Val)
bool isCall
Is a function call.
ScheduleHazardRecognizer * HazardRec
unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles)
Compute the next cycle at which the given processor resource can be scheduled.
void initQueues(ArrayRef< SUnit * > TopRoots, ArrayRef< SUnit * > BotRoots)
Release ExitSU predecessors and setup scheduler queues.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
CandReason
Represent the type of SchedCandidate found within a single queue.
ArrayRef< unsigned > getLiveThru() const
Helpers for implementing custom MachineSchedStrategy classes.
PressureChange CurrentMax
unsigned getScheduledLatency() const
Get the number of latency cycles "covered" by the scheduled instructions.
const InstrItineraryData * getInstrItineraries() const
unsigned short Latency
Node latency.
static const unsigned MinSubtreeSize
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
unsigned getZoneCritResIdx() const
void removeReady(SUnit *SU)
Remove SU from the ready set for this boundary.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const MachineOperand & getOperand(unsigned i) const
Summarize the scheduling resources required for an instruction of a particular scheduling class...
void updatePressureDiffs(ArrayRef< RegisterMaskPair > LiveUses)
Update the PressureDiff array for liveness after scheduling this instruction.
unsigned getLatencyFactor() const
Multiply cycle count by this factor to normalize it relative to other resources.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static bool isSchedBoundary(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB, MachineFunction *MF, const TargetInstrInfo *TII)
Return true of the given instruction should not be included in a scheduling region.
RegisterPressure computed within a region of instructions delimited by TopPos and BottomPos...
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
void setUniverse(unsigned U)
Set the universe size which determines the largest key the set can hold.
Represent the analysis usage information of a pass.
static MachinePassRegistry Registry
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
Store the state used by GenericScheduler heuristics, required for the lifetime of one invocation of p...
bool checkHazard(SUnit *SU)
Does this SU have a hazard within the current instruction group.
void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone)
Apply a set of heursitics to a new candidate.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
void releasePred(SUnit *SU, SDep *PredEdge)
ReleasePred - Decrement the NumSuccsLeft count of a predecessor.
Track the current register pressure at some position in the instruction stream, and remember the high...
static const unsigned End
virtual void releaseBottomNode(SUnit *SU)=0
When all successor dependencies have been resolved, free this node for bottom-up scheduling.
void findRootsAndBiasEdges(SmallVectorImpl< SUnit * > &TopRoots, SmallVectorImpl< SUnit * > &BotRoots)
Policy for scheduling the next instruction in the candidate's zone.
const TargetSchedModel * SchedModel
static ScheduleDAGInstrs * useDefaultMachineSched(MachineSchedContext *C)
A dummy default scheduler factory indicates whether the scheduler is overridden on the command line...
void dumpScheduledState() const
List of PressureChanges in order of increasing, unique PSetID.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
DOTGraphTraits(bool isSimple=false)
bool empty() const
empty - Check if the array is empty.
SchedResourceDelta ResDelta
const TargetRegisterInfo * TRI
virtual bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Test if the given instruction should be considered a scheduling boundary.
ScheduleDAGInstrs *(*)(MachineSchedContext *) ScheduleDAGCtor
std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
SchedDFSResult * DFSResult
Information about DAG subtrees.
PressureDiffs SUPressureDiffs
void clear()
Clears the set.
unsigned getNumProcResourceKinds() const
Get the number of kinds of resources for this target.
static MachineBasicBlock::const_iterator nextIfDebug(MachineBasicBlock::const_iterator I, MachineBasicBlock::const_iterator End)
If this iterator is a debug value, increment until reaching the End or a non-debug instruction...
void apply(Opt *O, const Mod &M, const Mods &...Ms)
LiveIntervals * getLIS() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Machine Instruction false
void releaseSuccessors(SUnit *SU)
releaseSuccessors - Call releaseSucc on each of SU's successors.
const SUnit * NextClusterSucc
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,"Machine Instruction Scheduler", false, false) INITIALIZE_PASS_END(MachineScheduler
void viewGraph() override
Out-of-line implementation with no arguments is handy for gdb.
void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone, SchedBoundary *OtherZone)
Set the CandPolicy given a scheduling zone given the current resources and latencies inside and outsi...
void initLiveThru(const RegPressureTracker &RPTracker)
Initialize the LiveThru pressure set based on the untied defs found in RPTracker. ...
static cl::opt< bool > EnableRegPressure("misched-regpressure", cl::Hidden, cl::desc("Enable register pressure scheduling."), cl::init(true))
ProcResIter getWriteProcResEnd(const MCSchedClassDesc *SC) const
iterator find(const KeyT &Key)
Find an element by its key.
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
unsigned WeakPredsLeft
of weak preds not scheduled.
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem)
bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model. ...
static cl::opt< unsigned > SchedOnlyBlock("misched-only-block", cl::Hidden, cl::desc("Only schedule this MBB#"))
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.
void adjustLaneLiveness(const LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos, MachineInstr *AddFlagsMI=nullptr)
Use liveness information to find out which uses/defs are partially undefined/dead and adjust the Regi...
void advance()
Advance across the current instruction.
Iterator for intrusive lists based on ilist_node.
std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
virtual void EmitInstruction(SUnit *)
EmitInstruction - This callback is invoked when an instruction is emitted, to advance the hazard stat...
const SUnit * NextClusterPred
Record the next node in a scheduled cluster.
const MCProcResourceDesc * getProcResource(unsigned PIdx) const
Get a processor resource by ID for convenience.
void dump(const TargetRegisterInfo &TRI) const
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
void compute(ArrayRef< SUnit > SUnits)
Compute various metrics for the DAG with given roots.
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
void reschedulePhysRegCopies(SUnit *SU, bool isTop)
unsigned getExecutedCount() const
Get a scaled count for the minimum execution time of the scheduled micro-ops that are ready to execut...
AnalysisUsage & addRequiredID(const void *ID)
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static cl::opt< unsigned > MISchedCutoff("misched-cutoff", cl::Hidden, cl::desc("Stop scheduling after N instructions"), cl::init(~0U))
static ScheduleDAGInstrs * createILPMinScheduler(MachineSchedContext *C)
bool test(unsigned Idx) const
bool isCtrlDep() const
Tests if this is not an SDep::Data dependence.
virtual const TargetLowering * getTargetLowering() const
static cl::opt< bool > EnableMachineSched("enable-misched", cl::desc("Enable the machine instruction scheduling pass."), cl::init(true), cl::Hidden)
static LaneBitmask getNone()
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
cl::opt< bool > DumpCriticalPathLength("misched-dcpl", cl::Hidden, cl::desc("Print critical path length to stdout"))
void releaseNode(SUnit *SU, unsigned ReadyCycle)
CHAIN = SC CHAIN, Imm128 - System call.
StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
void updateScheduledPressure(const SUnit *SU, const std::vector< unsigned > &NewMaxPressure)
void setPreservesCFG()
This function should be called by the pass, iff they do not:
LiveInterval & getInterval(unsigned Reg)
std::unique_ptr< ScheduleDAGMutation > createCopyConstrainDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
static cl::opt< bool > EnableCyclicPath("misched-cyclicpath", cl::Hidden, cl::desc("Enable cyclic critical path analysis."), cl::init(true))
void initResourceDelta(const ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
~ScheduleDAGMILive() override
void initializeMachineSchedulerPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned getOtherResourceCount(unsigned &OtherCritIdx)
void dumpPolicy() const override
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static bool tryLess(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
Return true if this heuristic determines order.
virtual void finalizeSchedule()
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand)
Apply a set of heursitics to a new candidate for PostRA scheduling.
bool IsReachable(const SUnit *SU, const SUnit *TargetSU)
Checks if SU is reachable from TargetSU.
static MachineSchedRegistry GenericSchedRegistry("converge","Standard converging scheduler.", createConveringSched)
void biasCriticalPath()
Orders this node's predecessor edges such that the critical path edge occurs first.
PressureChange CriticalMax
virtual void Reset()
Reset - This callback is invoked when a new block of instructions is about to be schedule.
virtual void schedule()=0
Orders nodes according to selected style.
virtual bool getMemOpBaseRegImmOfs(MachineInstr &MemOp, unsigned &BaseReg, int64_t &Offset, const TargetRegisterInfo *TRI) const
Get the base register and byte offset of an instruction that reads/writes memory. ...
virtual const TargetRegisterClass * getRegClassFor(MVT VT) const
Return the register class that should be used for the specified value type.
MachineBasicBlock::iterator bottom() const
void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos)
Change the position of an instruction within the basic block and update live ranges and region bounda...
MachineBasicBlock::iterator end() const
Returns an iterator to the bottom of the current scheduling region.
virtual bool hasVRegLiveness() const
Return true if this DAG supports VReg liveness and RegPressure.
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
void schedNode(SUnit *SU, bool IsTopNode) override
Update the scheduler's state after scheduling a node.
const SUnit * getNextClusterSucc() const
virtual void scheduleTree(unsigned SubtreeID)
Scheduler callback to notify that a new subtree is scheduled.
llvm_unreachable("Unknown RegBank!")
void closeTop()
Set the boundary for the top of the region and summarize live ins.
void releasePredecessors(SUnit *SU)
releasePredecessors - Call releasePred on each of SU's predecessors.
unsigned getSubtreeID(const SUnit *SU) const
Get the ID of the subtree the given DAG node belongs to.
unsigned getUnscheduledLatency(SUnit *SU) const
void initialize(ScheduleDAGMI *dag) override
Initialize the strategy after building the DAG for a new region.
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
bool isCluster() const
Tests if this is an Order dependence that is marked as "cluster", meaning it is artificial and wants ...
SUnit EntrySU
Special node for the region entry.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
virtual SUnit * pickNode(bool &IsTopNode)=0
Pick the next node to schedule, or return NULL.
unsigned getNumMicroOps(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return the number of issue slots required for this MI.
A ScheduleDAG for scheduling lists of MachineInstr.
Representation of each machine instruction.
SUnit ExitSU
Special node for the region exit.
void initializePostMachineSchedulerPass(PassRegistry &)
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void initialize(ScheduleDAGMI *Dag) override
Initialize the strategy after building the DAG for a new region.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit * pickOnlyChoice()
Call this before applying any other heuristics to the Available queue.
void dumpRegSetPressure(ArrayRef< unsigned > SetPressure, const TargetRegisterInfo *TRI)
Status of an instruction's critical resource consumption.
~ScheduleDAGMI() override
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
cl::opt< bool > ForceBottomUp
unsigned findMaxLatency(ArrayRef< SUnit * > ReadySUs)
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
unsigned getNumInstrs(const SUnit *SU) const
Get the number of instructions in the given subtree and its children.
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
MachineSchedStrategy - Interface to the scheduling algorithm used by ScheduleDAGMI.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Capture a change in pressure for a single pressure set.
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.
SmallVector< unsigned, 16 > RemainingCounts
static ScheduleDAGInstrs * createConveringSched(MachineSchedContext *C)
void placeDebugValues()
Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
static cl::opt< unsigned > ViewMISchedCutoff("view-misched-cutoff", cl::Hidden, cl::desc("Hide nodes with more predecessor/successor than cutoff"))
In some situations a few uninteresting nodes depend on nearly all other nodes in the graph...
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream...
unsigned getLatencyStallCycles(SUnit *SU)
Get the difference between the given SUnit's ready time and the current cycle.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
SUnit * pickNode(bool &IsTopNode) override
Pick the best node to balance the schedule. Implements MachineSchedStrategy.
void pickNodeFromQueue(SchedBoundary &Zone, const CandPolicy &ZonePolicy, const RegPressureTracker &RPTracker, SchedCandidate &Candidate)
Pick the best candidate from the queue.
const TargetInstrInfo * TII
Target instruction information.
static bool isNodeHidden(const SUnit *Node)
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.
static cl::opt< unsigned > ReadyListLimit("misched-limit", cl::Hidden, cl::desc("Limit ready list to N instructions"), cl::init(256))
Avoid quadratic complexity in unusually large basic blocks by limiting the size of the ready lists...
unsigned NodeNum
Entry # of node in the node vector.
unsigned getPSetOrMax() const
const std::vector< unsigned > & getRegSetPressureAtPos() const
Get the register set pressure at the current position, which may be less than the pressure across the...
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
unsigned getReg() const
getReg - Returns the register number.
MachineBasicBlock::iterator CurrentBottom
The bottom of the unscheduled zone.
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.
bool operator<(int64_t V1, const APSInt &V2)
A raw_ostream that writes to an std::string.
void initQueues(ArrayRef< SUnit * > TopRoots, ArrayRef< SUnit * > BotRoots)
Release ExitSU predecessors and setup scheduler queues.
virtual const TargetInstrInfo * getInstrInfo() const
unsigned getMicroOpFactor() const
Multiply number of micro-ops by this factor to normalize it relative to other resources.
void postprocessDAG()
Apply each ScheduleDAGMutation step in order.
static LLVM_ATTRIBUTE_UNUSED Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
SmallVector< SDep, 4 > Succs
All sunit successors.
unsigned getIssueWidth() const
Maximum number of micro-ops that may be scheduled per cycle.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
bool isBottomReady() const
static MachineSchedRegistry ILPMinRegistry("ilpmin","Schedule bottom-up for min ILP", createILPMinScheduler)
Arbitrary strong DAG edge (no real dependence).
void scheduleTree(unsigned SubtreeID)
Scheduler callback to update SubtreeConnectLevels when a tree is initially scheduled.
const SUnit * getNextClusterPred() const
This class implements an extremely fast bulk output stream that can only output to a stream...
StringRef getName() const
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
void AddPred(SUnit *Y, SUnit *X)
Updates the topological ordering to accommodate an edge to be added from SUnit X to SUnit Y...
MachineInstr * FirstDbgValue
Machine Instruction Scheduler
MachineBasicBlock * BB
The block in which to insert instructions.
unsigned getCurrMOps() const
Micro-ops issued in the current cycle.
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
const TargetSchedModel * SchedModel
INITIALIZE_PASS(PostMachineScheduler,"postmisched","PostRA Machine Instruction Scheduler", false, false) PostMachineScheduler
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register. ...
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
void setPos(MachineBasicBlock::const_iterator Pos)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
RegisterPressure & getPressure()
Get the resulting register pressure over the traversed region.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
MachineRegisterInfo & MRI
Virtual/real register map.
std::vector< SUnit > SUnits
The scheduling units.
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
unsigned getReg() const
Returns the register associated with this edge.
ProcResIter getWriteProcResBegin(const MCSchedClassDesc *SC) const
SlotIndex - An opaque wrapper around machine indexes.
Printable PrintVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI)
Create Printable object to print virtual registers and physical registers on a raw_ostream.
const char * getResourceName(unsigned PIdx) const
static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
RegPressureTracker TopRPTracker
RegPressureTracker RPTracker
void setBest(SchedCandidate &Best)
virtual HazardType getHazardType(SUnit *m, int Stalls=0)
getHazardType - Return the hazard type of emitting this node.
void pickNodeFromQueue(SchedCandidate &Cand)
unsigned getResourceCount(unsigned ResIdx) const
void getUpwardPressureDelta(const MachineInstr *MI, PressureDiff &PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit) const
This is the fast version of querying register pressure that does not directly depend on current liven...
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block...
Scheduling unit. This is a node in the scheduling DAG.
This file describes how to lower LLVM code to machine code.
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
cl::opt< bool > ForceTopDown
bool isResourceLimited() const
static cl::opt< bool > EnableMemOpCluster("misched-cluster", cl::Hidden, cl::desc("Enable memop clustering."), cl::init(true))