xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
10b57cec5SDimitry Andric //===- GCNIterativeScheduler.cpp ------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "GCNIterativeScheduler.h"
100b57cec5SDimitry Andric #include "AMDGPUSubtarget.h"
110b57cec5SDimitry Andric #include "GCNRegPressure.h"
120b57cec5SDimitry Andric #include "GCNSchedStrategy.h"
130b57cec5SDimitry Andric #include "SIMachineFunctionInfo.h"
140b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAG.h"
220b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
230b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
240b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
250b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
260b57cec5SDimitry Andric #include <algorithm>
270b57cec5SDimitry Andric #include <cassert>
280b57cec5SDimitry Andric #include <iterator>
290b57cec5SDimitry Andric #include <limits>
300b57cec5SDimitry Andric #include <memory>
310b57cec5SDimitry Andric #include <type_traits>
320b57cec5SDimitry Andric #include <vector>
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric using namespace llvm;
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric #define DEBUG_TYPE "machine-scheduler"
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric namespace llvm {
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric std::vector<const SUnit *> makeMinRegSchedule(ArrayRef<const SUnit *> TopRoots,
410b57cec5SDimitry Andric                                               const ScheduleDAG &DAG);
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric   std::vector<const SUnit*> makeGCNILPScheduler(ArrayRef<const SUnit*> BotRoots,
440b57cec5SDimitry Andric     const ScheduleDAG &DAG);
450b57cec5SDimitry Andric }
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric // shim accessors for different order containers
480b57cec5SDimitry Andric static inline MachineInstr *getMachineInstr(MachineInstr *MI) {
490b57cec5SDimitry Andric   return MI;
500b57cec5SDimitry Andric }
510b57cec5SDimitry Andric static inline MachineInstr *getMachineInstr(const SUnit *SU) {
520b57cec5SDimitry Andric   return SU->getInstr();
530b57cec5SDimitry Andric }
540b57cec5SDimitry Andric static inline MachineInstr *getMachineInstr(const SUnit &SU) {
550b57cec5SDimitry Andric   return SU.getInstr();
560b57cec5SDimitry Andric }
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
590b57cec5SDimitry Andric LLVM_DUMP_METHOD
600b57cec5SDimitry Andric static void printRegion(raw_ostream &OS,
610b57cec5SDimitry Andric                         MachineBasicBlock::iterator Begin,
620b57cec5SDimitry Andric                         MachineBasicBlock::iterator End,
630b57cec5SDimitry Andric                         const LiveIntervals *LIS,
640b57cec5SDimitry Andric                         unsigned MaxInstNum =
650b57cec5SDimitry Andric                           std::numeric_limits<unsigned>::max()) {
660b57cec5SDimitry Andric   auto BB = Begin->getParent();
670b57cec5SDimitry Andric   OS << BB->getParent()->getName() << ":" << printMBBReference(*BB) << ' '
680b57cec5SDimitry Andric      << BB->getName() << ":\n";
690b57cec5SDimitry Andric   auto I = Begin;
700b57cec5SDimitry Andric   MaxInstNum = std::max(MaxInstNum, 1u);
710b57cec5SDimitry Andric   for (; I != End && MaxInstNum; ++I, --MaxInstNum) {
720b57cec5SDimitry Andric     if (!I->isDebugInstr() && LIS)
730b57cec5SDimitry Andric       OS << LIS->getInstructionIndex(*I);
740b57cec5SDimitry Andric     OS << '\t' << *I;
750b57cec5SDimitry Andric   }
760b57cec5SDimitry Andric   if (I != End) {
770b57cec5SDimitry Andric     OS << "\t...\n";
780b57cec5SDimitry Andric     I = std::prev(End);
790b57cec5SDimitry Andric     if (!I->isDebugInstr() && LIS)
800b57cec5SDimitry Andric       OS << LIS->getInstructionIndex(*I);
810b57cec5SDimitry Andric     OS << '\t' << *I;
820b57cec5SDimitry Andric   }
830b57cec5SDimitry Andric   if (End != BB->end()) { // print boundary inst if present
840b57cec5SDimitry Andric     OS << "----\n";
850b57cec5SDimitry Andric     if (LIS) OS << LIS->getInstructionIndex(*End) << '\t';
860b57cec5SDimitry Andric     OS << *End;
870b57cec5SDimitry Andric   }
880b57cec5SDimitry Andric }
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric LLVM_DUMP_METHOD
910b57cec5SDimitry Andric static void printLivenessInfo(raw_ostream &OS,
920b57cec5SDimitry Andric                               MachineBasicBlock::iterator Begin,
930b57cec5SDimitry Andric                               MachineBasicBlock::iterator End,
940b57cec5SDimitry Andric                               const LiveIntervals *LIS) {
950b57cec5SDimitry Andric   const auto BB = Begin->getParent();
960b57cec5SDimitry Andric   const auto &MRI = BB->getParent()->getRegInfo();
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   const auto LiveIns = getLiveRegsBefore(*Begin, *LIS);
990b57cec5SDimitry Andric   OS << "LIn RP: ";
1000b57cec5SDimitry Andric   getRegPressure(MRI, LiveIns).print(OS);
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   const auto BottomMI = End == BB->end() ? std::prev(End) : End;
1030b57cec5SDimitry Andric   const auto LiveOuts = getLiveRegsAfter(*BottomMI, *LIS);
1040b57cec5SDimitry Andric   OS << "LOt RP: ";
1050b57cec5SDimitry Andric   getRegPressure(MRI, LiveOuts).print(OS);
1060b57cec5SDimitry Andric }
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric LLVM_DUMP_METHOD
1090b57cec5SDimitry Andric void GCNIterativeScheduler::printRegions(raw_ostream &OS) const {
1100b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
1110b57cec5SDimitry Andric   for (const auto R : Regions) {
1120b57cec5SDimitry Andric     OS << "Region to schedule ";
1130b57cec5SDimitry Andric     printRegion(OS, R->Begin, R->End, LIS, 1);
1140b57cec5SDimitry Andric     printLivenessInfo(OS, R->Begin, R->End, LIS);
1150b57cec5SDimitry Andric     OS << "Max RP: ";
1160b57cec5SDimitry Andric     R->MaxPressure.print(OS, &ST);
1170b57cec5SDimitry Andric   }
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric LLVM_DUMP_METHOD
1210b57cec5SDimitry Andric void GCNIterativeScheduler::printSchedResult(raw_ostream &OS,
1220b57cec5SDimitry Andric                                              const Region *R,
1230b57cec5SDimitry Andric                                              const GCNRegPressure &RP) const {
1240b57cec5SDimitry Andric   OS << "\nAfter scheduling ";
1250b57cec5SDimitry Andric   printRegion(OS, R->Begin, R->End, LIS);
1260b57cec5SDimitry Andric   printSchedRP(OS, R->MaxPressure, RP);
1270b57cec5SDimitry Andric   OS << '\n';
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric LLVM_DUMP_METHOD
1310b57cec5SDimitry Andric void GCNIterativeScheduler::printSchedRP(raw_ostream &OS,
1320b57cec5SDimitry Andric                                          const GCNRegPressure &Before,
1330b57cec5SDimitry Andric                                          const GCNRegPressure &After) const {
1340b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
1350b57cec5SDimitry Andric   OS << "RP before: ";
1360b57cec5SDimitry Andric   Before.print(OS, &ST);
1370b57cec5SDimitry Andric   OS << "RP after:  ";
1380b57cec5SDimitry Andric   After.print(OS, &ST);
1390b57cec5SDimitry Andric }
1400b57cec5SDimitry Andric #endif
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric // DAG builder helper
1430b57cec5SDimitry Andric class GCNIterativeScheduler::BuildDAG {
1440b57cec5SDimitry Andric   GCNIterativeScheduler &Sch;
1450b57cec5SDimitry Andric   SmallVector<SUnit *, 8> TopRoots;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   SmallVector<SUnit*, 8> BotRoots;
1480b57cec5SDimitry Andric public:
1490b57cec5SDimitry Andric   BuildDAG(const Region &R, GCNIterativeScheduler &_Sch)
1500b57cec5SDimitry Andric     : Sch(_Sch) {
1510b57cec5SDimitry Andric     auto BB = R.Begin->getParent();
1520b57cec5SDimitry Andric     Sch.BaseClass::startBlock(BB);
1530b57cec5SDimitry Andric     Sch.BaseClass::enterRegion(BB, R.Begin, R.End, R.NumRegionInstrs);
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     Sch.buildSchedGraph(Sch.AA, nullptr, nullptr, nullptr,
1560b57cec5SDimitry Andric                         /*TrackLaneMask*/true);
1570b57cec5SDimitry Andric     Sch.Topo.InitDAGTopologicalSorting();
1580b57cec5SDimitry Andric     Sch.findRootsAndBiasEdges(TopRoots, BotRoots);
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   ~BuildDAG() {
1620b57cec5SDimitry Andric     Sch.BaseClass::exitRegion();
1630b57cec5SDimitry Andric     Sch.BaseClass::finishBlock();
1640b57cec5SDimitry Andric   }
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   ArrayRef<const SUnit *> getTopRoots() const {
1670b57cec5SDimitry Andric     return TopRoots;
1680b57cec5SDimitry Andric   }
1690b57cec5SDimitry Andric   ArrayRef<SUnit*> getBottomRoots() const {
1700b57cec5SDimitry Andric     return BotRoots;
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric };
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric class GCNIterativeScheduler::OverrideLegacyStrategy {
1750b57cec5SDimitry Andric   GCNIterativeScheduler &Sch;
1760b57cec5SDimitry Andric   Region &Rgn;
1770b57cec5SDimitry Andric   std::unique_ptr<MachineSchedStrategy> SaveSchedImpl;
1780b57cec5SDimitry Andric   GCNRegPressure SaveMaxRP;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric public:
1810b57cec5SDimitry Andric   OverrideLegacyStrategy(Region &R,
1820b57cec5SDimitry Andric                          MachineSchedStrategy &OverrideStrategy,
1830b57cec5SDimitry Andric                          GCNIterativeScheduler &_Sch)
1840b57cec5SDimitry Andric     : Sch(_Sch)
1850b57cec5SDimitry Andric     , Rgn(R)
1860b57cec5SDimitry Andric     , SaveSchedImpl(std::move(_Sch.SchedImpl))
1870b57cec5SDimitry Andric     , SaveMaxRP(R.MaxPressure) {
1880b57cec5SDimitry Andric     Sch.SchedImpl.reset(&OverrideStrategy);
1890b57cec5SDimitry Andric     auto BB = R.Begin->getParent();
1900b57cec5SDimitry Andric     Sch.BaseClass::startBlock(BB);
1910b57cec5SDimitry Andric     Sch.BaseClass::enterRegion(BB, R.Begin, R.End, R.NumRegionInstrs);
1920b57cec5SDimitry Andric   }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   ~OverrideLegacyStrategy() {
1950b57cec5SDimitry Andric     Sch.BaseClass::exitRegion();
1960b57cec5SDimitry Andric     Sch.BaseClass::finishBlock();
1970b57cec5SDimitry Andric     Sch.SchedImpl.release();
1980b57cec5SDimitry Andric     Sch.SchedImpl = std::move(SaveSchedImpl);
1990b57cec5SDimitry Andric   }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   void schedule() {
2020b57cec5SDimitry Andric     assert(Sch.RegionBegin == Rgn.Begin && Sch.RegionEnd == Rgn.End);
2030b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\nScheduling ";
2040b57cec5SDimitry Andric                printRegion(dbgs(), Rgn.Begin, Rgn.End, Sch.LIS, 2));
2050b57cec5SDimitry Andric     Sch.BaseClass::schedule();
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric     // Unfortunatelly placeDebugValues incorrectly modifies RegionEnd, restore
2080b57cec5SDimitry Andric     Sch.RegionEnd = Rgn.End;
2090b57cec5SDimitry Andric     //assert(Rgn.End == Sch.RegionEnd);
2100b57cec5SDimitry Andric     Rgn.Begin = Sch.RegionBegin;
2110b57cec5SDimitry Andric     Rgn.MaxPressure.clear();
2120b57cec5SDimitry Andric   }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   void restoreOrder() {
2150b57cec5SDimitry Andric     assert(Sch.RegionBegin == Rgn.Begin && Sch.RegionEnd == Rgn.End);
2160b57cec5SDimitry Andric     // DAG SUnits are stored using original region's order
2170b57cec5SDimitry Andric     // so just use SUnits as the restoring schedule
2180b57cec5SDimitry Andric     Sch.scheduleRegion(Rgn, Sch.SUnits, SaveMaxRP);
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric };
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric namespace {
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric // just a stub to make base class happy
2250b57cec5SDimitry Andric class SchedStrategyStub : public MachineSchedStrategy {
2260b57cec5SDimitry Andric public:
2270b57cec5SDimitry Andric   bool shouldTrackPressure() const override { return false; }
2280b57cec5SDimitry Andric   bool shouldTrackLaneMasks() const override { return false; }
2290b57cec5SDimitry Andric   void initialize(ScheduleDAGMI *DAG) override {}
2300b57cec5SDimitry Andric   SUnit *pickNode(bool &IsTopNode) override { return nullptr; }
2310b57cec5SDimitry Andric   void schedNode(SUnit *SU, bool IsTopNode) override {}
2320b57cec5SDimitry Andric   void releaseTopNode(SUnit *SU) override {}
2330b57cec5SDimitry Andric   void releaseBottomNode(SUnit *SU) override {}
2340b57cec5SDimitry Andric };
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric } // end anonymous namespace
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric GCNIterativeScheduler::GCNIterativeScheduler(MachineSchedContext *C,
2390b57cec5SDimitry Andric                                              StrategyKind S)
240*8bcb0991SDimitry Andric   : BaseClass(C, std::make_unique<SchedStrategyStub>())
2410b57cec5SDimitry Andric   , Context(C)
2420b57cec5SDimitry Andric   , Strategy(S)
2430b57cec5SDimitry Andric   , UPTracker(*LIS) {
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric // returns max pressure for a region
2470b57cec5SDimitry Andric GCNRegPressure
2480b57cec5SDimitry Andric GCNIterativeScheduler::getRegionPressure(MachineBasicBlock::iterator Begin,
2490b57cec5SDimitry Andric                                          MachineBasicBlock::iterator End)
2500b57cec5SDimitry Andric   const {
2510b57cec5SDimitry Andric   // For the purpose of pressure tracking bottom inst of the region should
2520b57cec5SDimitry Andric   // be also processed. End is either BB end, BB terminator inst or sched
2530b57cec5SDimitry Andric   // boundary inst.
2540b57cec5SDimitry Andric   auto const BBEnd = Begin->getParent()->end();
2550b57cec5SDimitry Andric   auto const BottomMI = End == BBEnd ? std::prev(End) : End;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   // scheduleRegions walks bottom to top, so its likely we just get next
2580b57cec5SDimitry Andric   // instruction to track
2590b57cec5SDimitry Andric   auto AfterBottomMI = std::next(BottomMI);
2600b57cec5SDimitry Andric   if (AfterBottomMI == BBEnd ||
2610b57cec5SDimitry Andric       &*AfterBottomMI != UPTracker.getLastTrackedMI()) {
2620b57cec5SDimitry Andric     UPTracker.reset(*BottomMI);
2630b57cec5SDimitry Andric   } else {
2640b57cec5SDimitry Andric     assert(UPTracker.isValid());
2650b57cec5SDimitry Andric   }
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   for (auto I = BottomMI; I != Begin; --I)
2680b57cec5SDimitry Andric     UPTracker.recede(*I);
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   UPTracker.recede(*Begin);
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   assert(UPTracker.isValid() ||
2730b57cec5SDimitry Andric          (dbgs() << "Tracked region ",
2740b57cec5SDimitry Andric           printRegion(dbgs(), Begin, End, LIS), false));
2750b57cec5SDimitry Andric   return UPTracker.moveMaxPressure();
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric // returns max pressure for a tentative schedule
2790b57cec5SDimitry Andric template <typename Range> GCNRegPressure
2800b57cec5SDimitry Andric GCNIterativeScheduler::getSchedulePressure(const Region &R,
2810b57cec5SDimitry Andric                                            Range &&Schedule) const {
2820b57cec5SDimitry Andric   auto const BBEnd = R.Begin->getParent()->end();
2830b57cec5SDimitry Andric   GCNUpwardRPTracker RPTracker(*LIS);
2840b57cec5SDimitry Andric   if (R.End != BBEnd) {
2850b57cec5SDimitry Andric     // R.End points to the boundary instruction but the
2860b57cec5SDimitry Andric     // schedule doesn't include it
2870b57cec5SDimitry Andric     RPTracker.reset(*R.End);
2880b57cec5SDimitry Andric     RPTracker.recede(*R.End);
2890b57cec5SDimitry Andric   } else {
2900b57cec5SDimitry Andric     // R.End doesn't point to the boundary instruction
2910b57cec5SDimitry Andric     RPTracker.reset(*std::prev(BBEnd));
2920b57cec5SDimitry Andric   }
2930b57cec5SDimitry Andric   for (auto I = Schedule.end(), B = Schedule.begin(); I != B;) {
2940b57cec5SDimitry Andric     RPTracker.recede(*getMachineInstr(*--I));
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric   return RPTracker.moveMaxPressure();
2970b57cec5SDimitry Andric }
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric void GCNIterativeScheduler::enterRegion(MachineBasicBlock *BB, // overriden
3000b57cec5SDimitry Andric                                         MachineBasicBlock::iterator Begin,
3010b57cec5SDimitry Andric                                         MachineBasicBlock::iterator End,
3020b57cec5SDimitry Andric                                         unsigned NumRegionInstrs) {
3030b57cec5SDimitry Andric   BaseClass::enterRegion(BB, Begin, End, NumRegionInstrs);
3040b57cec5SDimitry Andric   if (NumRegionInstrs > 2) {
3050b57cec5SDimitry Andric     Regions.push_back(
3060b57cec5SDimitry Andric       new (Alloc.Allocate())
3070b57cec5SDimitry Andric       Region { Begin, End, NumRegionInstrs,
3080b57cec5SDimitry Andric                getRegionPressure(Begin, End), nullptr });
3090b57cec5SDimitry Andric   }
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric void GCNIterativeScheduler::schedule() { // overriden
3130b57cec5SDimitry Andric   // do nothing
3140b57cec5SDimitry Andric   LLVM_DEBUG(printLivenessInfo(dbgs(), RegionBegin, RegionEnd, LIS);
3150b57cec5SDimitry Andric              if (!Regions.empty() && Regions.back()->Begin == RegionBegin) {
3160b57cec5SDimitry Andric                dbgs() << "Max RP: ";
3170b57cec5SDimitry Andric                Regions.back()->MaxPressure.print(
3180b57cec5SDimitry Andric                    dbgs(), &MF.getSubtarget<GCNSubtarget>());
3190b57cec5SDimitry Andric              } dbgs()
3200b57cec5SDimitry Andric              << '\n';);
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric void GCNIterativeScheduler::finalizeSchedule() { // overriden
3240b57cec5SDimitry Andric   if (Regions.empty())
3250b57cec5SDimitry Andric     return;
3260b57cec5SDimitry Andric   switch (Strategy) {
3270b57cec5SDimitry Andric   case SCHEDULE_MINREGONLY: scheduleMinReg(); break;
3280b57cec5SDimitry Andric   case SCHEDULE_MINREGFORCED: scheduleMinReg(true); break;
3290b57cec5SDimitry Andric   case SCHEDULE_LEGACYMAXOCCUPANCY: scheduleLegacyMaxOccupancy(); break;
3300b57cec5SDimitry Andric   case SCHEDULE_ILP: scheduleILP(false); break;
3310b57cec5SDimitry Andric   }
3320b57cec5SDimitry Andric }
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric // Detach schedule from SUnits and interleave it with debug values.
3350b57cec5SDimitry Andric // Returned schedule becomes independent of DAG state.
3360b57cec5SDimitry Andric std::vector<MachineInstr*>
3370b57cec5SDimitry Andric GCNIterativeScheduler::detachSchedule(ScheduleRef Schedule) const {
3380b57cec5SDimitry Andric   std::vector<MachineInstr*> Res;
3390b57cec5SDimitry Andric   Res.reserve(Schedule.size() * 2);
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   if (FirstDbgValue)
3420b57cec5SDimitry Andric     Res.push_back(FirstDbgValue);
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   const auto DbgB = DbgValues.begin(), DbgE = DbgValues.end();
3450b57cec5SDimitry Andric   for (auto SU : Schedule) {
3460b57cec5SDimitry Andric     Res.push_back(SU->getInstr());
3470b57cec5SDimitry Andric     const auto &D = std::find_if(DbgB, DbgE, [SU](decltype(*DbgB) &P) {
3480b57cec5SDimitry Andric       return P.second == SU->getInstr();
3490b57cec5SDimitry Andric     });
3500b57cec5SDimitry Andric     if (D != DbgE)
3510b57cec5SDimitry Andric       Res.push_back(D->first);
3520b57cec5SDimitry Andric   }
3530b57cec5SDimitry Andric   return Res;
3540b57cec5SDimitry Andric }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric void GCNIterativeScheduler::setBestSchedule(Region &R,
3570b57cec5SDimitry Andric                                             ScheduleRef Schedule,
3580b57cec5SDimitry Andric                                             const GCNRegPressure &MaxRP) {
3590b57cec5SDimitry Andric   R.BestSchedule.reset(
3600b57cec5SDimitry Andric     new TentativeSchedule{ detachSchedule(Schedule), MaxRP });
3610b57cec5SDimitry Andric }
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric void GCNIterativeScheduler::scheduleBest(Region &R) {
3640b57cec5SDimitry Andric   assert(R.BestSchedule.get() && "No schedule specified");
3650b57cec5SDimitry Andric   scheduleRegion(R, R.BestSchedule->Schedule, R.BestSchedule->MaxPressure);
3660b57cec5SDimitry Andric   R.BestSchedule.reset();
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric // minimal required region scheduler, works for ranges of SUnits*,
3700b57cec5SDimitry Andric // SUnits or MachineIntrs*
3710b57cec5SDimitry Andric template <typename Range>
3720b57cec5SDimitry Andric void GCNIterativeScheduler::scheduleRegion(Region &R, Range &&Schedule,
3730b57cec5SDimitry Andric                                            const GCNRegPressure &MaxRP) {
3740b57cec5SDimitry Andric   assert(RegionBegin == R.Begin && RegionEnd == R.End);
3750b57cec5SDimitry Andric   assert(LIS != nullptr);
3760b57cec5SDimitry Andric #ifndef NDEBUG
3770b57cec5SDimitry Andric   const auto SchedMaxRP = getSchedulePressure(R, Schedule);
3780b57cec5SDimitry Andric #endif
3790b57cec5SDimitry Andric   auto BB = R.Begin->getParent();
3800b57cec5SDimitry Andric   auto Top = R.Begin;
3810b57cec5SDimitry Andric   for (const auto &I : Schedule) {
3820b57cec5SDimitry Andric     auto MI = getMachineInstr(I);
3830b57cec5SDimitry Andric     if (MI != &*Top) {
3840b57cec5SDimitry Andric       BB->remove(MI);
3850b57cec5SDimitry Andric       BB->insert(Top, MI);
3860b57cec5SDimitry Andric       if (!MI->isDebugInstr())
3870b57cec5SDimitry Andric         LIS->handleMove(*MI, true);
3880b57cec5SDimitry Andric     }
3890b57cec5SDimitry Andric     if (!MI->isDebugInstr()) {
3900b57cec5SDimitry Andric       // Reset read - undef flags and update them later.
3910b57cec5SDimitry Andric       for (auto &Op : MI->operands())
3920b57cec5SDimitry Andric         if (Op.isReg() && Op.isDef())
3930b57cec5SDimitry Andric           Op.setIsUndef(false);
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric       RegisterOperands RegOpers;
3960b57cec5SDimitry Andric       RegOpers.collect(*MI, *TRI, MRI, /*ShouldTrackLaneMasks*/true,
3970b57cec5SDimitry Andric                                        /*IgnoreDead*/false);
3980b57cec5SDimitry Andric       // Adjust liveness and add missing dead+read-undef flags.
3990b57cec5SDimitry Andric       auto SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
4000b57cec5SDimitry Andric       RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
4010b57cec5SDimitry Andric     }
4020b57cec5SDimitry Andric     Top = std::next(MI->getIterator());
4030b57cec5SDimitry Andric   }
4040b57cec5SDimitry Andric   RegionBegin = getMachineInstr(Schedule.front());
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   // Schedule consisting of MachineInstr* is considered 'detached'
4070b57cec5SDimitry Andric   // and already interleaved with debug values
4080b57cec5SDimitry Andric   if (!std::is_same<decltype(*Schedule.begin()), MachineInstr*>::value) {
4090b57cec5SDimitry Andric     placeDebugValues();
4100b57cec5SDimitry Andric     // Unfortunatelly placeDebugValues incorrectly modifies RegionEnd, restore
4110b57cec5SDimitry Andric     //assert(R.End == RegionEnd);
4120b57cec5SDimitry Andric     RegionEnd = R.End;
4130b57cec5SDimitry Andric   }
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric   R.Begin = RegionBegin;
4160b57cec5SDimitry Andric   R.MaxPressure = MaxRP;
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric #ifndef NDEBUG
4190b57cec5SDimitry Andric   const auto RegionMaxRP = getRegionPressure(R);
4200b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
4210b57cec5SDimitry Andric #endif
4220b57cec5SDimitry Andric   assert((SchedMaxRP == RegionMaxRP && (MaxRP.empty() || SchedMaxRP == MaxRP))
4230b57cec5SDimitry Andric   || (dbgs() << "Max RP mismatch!!!\n"
4240b57cec5SDimitry Andric                 "RP for schedule (calculated): ",
4250b57cec5SDimitry Andric       SchedMaxRP.print(dbgs(), &ST),
4260b57cec5SDimitry Andric       dbgs() << "RP for schedule (reported): ",
4270b57cec5SDimitry Andric       MaxRP.print(dbgs(), &ST),
4280b57cec5SDimitry Andric       dbgs() << "RP after scheduling: ",
4290b57cec5SDimitry Andric       RegionMaxRP.print(dbgs(), &ST),
4300b57cec5SDimitry Andric       false));
4310b57cec5SDimitry Andric }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric // Sort recorded regions by pressure - highest at the front
4340b57cec5SDimitry Andric void GCNIterativeScheduler::sortRegionsByPressure(unsigned TargetOcc) {
4350b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
4360b57cec5SDimitry Andric   llvm::sort(Regions, [&ST, TargetOcc](const Region *R1, const Region *R2) {
4370b57cec5SDimitry Andric     return R2->MaxPressure.less(ST, R1->MaxPressure, TargetOcc);
4380b57cec5SDimitry Andric   });
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric ///////////////////////////////////////////////////////////////////////////////
4420b57cec5SDimitry Andric // Legacy MaxOccupancy Strategy
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric // Tries to increase occupancy applying minreg scheduler for a sequence of
4450b57cec5SDimitry Andric // most demanding regions. Obtained schedules are saved as BestSchedule for a
4460b57cec5SDimitry Andric // region.
4470b57cec5SDimitry Andric // TargetOcc is the best achievable occupancy for a kernel.
4480b57cec5SDimitry Andric // Returns better occupancy on success or current occupancy on fail.
4490b57cec5SDimitry Andric // BestSchedules aren't deleted on fail.
4500b57cec5SDimitry Andric unsigned GCNIterativeScheduler::tryMaximizeOccupancy(unsigned TargetOcc) {
4510b57cec5SDimitry Andric   // TODO: assert Regions are sorted descending by pressure
4520b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
4530b57cec5SDimitry Andric   const auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
4540b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to improve occupancy, target = " << TargetOcc
4550b57cec5SDimitry Andric                     << ", current = " << Occ << '\n');
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   auto NewOcc = TargetOcc;
4580b57cec5SDimitry Andric   for (auto R : Regions) {
4590b57cec5SDimitry Andric     if (R->MaxPressure.getOccupancy(ST) >= NewOcc)
4600b57cec5SDimitry Andric       break;
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric     LLVM_DEBUG(printRegion(dbgs(), R->Begin, R->End, LIS, 3);
4630b57cec5SDimitry Andric                printLivenessInfo(dbgs(), R->Begin, R->End, LIS));
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric     BuildDAG DAG(*R, *this);
4660b57cec5SDimitry Andric     const auto MinSchedule = makeMinRegSchedule(DAG.getTopRoots(), *this);
4670b57cec5SDimitry Andric     const auto MaxRP = getSchedulePressure(*R, MinSchedule);
4680b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Occupancy improvement attempt:\n";
4690b57cec5SDimitry Andric                printSchedRP(dbgs(), R->MaxPressure, MaxRP));
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric     NewOcc = std::min(NewOcc, MaxRP.getOccupancy(ST));
4720b57cec5SDimitry Andric     if (NewOcc <= Occ)
4730b57cec5SDimitry Andric       break;
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric     setBestSchedule(*R, MinSchedule, MaxRP);
4760b57cec5SDimitry Andric   }
4770b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "New occupancy = " << NewOcc
4780b57cec5SDimitry Andric                     << ", prev occupancy = " << Occ << '\n');
4790b57cec5SDimitry Andric   if (NewOcc > Occ) {
4800b57cec5SDimitry Andric     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4810b57cec5SDimitry Andric     MFI->increaseOccupancy(MF, NewOcc);
4820b57cec5SDimitry Andric   }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   return std::max(NewOcc, Occ);
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric void GCNIterativeScheduler::scheduleLegacyMaxOccupancy(
4880b57cec5SDimitry Andric   bool TryMaximizeOccupancy) {
4890b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
4900b57cec5SDimitry Andric   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4910b57cec5SDimitry Andric   auto TgtOcc = MFI->getMinAllowedOccupancy();
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   sortRegionsByPressure(TgtOcc);
4940b57cec5SDimitry Andric   auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   if (TryMaximizeOccupancy && Occ < TgtOcc)
4970b57cec5SDimitry Andric     Occ = tryMaximizeOccupancy(TgtOcc);
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   // This is really weird but for some magic scheduling regions twice
5000b57cec5SDimitry Andric   // gives performance improvement
5010b57cec5SDimitry Andric   const int NumPasses = Occ < TgtOcc ? 2 : 1;
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   TgtOcc = std::min(Occ, TgtOcc);
5040b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Scheduling using default scheduler, "
5050b57cec5SDimitry Andric                        "target occupancy = "
5060b57cec5SDimitry Andric                     << TgtOcc << '\n');
5070b57cec5SDimitry Andric   GCNMaxOccupancySchedStrategy LStrgy(Context);
5080b57cec5SDimitry Andric   unsigned FinalOccupancy = std::min(Occ, MFI->getOccupancy());
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   for (int I = 0; I < NumPasses; ++I) {
5110b57cec5SDimitry Andric     // running first pass with TargetOccupancy = 0 mimics previous scheduling
5120b57cec5SDimitry Andric     // approach and is a performance magic
5130b57cec5SDimitry Andric     LStrgy.setTargetOccupancy(I == 0 ? 0 : TgtOcc);
5140b57cec5SDimitry Andric     for (auto R : Regions) {
5150b57cec5SDimitry Andric       OverrideLegacyStrategy Ovr(*R, LStrgy, *this);
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric       Ovr.schedule();
5180b57cec5SDimitry Andric       const auto RP = getRegionPressure(*R);
5190b57cec5SDimitry Andric       LLVM_DEBUG(printSchedRP(dbgs(), R->MaxPressure, RP));
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric       if (RP.getOccupancy(ST) < TgtOcc) {
5220b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Didn't fit into target occupancy O" << TgtOcc);
5230b57cec5SDimitry Andric         if (R->BestSchedule.get() &&
5240b57cec5SDimitry Andric             R->BestSchedule->MaxPressure.getOccupancy(ST) >= TgtOcc) {
5250b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << ", scheduling minimal register\n");
5260b57cec5SDimitry Andric           scheduleBest(*R);
5270b57cec5SDimitry Andric         } else {
5280b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << ", restoring\n");
5290b57cec5SDimitry Andric           Ovr.restoreOrder();
5300b57cec5SDimitry Andric           assert(R->MaxPressure.getOccupancy(ST) >= TgtOcc);
5310b57cec5SDimitry Andric         }
5320b57cec5SDimitry Andric       }
5330b57cec5SDimitry Andric       FinalOccupancy = std::min(FinalOccupancy, RP.getOccupancy(ST));
5340b57cec5SDimitry Andric     }
5350b57cec5SDimitry Andric   }
5360b57cec5SDimitry Andric   MFI->limitOccupancy(FinalOccupancy);
5370b57cec5SDimitry Andric }
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric ///////////////////////////////////////////////////////////////////////////////
5400b57cec5SDimitry Andric // Minimal Register Strategy
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric void GCNIterativeScheduler::scheduleMinReg(bool force) {
5430b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
5440b57cec5SDimitry Andric   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5450b57cec5SDimitry Andric   const auto TgtOcc = MFI->getOccupancy();
5460b57cec5SDimitry Andric   sortRegionsByPressure(TgtOcc);
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric   auto MaxPressure = Regions.front()->MaxPressure;
5490b57cec5SDimitry Andric   for (auto R : Regions) {
5500b57cec5SDimitry Andric     if (!force && R->MaxPressure.less(ST, MaxPressure, TgtOcc))
5510b57cec5SDimitry Andric       break;
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric     BuildDAG DAG(*R, *this);
5540b57cec5SDimitry Andric     const auto MinSchedule = makeMinRegSchedule(DAG.getTopRoots(), *this);
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric     const auto RP = getSchedulePressure(*R, MinSchedule);
5570b57cec5SDimitry Andric     LLVM_DEBUG(if (R->MaxPressure.less(ST, RP, TgtOcc)) {
5580b57cec5SDimitry Andric       dbgs() << "\nWarning: Pressure becomes worse after minreg!";
5590b57cec5SDimitry Andric       printSchedRP(dbgs(), R->MaxPressure, RP);
5600b57cec5SDimitry Andric     });
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric     if (!force && MaxPressure.less(ST, RP, TgtOcc))
5630b57cec5SDimitry Andric       break;
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric     scheduleRegion(*R, MinSchedule, RP);
5660b57cec5SDimitry Andric     LLVM_DEBUG(printSchedResult(dbgs(), R, RP));
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric     MaxPressure = RP;
5690b57cec5SDimitry Andric   }
5700b57cec5SDimitry Andric }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric ///////////////////////////////////////////////////////////////////////////////
5730b57cec5SDimitry Andric // ILP scheduler port
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric void GCNIterativeScheduler::scheduleILP(
5760b57cec5SDimitry Andric   bool TryMaximizeOccupancy) {
5770b57cec5SDimitry Andric   const auto &ST = MF.getSubtarget<GCNSubtarget>();
5780b57cec5SDimitry Andric   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5790b57cec5SDimitry Andric   auto TgtOcc = MFI->getMinAllowedOccupancy();
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric   sortRegionsByPressure(TgtOcc);
5820b57cec5SDimitry Andric   auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   if (TryMaximizeOccupancy && Occ < TgtOcc)
5850b57cec5SDimitry Andric     Occ = tryMaximizeOccupancy(TgtOcc);
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric   TgtOcc = std::min(Occ, TgtOcc);
5880b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Scheduling using default scheduler, "
5890b57cec5SDimitry Andric                        "target occupancy = "
5900b57cec5SDimitry Andric                     << TgtOcc << '\n');
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric   unsigned FinalOccupancy = std::min(Occ, MFI->getOccupancy());
5930b57cec5SDimitry Andric   for (auto R : Regions) {
5940b57cec5SDimitry Andric     BuildDAG DAG(*R, *this);
5950b57cec5SDimitry Andric     const auto ILPSchedule = makeGCNILPScheduler(DAG.getBottomRoots(), *this);
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     const auto RP = getSchedulePressure(*R, ILPSchedule);
5980b57cec5SDimitry Andric     LLVM_DEBUG(printSchedRP(dbgs(), R->MaxPressure, RP));
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric     if (RP.getOccupancy(ST) < TgtOcc) {
6010b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Didn't fit into target occupancy O" << TgtOcc);
6020b57cec5SDimitry Andric       if (R->BestSchedule.get() &&
6030b57cec5SDimitry Andric         R->BestSchedule->MaxPressure.getOccupancy(ST) >= TgtOcc) {
6040b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << ", scheduling minimal register\n");
6050b57cec5SDimitry Andric         scheduleBest(*R);
6060b57cec5SDimitry Andric       }
6070b57cec5SDimitry Andric     } else {
6080b57cec5SDimitry Andric       scheduleRegion(*R, ILPSchedule, RP);
6090b57cec5SDimitry Andric       LLVM_DEBUG(printSchedResult(dbgs(), R, RP));
6100b57cec5SDimitry Andric       FinalOccupancy = std::min(FinalOccupancy, RP.getOccupancy(ST));
6110b57cec5SDimitry Andric     }
6120b57cec5SDimitry Andric   }
6130b57cec5SDimitry Andric   MFI->limitOccupancy(FinalOccupancy);
6140b57cec5SDimitry Andric }
615