53#include "llvm/Config/llvm-config.h"
77#define DEBUG_TYPE "machine-scheduler"
80 "Number of instructions in source order after pre-RA scheduling");
82 "Number of instructions in source order after post-RA scheduling");
84 "Number of instructions scheduled by pre-RA scheduler");
86 "Number of instructions scheduled by post-RA scheduler");
87STATISTIC(NumClustered,
"Number of load/store pairs clustered");
90 "Number of scheduling units chosen from top queue pre-RA");
92 "Number of scheduling units chosen from bottom queue pre-RA");
94 "Number of scheduling units chosen for NoCand heuristic pre-RA");
96 "Number of scheduling units chosen for Only1 heuristic pre-RA");
98 "Number of scheduling units chosen for PhysReg heuristic pre-RA");
100 "Number of scheduling units chosen for RegExcess heuristic pre-RA");
102 "Number of scheduling units chosen for RegCritical heuristic pre-RA");
104 "Number of scheduling units chosen for Stall heuristic pre-RA");
106 "Number of scheduling units chosen for Cluster heuristic pre-RA");
108 "Number of scheduling units chosen for Weak heuristic pre-RA");
110 "Number of scheduling units chosen for RegMax heuristic pre-RA");
112 NumResourceReducePreRA,
113 "Number of scheduling units chosen for ResourceReduce heuristic pre-RA");
115 NumResourceDemandPreRA,
116 "Number of scheduling units chosen for ResourceDemand heuristic pre-RA");
118 NumTopDepthReducePreRA,
119 "Number of scheduling units chosen for TopDepthReduce heuristic pre-RA");
121 NumTopPathReducePreRA,
122 "Number of scheduling units chosen for TopPathReduce heuristic pre-RA");
124 NumBotHeightReducePreRA,
125 "Number of scheduling units chosen for BotHeightReduce heuristic pre-RA");
127 NumBotPathReducePreRA,
128 "Number of scheduling units chosen for BotPathReduce heuristic pre-RA");
130 "Number of scheduling units chosen for NodeOrder heuristic pre-RA");
132 "Number of scheduling units chosen for FirstValid heuristic pre-RA");
135 "Number of scheduling units chosen from top queue post-RA");
137 "Number of scheduling units chosen from bottom queue post-RA");
139 "Number of scheduling units chosen for NoCand heuristic post-RA");
141 "Number of scheduling units chosen for Only1 heuristic post-RA");
143 "Number of scheduling units chosen for PhysReg heuristic post-RA");
145 "Number of scheduling units chosen for RegExcess heuristic post-RA");
147 NumRegCriticalPostRA,
148 "Number of scheduling units chosen for RegCritical heuristic post-RA");
150 "Number of scheduling units chosen for Stall heuristic post-RA");
152 "Number of scheduling units chosen for Cluster heuristic post-RA");
154 "Number of scheduling units chosen for Weak heuristic post-RA");
156 "Number of scheduling units chosen for RegMax heuristic post-RA");
158 NumResourceReducePostRA,
159 "Number of scheduling units chosen for ResourceReduce heuristic post-RA");
161 NumResourceDemandPostRA,
162 "Number of scheduling units chosen for ResourceDemand heuristic post-RA");
164 NumTopDepthReducePostRA,
165 "Number of scheduling units chosen for TopDepthReduce heuristic post-RA");
167 NumTopPathReducePostRA,
168 "Number of scheduling units chosen for TopPathReduce heuristic post-RA");
170 NumBotHeightReducePostRA,
171 "Number of scheduling units chosen for BotHeightReduce heuristic post-RA");
173 NumBotPathReducePostRA,
174 "Number of scheduling units chosen for BotPathReduce heuristic post-RA");
176 "Number of scheduling units chosen for NodeOrder heuristic post-RA");
178 "Number of scheduling units chosen for FirstValid heuristic post-RA");
182 cl::desc(
"Set the post-RA MISched anti-dependency break mode"),
183 cl::init(TargetSubtargetInfo::ANTIDEP_NONE),
185 "No anti-dependency breaking"),
186 clEnumValN(TargetSubtargetInfo::ANTIDEP_CRITICAL,
"critical",
187 "Break critical-path anti-dependencies"),
188 clEnumValN(TargetSubtargetInfo::ANTIDEP_ALL,
"all",
189 "Break all anti-dependencies")));
219void MachineSchedStrategy::anchor() {}
221void ScheduleDAGMutation::anchor() {}
261 const RequiredAnalyses &Analyses);
289 const RequiredAnalyses &Analyses);
314 const RequiredAnalyses &Analyses);
331 MachineSchedulerImpl Impl;
334 MachineSchedulerLegacy();
335 void getAnalysisUsage(AnalysisUsage &AU)
const override;
343 SSAMachineSchedulerImpl Impl;
346 SSAMachineSchedulerLegacy();
347 void getAnalysisUsage(AnalysisUsage &AU)
const override;
355 PostMachineSchedulerImpl Impl;
358 PostMachineSchedulerLegacy();
359 void getAnalysisUsage(AnalysisUsage &AU)
const override;
367char MachineSchedulerLegacy::ID = 0;
372 "Machine Instruction Scheduler",
false,
false)
379 "Machine Instruction Scheduler",
false,
false)
383void MachineSchedulerLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
396char SSAMachineSchedulerLegacy::ID = 0;
401 "SSA Machine Instruction Scheduler",
false,
false)
408 "SSA Machine Instruction Scheduler",
false,
false)
410SSAMachineSchedulerLegacy::SSAMachineSchedulerLegacy()
415void SSAMachineSchedulerLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
428char PostMachineSchedulerLegacy::ID = 0;
433 "PostRA Machine Instruction Scheduler",
false,
false)
440PostMachineSchedulerLegacy::PostMachineSchedulerLegacy()
443void PostMachineSchedulerLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
466 cl::desc(
"Machine instruction scheduler to use"));
476 assert(
I != Beg &&
"reached the top of the region, cannot decrement");
478 if (!
I->isDebugOrPseudoInstr())
497 for(;
I !=
End; ++
I) {
498 if (!
I->isDebugOrPseudoInstr())
539 if (Opts.verify_misched) {
541 const char *MSchedBanner =
"Before machine scheduling.";
543 MF->verify(P, MSchedBanner, &
errs());
545 MF->verify(*MFAM, MSchedBanner, &
errs());
554 if (Opts.verify_misched) {
555 const char *MSchedBanner =
"After machine scheduling.";
557 MF->verify(P, MSchedBanner, &
errs());
559 MF->verify(*MFAM, MSchedBanner, &
errs());
587 if (Opts.verify_misched) {
589 const char *MSchedBanner =
"Before machine scheduling.";
591 MF->verify(P, MSchedBanner, &
errs());
593 MF->verify(*MFAM, MSchedBanner, &
errs());
603 if (Opts.verify_misched) {
604 const char *MSchedBanner =
"After machine scheduling.";
606 MF->verify(P, MSchedBanner, &
errs());
608 MF->verify(*MFAM, MSchedBanner, &
errs());
636 if (Opts.verify_misched) {
637 const char *PostMSchedBanner =
"Before post machine scheduling.";
639 MF->verify(P, PostMSchedBanner, &
errs());
641 MF->verify(*MFAM, PostMSchedBanner, &
errs());
649 if (Opts.verify_misched) {
650 const char *PostMSchedBanner =
"After post machine scheduling.";
652 MF->verify(P, PostMSchedBanner, &
errs());
654 MF->verify(*MFAM, PostMSchedBanner, &
errs());
675bool MachineSchedulerLegacy::runOnMachineFunction(
MachineFunction &MF) {
685 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
686 auto &TM = getAnalysis<TargetPassConfig>().getTM<
TargetMachine>();
687 auto &
AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
688 auto &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
690 getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
691 auto &MBFI = getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
693 Impl.setLegacyPass(
this);
694 return Impl.run(MF, TM, {MLI,
AA, LIS, RegClassInfo, MBFI});
697bool SSAMachineSchedulerLegacy::runOnMachineFunction(
MachineFunction &MF) {
705 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
706 auto &TM = getAnalysis<TargetPassConfig>().getTM<
TargetMachine>();
707 auto &
AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
708 auto &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
710 getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
711 auto &MBFI = getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
713 Impl.setLegacyPass(
this);
714 return Impl.run(MF, TM, {MLI,
AA, LIS, RegClassInfo, MBFI});
718 : Impl(
std::make_unique<MachineSchedulerImpl>()), TM(TM) {}
724 : Impl(
std::make_unique<SSAMachineSchedulerImpl>()), TM(TM) {}
730 : Impl(
std::make_unique<PostMachineSchedulerImpl>()), TM(TM) {}
751 Impl->setMFAM(&MFAM);
752 bool Changed = Impl->run(MF, *TM, {MLI,
AA, LIS, RegClassInfo, MBFI});
758 .preserve<SlotIndexesAnalysis>()
781 Impl->setMFAM(&MFAM);
782 bool Changed = Impl->run(MF, *TM, {MLI,
AA, LIS, RegClassInfo, MBFI});
791bool PostMachineSchedulerLegacy::runOnMachineFunction(
MachineFunction &MF) {
803 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
804 auto &TM = getAnalysis<TargetPassConfig>().getTM<
TargetMachine>();
805 auto &
AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
806 auto &RCI = getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
807 Impl.setLegacyPass(
this);
808 return Impl.run(MF, TM, {MLI,
AA, RCI});
828 Impl->setMFAM(&MFAM);
829 bool Changed = Impl->run(MF, *TM, {MLI,
AA, RCI});
851 return MI->isCall() ||
TII->isSchedulingBoundary(*
MI,
MBB, *MF) ||
852 MI->isFakeUse() ||
MI->isPHI();
860 bool RegionsTopDown) {
866 RegionEnd !=
MBB->begin(); RegionEnd =
I) {
869 if (RegionEnd !=
MBB->end() ||
876 unsigned NumRegionInstrs = 0;
878 for (;
I !=
MBB->begin(); --
I) {
882 if (!
MI.isDebugOrPseudoInstr()) {
891 if (NumRegionInstrs != 0)
896 std::reverse(Regions.
begin(), Regions.
end());
902 const CodeGenOptions &Opts =
Scheduler.Opts;
911 if (Opts.misched_only_func && *Opts.misched_only_func !=
MF->getName())
913 if (Opts.misched_only_block &&
914 (
int)*Opts.misched_only_block !=
MBB->getNumber())
936 bool ScheduleSingleMI =
Scheduler.shouldScheduleSingleMIRegions();
940 unsigned NumRegionInstrs = R.NumRegionInstrs;
948 if (
I == RegionEnd || (!ScheduleSingleMI &&
I == std::prev(RegionEnd))) {
954 auto DumpRegionHeader = [&] {
955 dbgs() <<
"Current Schedule Region\n";
957 <<
MBB->getName() <<
"\n From: " << *
I <<
" To: ";
958 if (RegionEnd !=
MBB->end())
959 dbgs() << *RegionEnd;
962 dbgs() <<
" RegionInstrs: " << NumRegionInstrs <<
'\n';
968 if (Opts.misched_dcpl) {
970 errs() <<
":%bb. " <<
MBB->getNumber();
971 errs() <<
" " <<
MBB->getName() <<
" \n";
991#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
993 dbgs() <<
"Queue " << Name <<
": ";
994 for (
const SUnit *SU : Queue)
995 dbgs() << *SU <<
" ";
1008 if (AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE)
1011 assert(
C->MF->getRegInfo().tracksLiveness() &&
1012 "Live-ins must be accurate for anti-dependency breaking");
1014 "Register class info is required for anti-dependency breaking");
1015 if (AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) {
1017 C->MF->getSubtarget().getCriticalPathRCs(CriticalPathRCs);
1021 assert(AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL &&
1022 "Unexpected anti-dependency break mode");
1029 for (
auto I = From;
I != To;) {
1031 --BoundaryScanIndex;
1032 if (!
MI.isDebugOrPseudoInstr())
1033 Breaker->Observe(
MI, BoundaryScanIndex, RegionEndIndex);
1035 BoundaryScanIndex -=
MI.getBundleSize();
1042 Breaker->StartBlock(
MBB);
1043 BoundaryScanPos =
MBB->end();
1044 BoundaryScanIndex =
MBB->size();
1045 RegionEndIndex = BoundaryScanIndex;
1051 Breaker->FinishBlock();
1060 scanRangeBackwards(BoundaryScanPos,
End);
1061 RegionEndIndex = BoundaryScanIndex;
1062 RegionProcessed =
false;
1070 BoundaryScanPos = Begin;
1071 if (RegionProcessed) {
1072 BoundaryScanIndex -= std::distance(Begin,
End);
1076 scanRangeBackwards(
End, Begin);
1086 RegionProcessed =
true;
1087 return Breaker->BreakAntiDependencies(SUnits, Begin,
End, RegionEndIndex,
1101 if (SuccEdge->
isWeak()) {
1107 dbgs() <<
"*** Scheduling failed! ***\n";
1109 dbgs() <<
" has been released too many times!\n";
1136 if (PredEdge->
isWeak()) {
1142 dbgs() <<
"*** Scheduling failed! ***\n";
1144 dbgs() <<
" has been released too many times!\n";
1183 unsigned regioninstrs) {
1193 else if (
SchedImpl->getPolicy().OnlyBottomUp)
1214 BB->splice(InsertPos,
BB,
MI);
1218 LIS->handleMove(*
MI,
true);
1226#if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
1227 if (NumInstrsScheduled ==
Opts.misched_cutoff &&
Opts.misched_cutoff != ~0U) {
1231 ++NumInstrsScheduled;
1273 bool IsTopNode =
false;
1278 LLVM_DEBUG(
dbgs() <<
"** ScheduleDAGMI::schedule picking next node\n");
1295 if (&*priorII ==
MI)
1317 dbgs() <<
"*** Final schedule for "
1334 assert(!SU.isBoundaryNode() &&
"Boundary node should not be in SUnits");
1337 SU.biasCriticalPath();
1340 if (!SU.NumPredsLeft)
1343 if (!SU.NumSuccsLeft)
1346 ExitSU.biasCriticalPath();
1356 for (
SUnit *SU : TopRoots)
1395 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>
::iterator
1397 std::pair<MachineInstr *, MachineInstr *>
P = *std::prev(DI);
1412 unsigned HeaderColWidth =
Opts.misched_dump_schedule_trace_col_header_width;
1413 unsigned ColWidth =
Opts.misched_dump_schedule_trace_col_width;
1422 dbgs() <<
" * Schedule table (TopDown):\n";
1440 for (
unsigned C = FirstCycle;
C <= LastCycle; ++
C)
1447 dbgs() <<
"Missing SUnit\n";
1450 std::string NodeName;
1453 unsigned C = FirstCycle;
1454 for (;
C <= LastCycle; ++
C) {
1467 if (
Opts.misched_sort_resources_in_trace)
1472 return std::tie(LHS.AcquireAtCycle, LHS.ReleaseAtCycle) <
1473 std::tie(RHS.AcquireAtCycle, RHS.ReleaseAtCycle);
1477 const std::string ResName =
1478 SchedModel.getResourceName(PI.ProcResourceIdx);
1483 for (
unsigned I = 0, E = PI.ReleaseAtCycle - PI.AcquireAtCycle;
I != E;
1486 while (
C++ <= LastCycle)
1495 unsigned HeaderColWidth =
Opts.misched_dump_schedule_trace_col_header_width;
1496 unsigned ColWidth =
Opts.misched_dump_schedule_trace_col_width;
1505 dbgs() <<
" * Schedule table (BottomUp):\n";
1518 if ((
int)SU->
BotReadyCycle - PI->ReleaseAtCycle + 1 < LastCycle)
1519 LastCycle = (int)SU->
BotReadyCycle - PI->ReleaseAtCycle + 1;
1524 for (
int C = FirstCycle;
C >= LastCycle; --
C)
1531 dbgs() <<
"Missing SUnit\n";
1534 std::string NodeName;
1538 for (;
C >= LastCycle; --
C) {
1550 if (
Opts.misched_sort_resources_in_trace)
1555 return std::tie(LHS.AcquireAtCycle, LHS.ReleaseAtCycle) <
1556 std::tie(RHS.AcquireAtCycle, RHS.ReleaseAtCycle);
1560 const std::string ResName =
1561 SchedModel.getResourceName(PI.ProcResourceIdx);
1566 for (
unsigned I = 0, E = PI.ReleaseAtCycle - PI.AcquireAtCycle;
I != E;
1569 while (
C-- >= LastCycle)
1578#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1581 if (
Opts.misched_dump_schedule_trace) {
1587 dbgs() <<
"* Schedule table (Bidirectional): not implemented\n";
1589 dbgs() <<
"* Schedule table: DumpDirection not set.\n";
1598 dbgs() <<
"Missing SUnit\n";
1623 if (!Reg.isVirtual())
1628 bool FoundDef =
false;
1630 if (MO2.getReg() == Reg && !MO2.isDead()) {
1641 for (; UI !=
VRegUses.end(); ++UI) {
1657 unsigned regioninstrs)
1671 "ShouldTrackLaneMasks requires ShouldTrackPressure");
1722 dbgs() <<
"Bottom Pressure: ";
1728 "Can't find the region bottom");
1736 unsigned Limit =
RegClassInfo->getRegPressureSetLimit(i);
1745 dbgs() <<
"Excess PSets: ";
1747 dbgs() <<
TRI->getRegPressureSetName(RCPS.getPSet()) <<
" ";
1755 const std::vector<unsigned> &NewMaxPressure) {
1761 unsigned ID = PC.getPSet();
1766 && NewMaxPressure[ID] <= (
unsigned)std::numeric_limits<int16_t>::max())
1769 unsigned Limit =
RegClassInfo->getRegPressureSetLimit(ID);
1770 if (NewMaxPressure[ID] >= Limit - 2) {
1772 << NewMaxPressure[ID]
1773 << ((NewMaxPressure[ID] > Limit) ?
" > " :
" <= ")
1785 if (!
P.VRegOrUnit.isVirtualReg())
1787 Register Reg =
P.VRegOrUnit.asVirtualReg();
1794 bool Decrement =
P.LaneMask.any();
1798 SUnit &SU = *V2SU.SU;
1808 <<
" UpdateRegPressure: " << SU <<
" "
1831 assert(VNI &&
"No live value at use.");
1834 SUnit *SU = V2SU.SU;
1858#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1859 if (
EntrySU.getInstr() !=
nullptr)
1864 dbgs() <<
" Pressure Diff : ";
1867 dbgs() <<
" Single Issue : ";
1868 if (
SchedModel.mustBeginGroup(SU.getInstr()) &&
1875 if (
ExitSU.getInstr() !=
nullptr)
1913 bool IsTopNode =
false;
1918 LLVM_DEBUG(
dbgs() <<
"** ScheduleDAGMILive::schedule picking next node\n");
1927 unsigned SubtreeID =
DFSResult->getSubtreeID(SU);
1945 dbgs() <<
"*** Final schedule for "
2014 if (!
BB->isSuccessor(
BB))
2017 unsigned MaxCyclicLatency = 0;
2020 if (!
P.VRegOrUnit.isVirtualReg())
2022 Register Reg =
P.VRegOrUnit.asVirtualReg();
2033 unsigned LiveOutHeight = DefSU->
getHeight();
2038 SUnit *SU = V2SU.SU;
2050 unsigned CyclicLatency = 0;
2052 CyclicLatency = LiveOutDepth - SU->
getDepth();
2055 if (LiveInHeight > LiveOutHeight) {
2056 if (LiveInHeight - LiveOutHeight < CyclicLatency)
2057 CyclicLatency = LiveInHeight - LiveOutHeight;
2061 LLVM_DEBUG(
dbgs() <<
"Cyclic Path: " << *DefSU <<
" -> " << *SU <<
" = "
2062 << CyclicLatency <<
"c\n");
2063 if (CyclicLatency > MaxCyclicLatency)
2064 MaxCyclicLatency = CyclicLatency;
2067 LLVM_DEBUG(
dbgs() <<
"Cyclic Critical Path: " << MaxCyclicLatency <<
"c\n");
2068 return MaxCyclicLatency;
2120 if (&*priorII ==
MI)
2171 bool OffsetIsScalable;
2175 : SU(SU), BaseOps(BaseOps),
Offset(
Offset), Width(Width),
2176 OffsetIsScalable(OffsetIsScalable) {}
2180 if (
A->getType() !=
B->getType())
2181 return A->getType() <
B->getType();
2183 return A->getReg() <
B->getReg();
2195 if (AIsFixed != BIsFixed)
2196 return StackGrowsDown ? !AIsFixed : AIsFixed;
2204 if (AOffset != BOffset)
2205 return AOffset < BOffset;
2207 return StackGrowsDown ?
A->getIndex() >
B->getIndex()
2208 :
A->getIndex() <
B->getIndex();
2218 if (std::lexicographical_compare(BaseOps.
begin(), BaseOps.
end(),
2219 RHS.BaseOps.begin(),
RHS.BaseOps.end(),
2222 if (std::lexicographical_compare(
RHS.BaseOps.begin(),
RHS.BaseOps.end(),
2223 BaseOps.
begin(), BaseOps.
end(), Compare))
2233 enum class MemOpRelationship {
2240 const TargetInstrInfo *
TII;
2242 bool ReorderWhileClustering;
2245 BaseMemOpClusterMutation(
const TargetInstrInfo *tii,
bool IsLoad,
2246 bool ReorderWhileClustering)
2247 :
TII(tii), IsLoad(IsLoad),
2248 ReorderWhileClustering(ReorderWhileClustering) {}
2250 void apply(ScheduleDAGInstrs *DAGInstrs)
override;
2253 MemOpRelationship computeRelationship(ScheduleDAGInstrs *DAG, SUnit *SUa,
2258 ScheduleDAGInstrs *DAG);
2259 void collectMemOpRecords(std::vector<SUnit> &SUnits,
2260 SmallVectorImpl<MemOpInfo> &MemOpRecords);
2265class StoreClusterMutation :
public BaseMemOpClusterMutation {
2267 StoreClusterMutation(
const TargetInstrInfo *tii,
bool ReorderWhileClustering)
2268 : BaseMemOpClusterMutation(tii,
false, ReorderWhileClustering) {}
2271class LoadClusterMutation :
public BaseMemOpClusterMutation {
2273 LoadClusterMutation(
const TargetInstrInfo *tii,
bool ReorderWhileClustering)
2274 : BaseMemOpClusterMutation(tii,
true, ReorderWhileClustering) {}
2279std::unique_ptr<ScheduleDAGMutation>
2281 bool ReorderWhileClustering) {
2282 return std::make_unique<LoadClusterMutation>(
TII, ReorderWhileClustering);
2285std::unique_ptr<ScheduleDAGMutation>
2287 bool ReorderWhileClustering) {
2288 return std::make_unique<StoreClusterMutation>(
TII, ReorderWhileClustering);
2291BaseMemOpClusterMutation::MemOpRelationship
2297 if (!BReachesA && !AReachesB)
2298 return MemOpRelationship::Unrelated;
2307 assert(!AReachesB &&
"Cycle detected");
2319 return MemOpRelationship::UnsafePath;
2324 return MemOpRelationship::UnsafePath;
2327 return Reverse ? MemOpRelationship::ReverseOrd : MemOpRelationship::DirectOrd;
2335void BaseMemOpClusterMutation::clusterNeighboringMemOps(
2344 for (
unsigned Idx = 0,
End = MemOpRecords.
size(); Idx < (
End - 1); ++Idx) {
2346 auto MemOpa = MemOpRecords[
Idx];
2347 MemOpRelationship Relationship = MemOpRelationship::UnsafePath;
2350 unsigned NextIdx =
Idx + 1;
2351 for (; NextIdx <
End; ++NextIdx) {
2353 if (SUnit2ClusterInfo.
count(MemOpRecords[NextIdx].SU->NodeNum))
2359 Relationship = MemOpRelationship::Unrelated;
2364 computeRelationship(DAG, MemOpa.SU, MemOpRecords[NextIdx].SU);
2365 if (Relationship != MemOpRelationship::UnsafePath)
2372 auto MemOpb = MemOpRecords[NextIdx];
2373 unsigned ClusterLength = 2;
2374 unsigned CurrentClusterBytes = MemOpa.Width.getValue().getKnownMinValue() +
2375 MemOpb.Width.getValue().getKnownMinValue();
2376 auto It = SUnit2ClusterInfo.
find(MemOpa.SU->NodeNum);
2377 if (It != SUnit2ClusterInfo.
end()) {
2378 const auto &[
Len, Bytes] = It->second;
2379 ClusterLength =
Len + 1;
2380 CurrentClusterBytes = Bytes + MemOpb.Width.getValue().getKnownMinValue();
2383 if (!
TII->shouldClusterMemOps(MemOpa.BaseOps, MemOpa.Offset,
2384 MemOpa.OffsetIsScalable, MemOpb.BaseOps,
2385 MemOpb.Offset, MemOpb.OffsetIsScalable,
2386 ClusterLength, CurrentClusterBytes))
2389 SUnit *SUa = MemOpa.SU;
2390 SUnit *SUb = MemOpb.SU;
2395 if (Relationship == MemOpRelationship::ReverseOrd ||
2396 (Relationship == MemOpRelationship::Unrelated &&
2404 "Adding an edge would create a cycle without FastCluster enabled");
2409 LLVM_DEBUG(
dbgs() <<
"Cluster ld/st " << *SUa <<
" - " << *SUb <<
"\n");
2430 if (
Pred.getSUnit() == SUa)
2437 SUnit2ClusterInfo[MemOpb.SU->NodeNum] = {ClusterLength,
2438 CurrentClusterBytes};
2441 <<
", Curr cluster bytes: " << CurrentClusterBytes
2452 unsigned ClusterIdx = AllClusters.size();
2454 MemberI->ParentClusterIdx = ClusterIdx;
2457 AllClusters.push_back(Group);
2461void BaseMemOpClusterMutation::collectMemOpRecords(
2463 for (
auto &SU : SUnits) {
2471 bool OffsetIsScalable;
2474 OffsetIsScalable, Width)) {
2479 MemOpInfo(&SU, BaseOps,
Offset, OffsetIsScalable, Width));
2482 <<
Offset <<
", OffsetIsScalable: " << OffsetIsScalable
2483 <<
", Width: " << Width <<
"\n");
2486 for (
const auto *
Op : BaseOps)
2492bool BaseMemOpClusterMutation::groupMemOps(
2495 bool FastCluster = DAG->
Opts.misched_force_fast_cluster ||
2497 DAG->
Opts.misched_fast_cluster_threshold;
2499 for (
const auto &
MemOp : MemOps) {
2500 unsigned ChainPredID = DAG->
SUnits.size();
2506 if ((
Pred.isCtrl() &&
2508 (
Pred.getSUnit() &&
Pred.getSUnit()->getInstr()->mayStore()))) &&
2509 !
Pred.isArtificial()) {
2510 ChainPredID =
Pred.getSUnit()->NodeNum;
2524 if (!DAG->
Opts.misched_cluster)
2529 collectMemOpRecords(DAG->
SUnits, MemOpRecords);
2531 if (MemOpRecords.
size() < 2)
2538 bool FastCluster = groupMemOps(MemOpRecords, DAG,
Groups);
2540 for (
auto &Group :
Groups) {
2546 clusterNeighboringMemOps(Group.second, FastCluster, DAG);
2561 SlotIndex RegionBeginIdx;
2565 SlotIndex RegionEndIdx;
2568 CopyConstrain(
const TargetInstrInfo *) {}
2570 void apply(ScheduleDAGInstrs *DAGInstrs)
override;
2573 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
2578std::unique_ptr<ScheduleDAGMutation>
2580 return std::make_unique<CopyConstrain>(
TII);
2623 unsigned LocalReg = SrcReg;
2624 unsigned GlobalReg = DstReg;
2626 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx)) {
2630 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx))
2641 if (GlobalSegment == GlobalLI->
end())
2648 if (GlobalSegment->contains(LocalLI->
beginIndex()))
2651 if (GlobalSegment == GlobalLI->
end())
2655 if (GlobalSegment != GlobalLI->
begin()) {
2658 GlobalSegment->start)) {
2669 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
2670 "Disconnected LRG within the scheduling region.");
2686 for (
const SDep &Succ : LastLocalSU->
Succs) {
2704 if (
Pred.getSUnit() == FirstLocalSU)
2712 for (
SUnit *LU : LocalUses) {
2713 LLVM_DEBUG(
dbgs() <<
" Local use SU(" << LU->NodeNum <<
") -> SU("
2714 << GlobalSU->
NodeNum <<
")\n");
2717 for (
SUnit *GU : GlobalUses) {
2718 LLVM_DEBUG(
dbgs() <<
" Global use " << *GU <<
" -> " << *FirstLocalSU
2731 if (FirstPos == DAG->
end())
2759 unsigned Latency,
bool AfterSchedNode) {
2762 return ResCntFactor >= (int)LFactor;
2764 return ResCntFactor > (int)LFactor;
2775 CheckPending =
false;
2778 MinReadyCycle = std::numeric_limits<unsigned>::max();
2779 ExpectedLatency = 0;
2780 DependentLatency = 0;
2782 MaxExecutedResCount = 0;
2784 IsResourceLimited =
false;
2785 ReservedCycles.clear();
2786 ReservedResourceSegments.clear();
2787 ReservedCyclesIndex.clear();
2788 ResourceGroupSubUnitMasks.clear();
2789#if LLVM_ENABLE_ABI_BREAKING_CHECKS
2793 MaxObservedStall = 0;
2796 ExecutedResCounts.resize(1);
2797 assert(!ExecutedResCounts[0] &&
"nonzero count for bad resource");
2813 unsigned PIdx = PI->ProcResourceIdx;
2815 assert(PI->ReleaseAtCycle >= PI->AcquireAtCycle);
2817 (Factor * (PI->ReleaseAtCycle - PI->AcquireAtCycle));
2829 unsigned ResourceCount =
SchedModel->getNumProcResourceKinds();
2830 ReservedCyclesIndex.resize(ResourceCount);
2831 ExecutedResCounts.resize(ResourceCount);
2832 ResourceGroupSubUnitMasks.resize(ResourceCount,
APInt(ResourceCount, 0));
2833 unsigned NumUnits = 0;
2835 for (
unsigned i = 0; i < ResourceCount; ++i) {
2836 ReservedCyclesIndex[i] = NumUnits;
2837 NumUnits +=
SchedModel->getProcResource(i)->NumUnits;
2839 auto SubUnits =
SchedModel->getProcResource(i)->SubUnitsIdxBegin;
2840 for (
unsigned U = 0, UE =
SchedModel->getProcResource(i)->NumUnits;
2842 ResourceGroupSubUnitMasks[i].setBit(SubUnits[U]);
2862 if (ReadyCycle > CurrCycle)
2863 return ReadyCycle - CurrCycle;
2870 unsigned ReleaseAtCycle,
2871 unsigned AcquireAtCycle) {
2874 return ReservedResourceSegments[InstanceIdx].getFirstAvailableAtFromTop(
2875 CurrCycle, AcquireAtCycle, ReleaseAtCycle);
2877 return ReservedResourceSegments[InstanceIdx].getFirstAvailableAtFromBottom(
2878 CurrCycle, AcquireAtCycle, ReleaseAtCycle);
2881 unsigned NextUnreserved = ReservedCycles[InstanceIdx];
2887 NextUnreserved = std::max(CurrCycle, NextUnreserved + ReleaseAtCycle);
2888 return NextUnreserved;
2894std::pair<unsigned, unsigned>
2896 unsigned ReleaseAtCycle,
2897 unsigned AcquireAtCycle) {
2899 dbgs() <<
" Resource booking (@" << CurrCycle <<
"c): \n";
2900 dumpReservedCycles();
2901 dbgs() <<
" getNextResourceCycle (@" << CurrCycle <<
"c): \n";
2904 unsigned InstanceIdx = 0;
2905 unsigned StartIndex = ReservedCyclesIndex[PIdx];
2906 unsigned NumberOfInstances =
SchedModel->getProcResource(PIdx)->NumUnits;
2907 assert(NumberOfInstances > 0 &&
2908 "Cannot have zero instances of a ProcResource");
2925 if (ResourceGroupSubUnitMasks[PIdx][PE.ProcResourceIdx])
2927 StartIndex, ReleaseAtCycle, AcquireAtCycle),
2930 auto SubUnits =
SchedModel->getProcResource(PIdx)->SubUnitsIdxBegin;
2931 for (
unsigned I = 0,
End = NumberOfInstances;
I <
End; ++
I) {
2932 unsigned NextUnreserved, NextInstanceIdx;
2933 std::tie(NextUnreserved, NextInstanceIdx) =
2935 if (MinNextUnreserved > NextUnreserved) {
2936 InstanceIdx = NextInstanceIdx;
2937 MinNextUnreserved = NextUnreserved;
2940 return std::make_pair(MinNextUnreserved, InstanceIdx);
2943 for (
unsigned I = StartIndex,
End = StartIndex + NumberOfInstances;
I <
End;
2945 unsigned NextUnreserved =
2948 if (
DAG->Opts.misched_detail_resource_booking)
2949 dbgs() <<
" Instance " <<
I - StartIndex <<
" available @"
2950 << NextUnreserved <<
"c\n";
2952 if (MinNextUnreserved > NextUnreserved) {
2954 MinNextUnreserved = NextUnreserved;
2958 if (
DAG->Opts.misched_detail_resource_booking)
2959 dbgs() <<
" selecting " <<
SchedModel->getResourceName(PIdx) <<
"["
2960 << InstanceIdx - StartIndex <<
"]"
2961 <<
" available @" << MinNextUnreserved <<
"c"
2964 return std::make_pair(MinNextUnreserved, InstanceIdx);
2984 <<
"hazard: " << *SU <<
" reported by HazardRec\n");
2989 if ((CurrMOps > 0) && (CurrMOps + uops >
SchedModel->getIssueWidth())) {
2991 <<
", CurrMOps = " << CurrMOps <<
", "
2992 <<
"CurrMOps + uops > issue width of "
3001 << (
isTop() ?
"begin" :
"end") <<
" group\n");
3010 unsigned ResIdx = PE.ProcResourceIdx;
3011 unsigned ReleaseAtCycle = PE.ReleaseAtCycle;
3012 unsigned AcquireAtCycle = PE.AcquireAtCycle;
3013 unsigned NRCycle, InstanceIdx;
3014 std::tie(NRCycle, InstanceIdx) =
3016 if (NRCycle > CurrCycle) {
3017#if LLVM_ENABLE_ABI_BREAKING_CHECKS
3018 MaxObservedStall = std::max(ReleaseAtCycle, MaxObservedStall);
3021 <<
"hazard: " << *SU <<
" "
3022 <<
SchedModel->getResourceName(ResIdx) <<
'['
3023 << InstanceIdx - ReservedCyclesIndex[ResIdx] <<
']' <<
"="
3024 << NRCycle <<
"c, is later than "
3025 <<
"CurrCycle = " << CurrCycle <<
"c\n");
3036 SUnit *LateSU =
nullptr;
3037 unsigned RemLatency = 0;
3038 for (
SUnit *SU : ReadySUs) {
3040 if (L > RemLatency) {
3047 << RemLatency <<
"c\n");
3061 unsigned OtherCritCount =
Rem->RemIssueCount
3062 + (RetiredMOps *
SchedModel->getMicroOpFactor());
3064 << OtherCritCount /
SchedModel->getMicroOpFactor() <<
'\n');
3065 for (
unsigned PIdx = 1, PEnd =
SchedModel->getNumProcResourceKinds();
3066 PIdx != PEnd; ++PIdx) {
3068 if (OtherCount > OtherCritCount) {
3069 OtherCritCount = OtherCount;
3070 OtherCritIdx = PIdx;
3075 dbgs() <<
" " <<
Available.getName() <<
" + Remain CritRes: "
3076 << OtherCritCount /
SchedModel->getResourceFactor(OtherCritIdx)
3077 <<
" " <<
SchedModel->getResourceName(OtherCritIdx) <<
"\n");
3079 return OtherCritCount;
3086#if LLVM_ENABLE_ABI_BREAKING_CHECKS
3090 if (ReadyCycle > CurrCycle)
3091 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
3094 if (ReadyCycle < MinReadyCycle)
3095 MinReadyCycle = ReadyCycle;
3099 bool IsBuffered =
SchedModel->getMicroOpBufferSize() != 0;
3100 bool HazardDetected = !IsBuffered && ReadyCycle > CurrCycle;
3103 <<
"hazard: " << *SU <<
" ReadyCycle = " << ReadyCycle
3104 <<
" is later than CurrCycle = " << CurrCycle
3105 <<
" on an unbuffered resource" <<
"\n");
3109 if (!HazardDetected &&
Available.size() >=
DAG->Opts.misched_limit) {
3110 HazardDetected =
true;
3115 if (!HazardDetected) {
3130 if (
SchedModel->getMicroOpBufferSize() == 0) {
3131 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
3132 "MinReadyCycle uninitialized");
3133 if (MinReadyCycle > NextCycle)
3134 NextCycle = MinReadyCycle;
3137 unsigned DecMOps =
SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
3138 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
3141 if ((NextCycle - CurrCycle) > DependentLatency)
3142 DependentLatency = 0;
3144 DependentLatency -= (NextCycle - CurrCycle);
3148 CurrCycle = NextCycle;
3151 for (; CurrCycle != NextCycle; ++CurrCycle) {
3158 CheckPending =
true;
3168 ExecutedResCounts[PIdx] +=
Count;
3169 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
3170 MaxExecutedResCount = ExecutedResCounts[PIdx];
3184 unsigned ReleaseAtCycle,
3186 unsigned AcquireAtCycle) {
3187 unsigned Factor =
SchedModel->getResourceFactor(PIdx);
3188 unsigned Count = Factor * (ReleaseAtCycle- AcquireAtCycle);
3190 << ReleaseAtCycle <<
"x" << Factor <<
"u\n");
3194 assert(
Rem->RemainingCounts[PIdx] >=
Count &&
"resource double counted");
3195 Rem->RemainingCounts[PIdx] -=
Count;
3200 ZoneCritResIdx = PIdx;
3207 unsigned NextAvailable, InstanceIdx;
3208 std::tie(NextAvailable, InstanceIdx) =
3210 if (NextAvailable > CurrCycle) {
3213 <<
'[' << InstanceIdx - ReservedCyclesIndex[PIdx] <<
']'
3214 <<
" reserved until @" << NextAvailable <<
"\n");
3216 return NextAvailable;
3226 (CurrMOps == 0 || (CurrMOps + IncMOps) <=
SchedModel->getIssueWidth()) &&
3227 "Cannot schedule this instruction's MicroOps in the current cycle.");
3232 unsigned NextCycle = CurrCycle;
3233 switch (
SchedModel->getMicroOpBufferSize()) {
3235 assert(ReadyCycle <= CurrCycle &&
"Broken PendingQueue");
3238 if (ReadyCycle > NextCycle) {
3239 NextCycle = ReadyCycle;
3240 LLVM_DEBUG(
dbgs() <<
" *** Stall until: " << ReadyCycle <<
"\n");
3249 NextCycle = ReadyCycle;
3252 RetiredMOps += IncMOps;
3256 unsigned DecRemIssue = IncMOps *
SchedModel->getMicroOpFactor();
3257 assert(
Rem->RemIssueCount >= DecRemIssue &&
"MOps double counted");
3258 Rem->RemIssueCount -= DecRemIssue;
3259 if (ZoneCritResIdx) {
3261 unsigned ScaledMOps =
3262 RetiredMOps *
SchedModel->getMicroOpFactor();
3270 << ScaledMOps /
SchedModel->getLatencyFactor()
3276 PE =
SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
3278 countResource(SC, PI->ProcResourceIdx, PI->ReleaseAtCycle, NextCycle,
3279 PI->AcquireAtCycle);
3280 if (RCycle > NextCycle)
3290 PE =
SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
3291 unsigned PIdx = PI->ProcResourceIdx;
3292 if (
SchedModel->getResourceBufferSize(PIdx) == 0) {
3295 unsigned ReservedUntil, InstanceIdx;
3297 SC, PIdx, PI->ReleaseAtCycle, PI->AcquireAtCycle);
3299 ReservedResourceSegments[InstanceIdx].add(
3301 NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
3302 DAG->Opts.misched_resource_cutoff);
3304 ReservedResourceSegments[InstanceIdx].add(
3306 NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
3307 DAG->Opts.misched_resource_cutoff);
3311 unsigned ReservedUntil, InstanceIdx;
3313 SC, PIdx, PI->ReleaseAtCycle, PI->AcquireAtCycle);
3315 ReservedCycles[InstanceIdx] =
3316 std::max(ReservedUntil, NextCycle + PI->ReleaseAtCycle);
3318 ReservedCycles[InstanceIdx] = NextCycle;
3325 unsigned &TopLatency =
isTop() ? ExpectedLatency : DependentLatency;
3326 unsigned &BotLatency =
isTop() ? DependentLatency : ExpectedLatency;
3330 <<
" " << TopLatency <<
"c\n");
3335 <<
" " << BotLatency <<
"c\n");
3338 if (NextCycle > CurrCycle)
3356 CheckPending =
true;
3363 CurrMOps += IncMOps;
3376 while (CurrMOps >=
SchedModel->getIssueWidth()) {
3377 LLVM_DEBUG(
dbgs() <<
" *** Max MOps " << CurrMOps <<
" at cycle "
3378 << CurrCycle <<
'\n');
3389 MinReadyCycle = std::numeric_limits<unsigned>::max();
3393 for (
unsigned I = 0, E =
Pending.size();
I < E; ++
I) {
3399 if (ReadyCycle < MinReadyCycle)
3400 MinReadyCycle = ReadyCycle;
3411 CheckPending =
false;
3440 for (
unsigned i = 0;
Available.empty(); ++i) {
3457#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3466 unsigned ResourceCount =
SchedModel->getNumProcResourceKinds();
3467 unsigned StartIdx = 0;
3469 for (
unsigned ResIdx = 0; ResIdx < ResourceCount; ++ResIdx) {
3470 const unsigned NumUnits =
SchedModel->getProcResource(ResIdx)->NumUnits;
3471 std::string ResName =
SchedModel->getResourceName(ResIdx);
3472 for (
unsigned UnitIdx = 0; UnitIdx < NumUnits; ++UnitIdx) {
3473 dbgs() << ResName <<
"(" << UnitIdx <<
") = ";
3475 if (ReservedResourceSegments.count(StartIdx + UnitIdx))
3476 dbgs() << ReservedResourceSegments.at(StartIdx + UnitIdx);
3480 dbgs() << ReservedCycles[StartIdx + UnitIdx] <<
"\n";
3482 StartIdx += NumUnits;
3491 if (ZoneCritResIdx) {
3492 ResFactor =
SchedModel->getResourceFactor(ZoneCritResIdx);
3496 ResCount = RetiredMOps * ResFactor;
3498 unsigned LFactor =
SchedModel->getLatencyFactor();
3500 <<
" Retired: " << RetiredMOps;
3502 dbgs() <<
"\n Critical: " << ResCount / LFactor <<
"c, "
3503 << ResCount / ResFactor <<
" "
3504 <<
SchedModel->getResourceName(ZoneCritResIdx)
3505 <<
"\n ExpectedLatency: " << ExpectedLatency <<
"c\n"
3506 << (IsResourceLimited ?
" - Resource" :
" - Latency")
3509 if (
DAG->Opts.misched_dump_reserved_cycles)
3528 PE =
SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
3529 if (PI->ProcResourceIdx ==
Policy.ReduceResIdx)
3530 ResDelta.CritResources += PI->ReleaseAtCycle;
3531 if (PI->ProcResourceIdx ==
Policy.DemandResIdx)
3532 ResDelta.DemandedResources += PI->ReleaseAtCycle;
3538bool GenericSchedulerBase::shouldReduceLatency(
const CandPolicy &Policy,
3540 bool ComputeRemLatency,
3541 unsigned &RemLatency)
const {
3551 if (ComputeRemLatency)
3567 unsigned OtherCritIdx = 0;
3568 unsigned OtherCount =
3571 bool OtherResLimited =
false;
3572 unsigned RemLatency = 0;
3573 bool RemLatencyComputed =
false;
3574 if (
SchedModel->hasInstrSchedModel() && OtherCount != 0) {
3576 RemLatencyComputed =
true;
3578 OtherCount, RemLatency,
false);
3584 if (!OtherResLimited &&
3585 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
3589 <<
" RemainingLatency " << RemLatency <<
" + "
3591 <<
Rem.CriticalPath <<
"\n");
3598 dbgs() <<
" " << CurrZone.Available.getName() <<
" ResourceLimited: "
3599 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) <<
"\n";
3600 }
if (OtherResLimited)
dbgs()
3601 <<
" RemainingLimit: "
3602 <<
SchedModel->getResourceName(OtherCritIdx) <<
"\n";
3604 <<
" Latency limited both directions.\n");
3609 if (OtherResLimited)
3618 case NoCand:
return "NOCAND ";
3619 case Only1:
return "ONLY1 ";
3620 case PhysReg:
return "PHYS-REG ";
3623 case Stall:
return "STALL ";
3624 case Cluster:
return "CLUSTER ";
3625 case Weak:
return "WEAK ";
3626 case RegMax:
return "REG-MAX ";
3642 unsigned ResIdx = 0;
3677 dbgs() <<
" " <<
TRI->getRegPressureSetName(
P.getPSet())
3678 <<
":" <<
P.getUnitInc() <<
" ";
3682 dbgs() <<
" " <<
SchedModel->getProcResource(ResIdx)->Name <<
" ";
3711 RemLatency = std::max(RemLatency,
3713 RemLatency = std::max(RemLatency,
3725 if (TryVal < CandVal) {
3729 if (TryVal > CandVal) {
3730 if (Cand.
Reason > Reason)
3741 if (TryVal > CandVal) {
3745 if (TryVal < CandVal) {
3746 if (Cand.
Reason > Reason)
3788 const bool IsTop,
const bool IsPostRA =
false) {
3789 assert(SU &&
"SU must not be null for tracing");
3790 LLVM_DEBUG(
dbgs() <<
"Pick " << (IsTop ?
"Top " :
"Bot ") <<
"Cand " << *SU
3792 << (IsPostRA ?
"post-RA" :
"pre-RA") <<
"]\n");
3811 NumRegExcessPostRA++;
3814 NumRegCriticalPostRA++;
3829 NumResourceReducePostRA++;
3832 NumResourceDemandPostRA++;
3835 NumTopDepthReducePostRA++;
3838 NumTopPathReducePostRA++;
3841 NumBotHeightReducePostRA++;
3844 NumBotPathReducePostRA++;
3847 NumNodeOrderPostRA++;
3850 NumFirstValidPostRA++;
3870 NumRegExcessPreRA++;
3873 NumRegCriticalPreRA++;
3888 NumResourceReducePreRA++;
3891 NumResourceDemandPreRA++;
3894 NumTopDepthReducePreRA++;
3897 NumTopPathReducePreRA++;
3900 NumBotHeightReducePreRA++;
3903 NumBotPathReducePreRA++;
3906 NumNodeOrderPreRA++;
3909 NumFirstValidPreRA++;
3917 const bool IsPostRA =
false) {
3923 "(PreRA)GenericScheduler needs vreg liveness");
3929 DAG->computeDFSResult();
3941 Top.HazardRec.reset(
DAG->TII->CreateTargetMIHazardRecognizer(Itin,
DAG));
3943 Bot.HazardRec.reset(
DAG->TII->CreateTargetMIHazardRecognizer(Itin,
DAG));
3963 for (
unsigned VT = MVT::i64; VT > (
unsigned)MVT::i1; --VT) {
3965 if (
TLI->isTypeLegal(LegalIntVT)) {
3966 unsigned NIntRegs =
Context->RegClassInfo->getNumAllocatableRegs(
3967 TLI->getRegClassFor(LegalIntVT));
3984 if (!Opts.misched_regpressure) {
4006#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4007 dbgs() <<
"GenericScheduler RegionPolicy: "
4008 <<
" ShouldTrackPressure=" <<
RegionPolicy.ShouldTrackPressure
4025 if (
Rem.CyclicCritPath == 0 ||
Rem.CyclicCritPath >=
Rem.CriticalPath)
4029 unsigned IterCount =
4030 std::max(
Rem.CyclicCritPath *
SchedModel->getLatencyFactor(),
4033 unsigned AcyclicCount =
Rem.CriticalPath *
SchedModel->getLatencyFactor();
4035 unsigned InFlightCount =
4036 (AcyclicCount *
Rem.RemIssueCount + IterCount-1) / IterCount;
4037 unsigned BufferLimit =
4040 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
4043 dbgs() <<
"IssueCycles="
4044 <<
Rem.RemIssueCount /
SchedModel->getLatencyFactor() <<
"c "
4045 <<
"IterCycles=" << IterCount /
SchedModel->getLatencyFactor()
4046 <<
"c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
4047 <<
" InFlight=" << InFlightCount /
SchedModel->getMicroOpFactor()
4048 <<
"m BufferLim=" <<
SchedModel->getMicroOpBufferSize() <<
"m\n";
4049 if (
Rem.IsAcyclicLatencyLimited)
dbgs() <<
" ACYCLIC LATENCY LIMIT\n");
4053 Rem.CriticalPath =
DAG->ExitSU.getDepth();
4056 for (
const SUnit *SU :
Bot.Available) {
4061 if (
DAG->Opts.misched_dcpl) {
4062 errs() <<
"Critical Path(GS-RR ): " <<
Rem.CriticalPath <<
" \n";
4065 if (
DAG->Opts.misched_cyclicpath &&
SchedModel->getMicroOpBufferSize() > 0) {
4066 Rem.CyclicCritPath =
DAG->computeCyclicCriticalPath();
4092 if (TryPSet == CandPSet) {
4097 int TryRank = TryP.
isValid() ?
TRI->getRegPressureSetScore(MF, TryPSet) :
4098 std::numeric_limits<int>::max();
4100 int CandRank = CandP.
isValid() ?
TRI->getRegPressureSetScore(MF, CandPSet) :
4101 std::numeric_limits<int>::max();
4106 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
4124 unsigned ScheduledOper = isTop ? 1 : 0;
4125 unsigned UnscheduledOper = isTop ? 0 : 1;
4128 if (
MI->getOperand(ScheduledOper).getReg().isPhysical())
4133 if (
MI->getOperand(UnscheduledOper).getReg().isPhysical())
4134 return AtBoundary ? -1 : 1;
4137 if (
MI->isMoveImmediate()) {
4143 if (
Op.isReg() && !
Op.getReg().isPhysical()) {
4150 return isTop ? -1 : 1;
4153 if (BiasPRegsExtra && !isTop &&
MI->getNumExplicitDefs() == 1)
4156 return MI->getOperand(0).getReg().isPhysical();
4166 if (
tryGreater(TryCandPRegBias, CandPRegBias, TryCand, Cand,
4169 if (BiasPRegsExtra && Zone !=
nullptr && TryCandPRegBias &&
4170 TryCandPRegBias == CandPRegBias) {
4189 if (
DAG->isTrackingPressure()) {
4194 DAG->getRegionCriticalPSets(),
4195 DAG->getRegPressure().MaxSetPressure);
4197 if (
DAG->Opts.verify_misched) {
4200 &
DAG->getPressureDiff(Cand.
SU),
4202 DAG->getRegionCriticalPSets(),
4203 DAG->getRegPressure().MaxSetPressure);
4207 DAG->getPressureDiff(Cand.
SU),
4209 DAG->getRegionCriticalPSets(),
4210 DAG->getRegPressure().MaxSetPressure);
4215 <<
" Try " << *Cand.
SU <<
" "
4263 bool SameBoundary = Zone !=
nullptr;
4286 bool CandIsClusterSucc =
4288 bool TryCandIsClusterSucc =
4291 if (
tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
4299 TryCand, Cand,
Weak))
4324 !
Rem.IsAcyclicLatencyLimited &&
tryLatency(TryCand, Cand, *Zone))
4351 for (
SUnit *SU : Q) {
4371 if (
SUnit *SU =
Bot.pickOnlyChoice()) {
4376 if (
SUnit *SU =
Top.pickOnlyChoice()) {
4393 BotCand.Policy != BotPolicy) {
4400 if (
DAG->Opts.verify_misched) {
4405 "Last pick result should correspond to re-picking right now");
4413 TopCand.Policy != TopPolicy) {
4420 if (
DAG->Opts.verify_misched) {
4425 "Last pick result should correspond to re-picking right now");
4440 IsTopNode = Cand.
AtTop;
4447 if (
DAG->top() ==
DAG->bottom()) {
4449 Bot.Available.empty() &&
Bot.Pending.empty() &&
"ReadyQ garbage");
4454 SU =
Top.pickOnlyChoice();
4467 SU =
Bot.pickOnlyChoice();
4500 Top.removeReady(SU);
4502 Bot.removeReady(SU);
4508 ++NumInstrsInSourceOrderPreRA;
4512 ++NumInstrsInSourceOrderPreRA;
4515 NumInstrsScheduledPreRA += 1;
4528 for (
SDep &Dep : Deps) {
4529 if (Dep.getKind() !=
SDep::Data || !Dep.getReg().isPhysical())
4531 SUnit *DepSU = Dep.getSUnit();
4532 if (isTop ? DepSU->
Succs.size() > 1 : DepSU->
Preds.size() > 1)
4535 if (!Copy->isCopy() && !Copy->isMoveImmediate())
4538 DAG->dumpNode(*Dep.getSUnit()));
4547 if (MO.isReg() && MO.getReg().isVirtual())
4549 bool FixUndef = !CopyVRegs.
empty();
4556 OldNext = std::next(Copy->getIterator());
4559 DAG->moveInstruction(Copy, InsertPos);
4569 if (NewIdx < OldIdx) {
4570 FixBegin = std::next(NewIt);
4572 }
else if (OldIdx < NewIdx) {
4576 for (
auto I = FixBegin;
I != FixEnd; ++
I)
4577 if (!
I->isDebugInstr())
4598 dbgs() <<
" Top Cluster: ";
4599 for (
auto *
N : *TopCluster) {
4600 DAG->dumpNodeName(*
N);
4615 dbgs() <<
" Bot Cluster: ";
4616 for (
auto *
N : *BotCluster) {
4617 DAG->dumpNodeName(*
N);
4633static MachineSchedRegistry
4654 Top.HazardRec.reset(
DAG->TII->CreateTargetMIHazardRecognizer(Itin,
DAG));
4656 Bot.HazardRec.reset(
DAG->TII->CreateTargetMIHazardRecognizer(Itin,
DAG));
4694 Rem.CriticalPath =
DAG->ExitSU.getDepth();
4697 for (
const SUnit *SU :
Bot.Available) {
4702 if (
DAG->Opts.misched_dcpl) {
4703 errs() <<
"Critical Path(PGS-RR ): " <<
Rem.CriticalPath <<
" \n";
4722 Top.getLatencyStallCycles(Cand.
SU), TryCand, Cand,
Stall))
4728 bool CandIsClusterSucc =
4730 bool TryCandIsClusterSucc =
4733 if (
tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
4766 for (
SUnit *SU : Q) {
4785 if (
SUnit *SU =
Bot.pickOnlyChoice()) {
4790 if (
SUnit *SU =
Top.pickOnlyChoice()) {
4807 BotCand.Policy != BotPolicy) {
4814 if (
DAG->Opts.verify_misched) {
4819 "Last pick result should correspond to re-picking right now");
4827 TopCand.Policy != TopPolicy) {
4834 if (
DAG->Opts.verify_misched) {
4839 "Last pick result should correspond to re-picking right now");
4854 IsTopNode = Cand.
AtTop;
4861 if (
DAG->top() ==
DAG->bottom()) {
4863 Bot.Available.empty() &&
Bot.Pending.empty() &&
"ReadyQ garbage");
4868 SU =
Bot.pickOnlyChoice();
4884 SU =
Top.pickOnlyChoice();
4905 Top.removeReady(SU);
4907 Bot.removeReady(SU);
4913 ++NumInstrsInSourceOrderPostRA;
4917 ++NumInstrsInSourceOrderPostRA;
4920 NumInstrsScheduledPostRA += 1;
4948 const BitVector *ScheduledTrees =
nullptr;
4951 ILPOrder(
bool MaxILP) : MaximizeILP(MaxILP) {}
4956 bool operator()(
const SUnit *
A,
const SUnit *
B)
const {
4959 if (SchedTreeA != SchedTreeB) {
4961 if (ScheduledTrees->
test(SchedTreeA) != ScheduledTrees->
test(SchedTreeB))
4962 return ScheduledTrees->
test(SchedTreeB);
4979class ILPScheduler :
public MachineSchedStrategy {
4980 ScheduleDAGMILive *DAG =
nullptr;
4983 std::vector<SUnit*> ReadyQ;
4986 ILPScheduler(
bool MaximizeILP) :
Cmp(MaximizeILP) {}
4988 void initialize(ScheduleDAGMI *dag)
override {
4990 DAG =
static_cast<ScheduleDAGMILive*
>(dag);
4997 void registerRoots()
override {
4999 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5006 SUnit *pickNode(
bool &IsTopNode)
override {
5007 if (ReadyQ.empty())
return nullptr;
5008 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5009 SUnit *SU = ReadyQ.back();
5019 <<
"Scheduling " << *SU->
getInstr());
5024 void scheduleTree(
unsigned SubtreeID)
override {
5025 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5030 void schedNode(SUnit *SU,
bool IsTopNode)
override {
5031 assert(!IsTopNode &&
"SchedDFSResult needs bottom-up");
5034 void releaseTopNode(SUnit *)
override { }
5036 void releaseBottomNode(SUnit *SU)
override {
5037 ReadyQ.push_back(SU);
5038 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5065template<
bool IsReverse>
5069 return A->NodeNum >
B->NodeNum;
5071 return A->NodeNum <
B->NodeNum;
5076class InstructionShuffler :
public MachineSchedStrategy {
5083 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
5087 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
5091 InstructionShuffler(
bool alternate,
bool topdown)
5092 : IsAlternating(alternate), IsTopDown(topdown) {}
5102 SUnit *pickNode(
bool &IsTopNode)
override {
5106 if (TopQ.empty())
return nullptr;
5113 if (BottomQ.empty())
return nullptr;
5120 IsTopDown = !IsTopDown;
5124 void schedNode(SUnit *SU,
bool IsTopNode)
override {}
5126 void releaseTopNode(SUnit *SU)
override {
5129 void releaseBottomNode(SUnit *SU)
override {
5143 C, std::make_unique<InstructionShuffler>(Alternate, TopDown));
5147 "shuffle",
"Shuffle machine instructions alternating directions",
5155#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
5162struct llvm::DOTGraphTraits<ScheduleDAGMI *> :
public DefaultDOTGraphTraits {
5163 DOTGraphTraits(
bool isSimple =
false) : DefaultDOTGraphTraits(
isSimple) {}
5165 static std::string getGraphName(
const ScheduleDAG *
G) {
5166 return std::string(
G->MF.getName());
5169 static bool renderGraphFromBottomUp() {
5173 static bool isNodeHidden(
const SUnit *Node,
const ScheduleDAG *
G) {
5177 return Node->Preds.size() > Cutoff ||
Node->Succs.size() > Cutoff;
5182 static std::string getEdgeAttributes(
const SUnit *Node,
5184 const ScheduleDAG *
Graph) {
5186 return "color=cyan,style=dashed";
5188 return "color=blue,style=dashed";
5192 static std::string
getNodeLabel(
const SUnit *SU,
const ScheduleDAG *
G) {
5194 raw_string_ostream
SS(Str);
5195 const ScheduleDAGMI *DAG =
static_cast<const ScheduleDAGMI*
>(
G);
5197 static_cast<const ScheduleDAGMILive*
>(
G)->getDFSResult() :
nullptr;
5204 static std::string getNodeDescription(
const SUnit *SU,
const ScheduleDAG *
G) {
5205 return G->getGraphNodeLabel(SU);
5208 static std::string getNodeAttributes(
const SUnit *
N,
const ScheduleDAG *
G) {
5209 std::string Str(
"shape=Mrecord");
5210 const ScheduleDAGMI *DAG =
static_cast<const ScheduleDAGMI*
>(
G);
5212 static_cast<const ScheduleDAGMILive*
>(
G)->getDFSResult() :
nullptr;
5214 Str +=
",style=filled,fillcolor=\"#";
5227#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
5230 errs() <<
"ScheduleDAGMI::viewGraph is only available in debug builds on "
5231 <<
"systems with Graphviz or gv!\n";
5246 return A.first <
B.first;
5249unsigned ResourceSegments::getFirstAvailableAt(
5250 unsigned CurrCycle,
unsigned AcquireAtCycle,
unsigned ReleaseAtCycle,
5252 IntervalBuilder)
const {
5254 "Cannot execute on an un-sorted set of intervals.");
5258 if (AcquireAtCycle == ReleaseAtCycle)
5261 unsigned RetCycle = CurrCycle;
5263 IntervalBuilder(RetCycle, AcquireAtCycle, ReleaseAtCycle);
5264 for (
auto &
Interval : _Intervals) {
5271 "Invalid intervals configuration.");
5272 RetCycle += (unsigned)
Interval.second - (
unsigned)NewInterval.first;
5273 NewInterval = IntervalBuilder(RetCycle, AcquireAtCycle, ReleaseAtCycle);
5279 const unsigned CutOff) {
5280 assert(
A.first <=
A.second &&
"Cannot add negative resource usage");
5281 assert(CutOff > 0 &&
"0-size interval history has no use.");
5287 if (
A.first ==
A.second)
5294 "A resource is being overwritten");
5295 _Intervals.push_back(
A);
5301 while (_Intervals.size() > CutOff)
5302 _Intervals.pop_front();
5307 assert(
A.first <=
A.second &&
"Invalid interval");
5308 assert(
B.first <=
B.second &&
"Invalid interval");
5311 if ((
A.first ==
B.first) || (
A.second ==
B.second))
5316 if ((
A.first >
B.first) && (
A.second <
B.second))
5321 if ((
A.first >
B.first) && (
A.first <
B.second) && (
A.second >
B.second))
5326 if ((
A.first <
B.first) && (
B.first <
A.second) && (
B.second >
B.first))
5332void ResourceSegments::sortAndMerge() {
5333 if (_Intervals.size() <= 1)
5340 auto next = std::next(std::begin(_Intervals));
5341 auto E = std::end(_Intervals);
5342 for (; next != E; ++next) {
5343 if (std::prev(next)->second >= next->first) {
5344 next->first = std::prev(next)->first;
5345 _Intervals.erase(std::prev(next));
MachineInstrBuilder MachineInstrBuilder & DefMI
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
static const Function * getParent(const Value *V)
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static std::optional< ArrayRef< InsnRange >::iterator > intersects(const MachineInstr *StartMI, const MachineInstr *EndMI, ArrayRef< InsnRange > Ranges, const InstructionOrdering &Ordering)
Check if the instruction range [StartMI, EndMI] intersects any instruction range in Ranges.
This file defines the DenseMap class.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
const HexagonInstrInfo * TII
A common definition of LaneBitmask for use in TableGen and CodeGen.
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.
static MachineSchedRegistry ILPMaxRegistry("ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler)
PostRA Machine Instruction Scheduler
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.
static const unsigned MinSubtreeSize
static const unsigned InvalidCycle
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.
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.
static MachineSchedRegistry GenericSchedRegistry("converge", "Standard converging scheduler.", createConvergingSched)
static cl::opt< TargetSubtargetInfo::AntiDepBreakMode > PostRABreakAntiDeps("misched-postra-break-antideps", cl::Hidden, cl::desc("Set the post-RA MISched anti-dependency break mode"), cl::init(TargetSubtargetInfo::ANTIDEP_NONE), cl::values(clEnumValN(TargetSubtargetInfo::ANTIDEP_NONE, "none", "No anti-dependency breaking"), clEnumValN(TargetSubtargetInfo::ANTIDEP_CRITICAL, "critical", "Break critical-path anti-dependencies"), clEnumValN(TargetSubtargetInfo::ANTIDEP_ALL, "all", "Break all anti-dependencies")))
static bool checkResourceLimit(unsigned LFactor, unsigned Count, unsigned Latency, bool AfterSchedNode)
Given a Count of resource usage and a Latency value, return true if a SchedBoundary becomes resource ...
static ScheduleDAGInstrs * createInstructionShuffler(MachineSchedContext *C)
static ScheduleDAGInstrs * useDefaultMachineSched(MachineSchedContext *C)
A dummy default scheduler factory indicates whether the scheduler is overridden on the command line.
static bool sortIntervals(const ResourceSegments::IntervalTy &A, const ResourceSegments::IntervalTy &B)
Sort predicate for the intervals stored in an instance of ResourceSegments.
static MachineSchedRegistry DefaultSchedRegistry("default", "Use the target's default scheduler choice.", useDefaultMachineSched)
static const char * scheduleTableLegend
static ScheduleDAGInstrs * createConvergingSched(MachineSchedContext *C)
static MachineSchedRegistry ShufflerRegistry("shuffle", "Shuffle machine instructions alternating directions", createInstructionShuffler)
static void tracePick(const SUnit *SU, const GenericSchedulerBase::CandReason Reason, const bool IsTop, const bool IsPostRA=false)
static void getSchedRegions(MachineBasicBlock *MBB, MBBRegionsVector &Regions, bool RegionsTopDown)
static ScheduleDAGInstrs * createILPMaxScheduler(MachineSchedContext *C)
SmallVector< SchedRegion, 16 > MBBRegionsVector
static ScheduleDAGInstrs * createILPMinScheduler(MachineSchedContext *C)
static MachineSchedRegistry ILPMinRegistry("ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler)
Register const TargetRegisterInfo * TRI
std::pair< uint64_t, uint64_t > Interval
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the PriorityQueue class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
static const X86InstrFMA3Group Groups[]
Class recording the (high level) value of a variable.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
std::vector< std::pair< MachineInstr *, MachineInstr * > > DbgValueVector
void startBlock(MachineBasicBlock *MBB)
bool breakAntiDependencies(const std::vector< SUnit > &SUnits, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, AntiDepBreaker::DbgValueVector &DbgValues)
void exitRegion(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
AntiDepState(MachineSchedContext *C, TargetSubtargetInfo::AntiDepBreakMode AntiDepMode)
void enterRegion(MachineBasicBlock::iterator End)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
reverse_iterator rend() const
size_t size() const
Get the array size.
reverse_iterator rbegin() const
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Represents analyses that only rely on functions' control flow.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
The EquivalenceClasses data structure is just a set of these.
This represents a collection of equivalence classes and supports three efficient operations: insert a...
iterator_range< member_iterator > members(const ECValue &ECV) const
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
Merge the two equivalence sets for the specified values, inserting them if they do not already exist ...
void traceCandidate(const SchedCandidate &Cand)
LLVM_ABI 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...
MachineSchedPolicy RegionPolicy
const TargetSchedModel * SchedModel
static const char * getReasonStr(GenericSchedulerBase::CandReason Reason)
const MachineSchedContext * Context
CandReason
Represent the type of SchedCandidate found within a single queue.
const TargetRegisterInfo * TRI
void checkAcyclicLatency()
Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic critical path by more cycle...
SchedCandidate BotCand
Candidate last picked from Bot boundary.
SchedCandidate TopCand
Candidate last picked from Top boundary.
virtual bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const
Apply a set of heuristics to a new candidate.
void dumpPolicy() const override
void initialize(ScheduleDAGMI *dag) override
Initialize the strategy after building the DAG for a new region.
void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, RegPressureTracker &TempTracker)
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs) override
Initialize the per-region scheduling policy.
void reschedulePhysReg(SUnit *SU, bool isTop)
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.
bool shouldTrackLaneMasks() const override
Returns true if lanemasks should be tracked.
void schedNode(SUnit *SU, bool IsTopNode) override
Update the scheduler's state after scheduling a node.
SUnit * pickNodeBidirectional(bool &IsTopNode)
Pick the best candidate node from either the top or bottom queue.
bool getMemOperandsWithOffsetWidth(const MachineInstr &LdSt, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const override
Get the base register and byte offset of a load/store instr.
Itinerary data supplied by a subtarget to be used by a target.
LiveInterval - This class represents the liveness of a register, or stack slot.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
Result of a LiveRange query.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
Segments::iterator iterator
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
bool isLocal(SlotIndex Start, SlotIndex End) const
True iff this segment is a single segment that lies between the specified boundaries,...
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
static LocationSize precise(uint64_t Value)
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
nonconst_iterator getNonConstIterator() const
Representation of each machine instruction.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
MachinePassRegistry - Track the registration of machine passes.
MachineSchedRegistry provides a selection of available machine instruction schedulers.
static LLVM_ABI MachinePassRegistry< ScheduleDAGCtor > Registry
ScheduleDAGInstrs *(*)(MachineSchedContext *) ScheduleDAGCtor
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI MachineSchedulerPass(const TargetMachine *TM)
LLVM_ABI ~MachineSchedulerPass()
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs) override
Optionally override the per-region scheduling policy.
virtual bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand)
Apply a set of heuristics to a new candidate for PostRA scheduling.
void schedNode(SUnit *SU, bool IsTopNode) override
Called after ScheduleDAGMI has scheduled an instruction and updated scheduled/remaining flags in the ...
SchedCandidate BotCand
Candidate last picked from Bot boundary.
void pickNodeFromQueue(SchedBoundary &Zone, SchedCandidate &Cand)
void initialize(ScheduleDAGMI *Dag) override
Initialize the strategy after building the DAG for a new region.
SchedCandidate TopCand
Candidate last picked from Top boundary.
SUnit * pickNodeBidirectional(bool &IsTopNode)
Pick the best candidate node from either the top or bottom queue.
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
SUnit * pickNode(bool &IsTopNode) override
Pick the next node to schedule.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PostMachineSchedulerPass(const TargetMachine *TM)
LLVM_ABI ~PostMachineSchedulerPass()
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Capture a change in pressure for a single pressure set.
unsigned getPSetOrMax() const
List of PressureChanges in order of increasing, unique PSetID.
LLVM_ABI void dump(const TargetRegisterInfo &TRI) const
LLVM_ABI void addPressureChange(VirtRegOrUnit VRegOrUnit, bool IsDec, const MachineRegisterInfo *MRI)
Add a change in pressure to the pressure diff of a given instruction.
void clear()
clear - Erase all elements from the queue.
Helpers for implementing custom MachineSchedStrategy classes.
ArrayRef< SUnit * > elements()
LLVM_ABI void dump() const
std::vector< SUnit * >::iterator iterator
StringRef getName() const
Track the current register pressure at some position in the instruction stream, and remember the high...
LLVM_ABI 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.
LLVM_ABI void getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction top-down.
LLVM_ABI 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...
List of registers defined and used by a machine instruction.
LLVM_ABI void detectDeadDefs(const MachineInstr &MI, LiveIntervals &LIS, const MachineRegisterInfo &MRI)
Use liveness information to find dead defs at MI's dead slot not marked with a dead flag and move the...
LLVM_ABI void adjustLaneLiveness(LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos)
Use liveness information to find out which uses/defs are partially undefined/dead at Pos and adjust t...
LLVM_ABI 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...
static LLVM_ABI void restoreLivenessFlags(MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, LiveIntervals &LIS, bool TrackLaneMasks=true, ArrayRef< Register > OnlyRegs={})
Clear potentially-stale read-undef flags on the defs of MI, then recompute them from LIS.
RegisterPassParser class - Handle the addition of new machine passes.
Wrapper class representing virtual and physical registers.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
LLVM_ABI void add(IntervalTy A, const unsigned CutOff=10)
Adds an interval [a, b) to the collection of the instance.
static IntervalTy getResourceIntervalBottom(unsigned C, unsigned AcquireAtCycle, unsigned ReleaseAtCycle)
These function return the interval used by a resource in bottom and top scheduling.
static LLVM_ABI bool intersects(IntervalTy A, IntervalTy B)
Checks whether intervals intersect.
std::pair< int64_t, int64_t > IntervalTy
Represents an interval of discrete integer values closed on the left and open on the right: [a,...
static IntervalTy getResourceIntervalTop(unsigned C, unsigned AcquireAtCycle, unsigned ReleaseAtCycle)
Kind getKind() const
Returns an enum value representing the kind of the dependence.
@ Anti
A register anti-dependence (aka WAR).
@ Data
Regular data dependence (aka true-dependence).
bool isWeak() const
Tests if this a weak dependence.
@ Cluster
Weak DAG edge linking a chain of clustered instrs.
@ Artificial
Arbitrary strong DAG edge (no real dependence).
@ Weak
Arbitrary weak DAG edge.
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
Register getReg() const
Returns the register associated with this edge.
bool isNormalMemoryOrBarrier() const
Tests if this is could be any kind of memory dependence.
LLVM_ABI ~SSAMachineSchedulerPass()
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI SSAMachineSchedulerPass(const TargetMachine *TM)
bool isArtificialDep() const
bool isCtrlDep() const
Tests if this is not an SDep::Data dependence.
Scheduling unit. This is a node in the scheduling DAG.
bool isCall
Is a function call.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
bool isUnbuffered
Uses an unbuffered resource.
unsigned getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
unsigned short Latency
Node latency.
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...
bool isScheduled
True once scheduled.
unsigned ParentClusterIdx
The parent cluster id.
bool hasPhysRegDefs
Has physreg defs that are being used.
unsigned BotReadyCycle
Cycle relative to end when node is ready.
SmallVector< SDep, 4 > Succs
All sunit successors.
bool hasReservedResource
Uses a reserved resource.
bool isBottomReady() const
bool hasPhysRegUses
Has physreg uses.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Each Scheduling boundary is associated with ready queues.
LLVM_ABI unsigned getNextResourceCycleByInstance(unsigned InstanceIndex, unsigned ReleaseAtCycle, unsigned AcquireAtCycle)
Compute the next cycle at which the given processor resource unit can be scheduled.
LLVM_ABI void releasePending()
Release pending ready nodes in to the available queue.
unsigned getDependentLatency() const
bool isReservedGroup(unsigned PIdx) const
unsigned getScheduledLatency() const
Get the number of latency cycles "covered" by the scheduled instructions.
LLVM_ABI void incExecutedResources(unsigned PIdx, unsigned Count)
bool isResourceLimited() const
const TargetSchedModel * SchedModel
unsigned getExecutedCount() const
Get a scaled count for the minimum execution time of the scheduled micro-ops that are ready to execut...
LLVM_ABI unsigned getLatencyStallCycles(SUnit *SU)
Get the difference between the given SUnit's ready time and the current cycle.
LLVM_ABI unsigned findMaxLatency(ArrayRef< SUnit * > ReadySUs)
LLVM_ABI void dumpReservedCycles() const
Dump the state of the information that tracks resource usage.
LLVM_ABI unsigned getOtherResourceCount(unsigned &OtherCritIdx)
LLVM_ABI void bumpNode(SUnit *SU)
Move the boundary of scheduled code by one SUnit.
unsigned getCriticalCount() const
Get the scaled count of scheduled micro-ops and resources, including executed resources.
LLVM_ABI SUnit * pickOnlyChoice()
Call this before applying any other heuristics to the Available queue.
LLVM_ABI void releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue, unsigned Idx=0)
Release SU to make it ready.
LLVM_ABI unsigned countResource(const MCSchedClassDesc *SC, unsigned PIdx, unsigned Cycles, unsigned ReadyCycle, unsigned StartAtCycle)
Add the given processor resource to this scheduled zone.
LLVM_ABI ~SchedBoundary()
LLVM_ABI void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem)
unsigned getResourceCount(unsigned ResIdx) const
LLVM_ABI void bumpCycle(unsigned NextCycle)
Move the boundary of scheduled code by one cycle.
unsigned getCurrMOps() const
Micro-ops issued in the current cycle.
unsigned getCurrCycle() const
Number of cycles to issue the instructions scheduled in this zone.
std::unique_ptr< ScheduleHazardRecognizer > HazardRec
LLVM_ABI bool checkHazard(SUnit *SU)
Does this SU have a hazard within the current instruction group.
LLVM_ABI std::pair< unsigned, unsigned > getNextResourceCycle(const MCSchedClassDesc *SC, unsigned PIdx, unsigned ReleaseAtCycle, unsigned AcquireAtCycle)
Compute the next cycle at which the given processor resource can be scheduled.
LLVM_ABI void dumpScheduledState() const
LLVM_ABI void removeReady(SUnit *SU)
Remove SU from the ready set for this boundary.
unsigned getZoneCritResIdx() const
unsigned getUnscheduledLatency(SUnit *SU) const
Compute the values of each DAG node for various metrics during DFS.
unsigned getNumInstrs(const SUnit *SU) const
Get the number of instructions in the given subtree and its children.
unsigned getSubtreeID(const SUnit *SU) const
Get the ID of the subtree the given DAG node belongs to.
ILPValue getILP(const SUnit *SU) const
Get the ILP value for a DAG node.
unsigned getSubtreeLevel(unsigned SubtreeID) const
Get the connection level of a subtree.
A ScheduleDAG for scheduling lists of MachineInstr.
SmallVector< ClusterInfo > & getClusters()
Returns the array of the clusters.
virtual void finishBlock()
Cleans up after scheduling in the given block.
MachineBasicBlock::iterator end() const
Returns an iterator to the bottom of the current scheduling region.
std::string getDAGName() const override
Returns a label for the region of code covered by the DAG.
MachineBasicBlock * BB
The block in which to insert instructions.
MachineInstr * FirstDbgValue
virtual void startBlock(MachineBasicBlock *BB)
Prepares to perform scheduling in the given block.
const CodeGenOptions & Opts
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
DbgValueVector DbgValues
Remember instruction that precedes DBG_VALUE.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
DumpDirection
The direction that should be used to dump the scheduled Sequence.
bool TrackLaneMasks
Whether lane masks should get tracked.
void dumpNode(const SUnit &SU) const override
bool IsReachable(SUnit *SU, SUnit *TargetSU)
IsReachable - Checks if SU is reachable from TargetSU.
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
void buildSchedGraph(AAResults *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
TargetSchedModel SchedModel
TargetSchedModel provides an interface to the machine model.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
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 dump() const override
void setDumpDirection(DumpDirection D)
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
void scheduleMI(SUnit *SU, bool IsTopNode)
Move an instruction and update register pressure.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
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.
PressureDiff & getPressureDiff(const SUnit *SU)
SchedDFSResult * DFSResult
Information about DAG subtrees.
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
void initQueues(ArrayRef< SUnit * > TopRoots, ArrayRef< SUnit * > BotRoots)
Release ExitSU predecessors and setup scheduler queues.
bool ShouldTrackLaneMasks
RegPressureTracker BotRPTracker
void buildDAGWithRegPressure()
Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking enabled.
std::vector< PressureChange > RegionCriticalPSets
List of pressure sets that exceed the target's pressure limit before scheduling, listed in increasing...
void updateScheduledPressure(const SUnit *SU, const std::vector< unsigned > &NewMaxPressure)
PressureDiffs SUPressureDiffs
unsigned computeCyclicCriticalPath()
Compute the cyclic critical path through the DAG.
void updatePressureDiffs(ArrayRef< VRegMaskOrUnit > LiveUses)
Update the PressureDiff array for liveness after scheduling this instruction.
void collectVRegUses(SUnit &SU)
RegisterClassInfo * RegClassInfo
const SchedDFSResult * getDFSResult() const
Return a non-null DFS result if the scheduling strategy initialized it.
RegPressureTracker RPTracker
bool ShouldTrackPressure
Register pressure in this region computed by initRegPressure.
~ScheduleDAGMILive() override
void dump() const override
BitVector & getScheduledTrees()
MachineBasicBlock::iterator LiveRegionEnd
RegPressureTracker TopRPTracker
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void dumpSchedule() const
dump the scheduled Sequence.
std::unique_ptr< MachineSchedStrategy > SchedImpl
void exitRegion() override
Called when the scheduler has finished scheduling the current region.
void startBlock(MachineBasicBlock *bb) override
Prepares to perform scheduling in the given block.
void releasePred(SUnit *SU, SDep *PredEdge)
ReleasePred - Decrement the NumSuccsLeft count of a predecessor.
void initQueues(ArrayRef< SUnit * > TopRoots, ArrayRef< SUnit * > BotRoots)
Release ExitSU predecessors and setup scheduler queues.
void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos)
Change the position of an instruction within the basic block and update live ranges and region bounda...
void releasePredecessors(SUnit *SU)
releasePredecessors - Call releasePred on each of SU's predecessors.
void postProcessDAG()
Apply each ScheduleDAGMutation step in order.
void dumpScheduleTraceTopDown() const
Print execution trace of the schedule top-down or bottom-up.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
AntiDepState AntiDep
State for optional post-RA anti-dependency breaking.
void findRootsAndBiasEdges(SmallVectorImpl< SUnit * > &TopRoots, SmallVectorImpl< SUnit * > &BotRoots)
MachineBasicBlock::iterator CurrentBottom
The bottom of the unscheduled zone.
virtual bool hasVRegLiveness() const
Return true if this DAG supports VReg liveness and RegPressure.
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
LiveIntervals * getLIS() const
void viewGraph(const Twine &Name, const Twine &Title) override
viewGraph - Pop up a ghostview window with the reachable parts of the DAG rendered using 'dot'.
void viewGraph() override
Out-of-line implementation with no arguments is handy for gdb.
void releaseSucc(SUnit *SU, SDep *SuccEdge)
ReleaseSucc - Decrement the NumPredsLeft count of a successor.
void dumpScheduleTraceBottomUp() const
~ScheduleDAGMI() override
void finishBlock() override
Cleans up after scheduling in the given block.
void updateQueues(SUnit *SU, bool IsTopNode)
Update scheduler DAG and queues after scheduling an instruction.
void placeDebugValues()
Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
MachineBasicBlock::iterator CurrentTop
The top of the unscheduled zone.
void releaseSuccessors(SUnit *SU)
releaseSuccessors - Call releaseSucc on each of SU's successors.
std::vector< std::unique_ptr< ScheduleDAGMutation > > Mutations
Ordered list of DAG postprocessing steps.
Mutate the DAG as a postpass after normal DAG building.
MachineRegisterInfo & MRI
Virtual/real register map.
std::vector< SUnit > SUnits
The scheduling units.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
void dumpNodeAll(const SUnit &SU) const
void dumpNodeName(const SUnit &SU) const
SUnit ExitSU
Special node for the region exit.
SlotIndex - An opaque wrapper around machine indexes.
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
std::reverse_iterator< const_iterator > const_reverse_iterator
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator_base< SparseMultiSet * > iterator
Information about stack frame layout on the target.
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
TargetInstrInfo - Interface to description of machine instruction set.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
unsigned getMicroOpFactor() const
Multiply number of micro-ops by this factor to normalize it relative to other resources.
ProcResIter getWriteProcResEnd(const MCSchedClassDesc *SC) const
LLVM_ABI bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model.
const MCWriteProcResEntry * ProcResIter
unsigned getResourceFactor(unsigned ResIdx) const
Multiply the number of units consumed for a resource by this factor to normalize it relative to other...
LLVM_ABI unsigned getNumMicroOps(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return the number of issue slots required for this MI.
unsigned getNumProcResourceKinds() const
Get the number of kinds of resources for this target.
ProcResIter getWriteProcResBegin(const MCSchedClassDesc *SC) const
enum { ANTIDEP_NONE, ANTIDEP_CRITICAL, ANTIDEP_ALL } AntiDepBreakMode
virtual void overridePostRASchedPolicy(MachineSchedPolicy &Policy, const SchedRegion &Region) const
Override generic post-ra scheduling policy within a region.
virtual void overrideSchedPolicy(MachineSchedPolicy &Policy, const SchedRegion &Region) const
Override generic scheduling policy within a region.
virtual bool enableMachineScheduler() const
True if the subtarget should run MachineScheduler after aggressive coalescing.
virtual bool enableSSAMachineScheduler() const
True if the subtarget should run a machine scheduler before PHI elimination.
virtual bool enablePostRAMachineScheduler() const
True if the subtarget should run a machine scheduler after register allocation.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Wrapper class representing a virtual register or register unit.
Base class for the machine scheduler classes.
void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags)
Main driver for both MachineScheduler and PostMachineScheduler.
Impl class for MachineScheduler.
void setMFAM(MachineFunctionAnalysisManager *MFAM)
void setLegacyPass(MachineFunctionPass *P)
bool run(MachineFunction &MF, const TargetMachine &TM, const RequiredAnalyses &Analyses)
MachineSchedulerImpl()=default
ScheduleDAGInstrs * createMachineScheduler()
Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Impl class for PostMachineScheduler.
bool run(MachineFunction &Func, const TargetMachine &TM, const RequiredAnalyses &Analyses)
void setMFAM(MachineFunctionAnalysisManager *MFAM)
ScheduleDAGInstrs * createPostMachineScheduler()
Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by the caller.
void setLegacyPass(MachineFunctionPass *P)
PostMachineSchedulerImpl()=default
Impl class for SSAMachineScheduler.
void setLegacyPass(MachineFunctionPass *P)
bool run(MachineFunction &MF, const TargetMachine &TM, const RequiredAnalyses &Analyses)
ScheduleDAGInstrs * createMachineScheduler()
Instantiate a ScheduleDAGInstrs that will be owned by the caller.
void setMFAM(MachineFunctionAnalysisManager *MFAM)
SSAMachineSchedulerImpl()
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
LLVM_ABI StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
NodeAddr< NodeBase * > Node
bool isSimple(Instruction *I)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI int biasPhysReg(const SUnit *SU, bool isTop, bool BiasPRegsExtra=false)
Minimize physical register live ranges.
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
bool operator<(int64_t V1, const APSInt &V2)
void stable_sort(R &&Range)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI unsigned getWeakLeft(const SUnit *SU, bool isTop)
LLVM_ABI AntiDepBreaker * createAggressiveAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI, TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
LLVM_ABI bool shouldVerifyScheduling(const MachineFunction &MF)
Returns whether -verify-misched is set.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI TargetSubtargetInfo::AntiDepBreakMode getPostRABreakAntiDeps()
Returns -misched-postra-break-antideps.
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
LLVM_ABI char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool tryPressure(const PressureChange &TryP, const PressureChange &CandP, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason, const TargetRegisterInfo *TRI, const MachineFunction &MF)
LLVM_ABI void initializeSSAMachineSchedulerLegacyPass(PassRegistry &)
ScheduleDAGMI * createSchedPostRA(MachineSchedContext *C)
Create a generic scheduler with no vreg liveness or DAG mutation passes.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI bool shouldPrintMISchedDAGs(const MachineFunction &MF)
Return -misched-print-dags, which is false in a build without assertions.
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
LLVM_ABI bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
constexpr unsigned InvalidClusterId
LLVM_ABI MISched::Direction getPreRADirection(const MachineFunction &MF)
Returns -misched-prera-direction.
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
bool isTheSameCluster(unsigned A, unsigned B)
Return whether the input cluster ID's are the same and valid.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
LLVM_ABI bool tryBiasPhysRegs(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary *Zone, bool BiasPRegsExtra)
LLVM_ABI char & SSAMachineSchedulerID
SSAMachineScheduler - This pass schedules machine instructions in SSA.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createCopyConstrainDAGMutation(const TargetInstrInfo *TII)
DWARFExpression::Operation Op
constexpr std::optional< bool > toOptional(BoolOrDefault X)
LLVM_ABI bool tryGreater(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
SmallPtrSet< SUnit *, 8 > ClusterInfo
Keep record of which SUnit are in the same cluster group.
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.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI AntiDepBreaker * createCriticalAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI)
LLVM_ABI unsigned computeRemLatency(SchedBoundary &CurrZone)
Compute remaining latency.
constexpr bool valueOr(BoolOrDefault X, bool Default)
LLVM_ABI void dumpRegSetPressure(ArrayRef< unsigned > SetPressure, const TargetRegisterInfo *TRI)
LLVM_ABI bool tryLess(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
Return true if this heuristic determines order.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI bool shouldViewMISchedDAGs(const MachineFunction &MF)
Return -misched-view-dags, which is false in a build without assertions.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Policy for scheduling the next instruction in the candidate's zone.
Store the state used by GenericScheduler heuristics, required for the lifetime of one invocation of p...
void setBest(SchedCandidate &Best)
void reset(const CandPolicy &NewPolicy)
LLVM_ABI void initResourceDelta(const ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
SchedResourceDelta ResDelta
Status of an instruction's critical resource consumption.
unsigned DemandedResources
static constexpr LaneBitmask getNone()
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
RegisterClassInfo * RegClassInfo
MachineBlockFrequencyInfo * MBFI
const MachineLoopInfo * MLI
virtual ~MachineSchedContext()
PressureChange CriticalMax
PressureChange CurrentMax
RegisterPressure computed within a region of instructions delimited by TopPos and BottomPos.
A region of an MBB for scheduling.
Summarize the unscheduled region.
LLVM_ABI void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
SmallVector< unsigned, 16 > RemainingCounts
An individual mapping from virtual register number to SUnit.
RegisterClassInfo & RegClassInfo
MachineBlockFrequencyInfo & MBFI
MachineBlockFrequencyInfo & MBFI
RegisterClassInfo & RegClassInfo