10d23ebe8STom Stellard //===-- GCNSchedStrategy.cpp - GCN Scheduler Strategy ---------------------===//
20d23ebe8STom Stellard //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60d23ebe8STom Stellard //
70d23ebe8STom Stellard //===----------------------------------------------------------------------===//
80d23ebe8STom Stellard //
90d23ebe8STom Stellard /// \file
100d23ebe8STom Stellard /// This contains a MachineSchedStrategy implementation for maximizing wave
110d23ebe8STom Stellard /// occupancy on GCN hardware.
12*7ca9e471SAustin Kerbow ///
13*7ca9e471SAustin Kerbow /// This pass will apply multiple scheduling stages to the same function.
14*7ca9e471SAustin Kerbow /// Regions are first recorded in GCNScheduleDAGMILive::schedule. The actual
15*7ca9e471SAustin Kerbow /// entry point for the scheduling of those regions is
16*7ca9e471SAustin Kerbow /// GCNScheduleDAGMILive::runSchedStages.
17*7ca9e471SAustin Kerbow
18*7ca9e471SAustin Kerbow /// Generally, the reason for having multiple scheduling stages is to account
19*7ca9e471SAustin Kerbow /// for the kernel-wide effect of register usage on occupancy. Usually, only a
20*7ca9e471SAustin Kerbow /// few scheduling regions will have register pressure high enough to limit
21*7ca9e471SAustin Kerbow /// occupancy for the kernel, so constraints can be relaxed to improve ILP in
22*7ca9e471SAustin Kerbow /// other regions.
23*7ca9e471SAustin Kerbow ///
240d23ebe8STom Stellard //===----------------------------------------------------------------------===//
250d23ebe8STom Stellard
260d23ebe8STom Stellard #include "GCNSchedStrategy.h"
270d23ebe8STom Stellard #include "SIMachineFunctionInfo.h"
28989f1c72Sserge-sans-paille #include "llvm/CodeGen/RegisterClassInfo.h"
290d23ebe8STom Stellard
300cd23f56SEvandro Menezes #define DEBUG_TYPE "machine-scheduler"
310d23ebe8STom Stellard
320d23ebe8STom Stellard using namespace llvm;
330d23ebe8STom Stellard
GCNMaxOccupancySchedStrategy(const MachineSchedContext * C)340d23ebe8STom Stellard GCNMaxOccupancySchedStrategy::GCNMaxOccupancySchedStrategy(
35*7ca9e471SAustin Kerbow const MachineSchedContext *C)
36*7ca9e471SAustin Kerbow : GenericScheduler(C), TargetOccupancy(0), MF(nullptr),
37*7ca9e471SAustin Kerbow HasClusteredNodes(false), HasExcessPressure(false) {}
380d23ebe8STom Stellard
initialize(ScheduleDAGMI * DAG)39582a5237SStanislav Mekhanoshin void GCNMaxOccupancySchedStrategy::initialize(ScheduleDAGMI *DAG) {
40582a5237SStanislav Mekhanoshin GenericScheduler::initialize(DAG);
41582a5237SStanislav Mekhanoshin
42357d3db0SStanislav Mekhanoshin MF = &DAG->MF;
43357d3db0SStanislav Mekhanoshin
445bfbae5cSTom Stellard const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
45357d3db0SStanislav Mekhanoshin
46582a5237SStanislav Mekhanoshin // FIXME: This is also necessary, because some passes that run after
47582a5237SStanislav Mekhanoshin // scheduling and before regalloc increase register pressure.
4802e60f2eSAustin Kerbow const unsigned ErrorMargin = 3;
49582a5237SStanislav Mekhanoshin
5002e60f2eSAustin Kerbow SGPRExcessLimit =
5102e60f2eSAustin Kerbow Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::SGPR_32RegClass);
5202e60f2eSAustin Kerbow VGPRExcessLimit =
5302e60f2eSAustin Kerbow Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::VGPR_32RegClass);
54357d3db0SStanislav Mekhanoshin
5502e60f2eSAustin Kerbow SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
5602e60f2eSAustin Kerbow // Set the initial TargetOccupnacy to the maximum occupancy that we can
5702e60f2eSAustin Kerbow // achieve for this function. This effectively sets a lower bound on the
5802e60f2eSAustin Kerbow // 'Critical' register limits in the scheduler.
5902e60f2eSAustin Kerbow TargetOccupancy = MFI.getOccupancy();
6002e60f2eSAustin Kerbow SGPRCriticalLimit =
6102e60f2eSAustin Kerbow std::min(ST.getMaxNumSGPRs(TargetOccupancy, true), SGPRExcessLimit);
6202e60f2eSAustin Kerbow VGPRCriticalLimit =
6302e60f2eSAustin Kerbow std::min(ST.getMaxNumVGPRs(TargetOccupancy), VGPRExcessLimit);
6402e60f2eSAustin Kerbow
6502e60f2eSAustin Kerbow // Subtract error margin from register limits and avoid overflow.
6602e60f2eSAustin Kerbow SGPRCriticalLimit =
6702e60f2eSAustin Kerbow std::min(SGPRCriticalLimit - ErrorMargin, SGPRCriticalLimit);
6802e60f2eSAustin Kerbow VGPRCriticalLimit =
6902e60f2eSAustin Kerbow std::min(VGPRCriticalLimit - ErrorMargin, VGPRCriticalLimit);
7002e60f2eSAustin Kerbow SGPRExcessLimit = std::min(SGPRExcessLimit - ErrorMargin, SGPRExcessLimit);
7102e60f2eSAustin Kerbow VGPRExcessLimit = std::min(VGPRExcessLimit - ErrorMargin, VGPRExcessLimit);
72582a5237SStanislav Mekhanoshin }
73582a5237SStanislav Mekhanoshin
initCandidate(SchedCandidate & Cand,SUnit * SU,bool AtTop,const RegPressureTracker & RPTracker,const SIRegisterInfo * SRI,unsigned SGPRPressure,unsigned VGPRPressure)740d23ebe8STom Stellard void GCNMaxOccupancySchedStrategy::initCandidate(SchedCandidate &Cand, SUnit *SU,
750d23ebe8STom Stellard bool AtTop, const RegPressureTracker &RPTracker,
760d23ebe8STom Stellard const SIRegisterInfo *SRI,
77582a5237SStanislav Mekhanoshin unsigned SGPRPressure,
78582a5237SStanislav Mekhanoshin unsigned VGPRPressure) {
790d23ebe8STom Stellard
800d23ebe8STom Stellard Cand.SU = SU;
810d23ebe8STom Stellard Cand.AtTop = AtTop;
820d23ebe8STom Stellard
830d23ebe8STom Stellard // getDownwardPressure() and getUpwardPressure() make temporary changes to
84290adb31SHiroshi Inoue // the tracker, so we need to pass those function a non-const copy.
850d23ebe8STom Stellard RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
860d23ebe8STom Stellard
87f54daffcSMatt Arsenault Pressure.clear();
88f54daffcSMatt Arsenault MaxPressure.clear();
890d23ebe8STom Stellard
900d23ebe8STom Stellard if (AtTop)
910d23ebe8STom Stellard TempTracker.getDownwardPressure(SU->getInstr(), Pressure, MaxPressure);
920d23ebe8STom Stellard else {
930d23ebe8STom Stellard // FIXME: I think for bottom up scheduling, the register pressure is cached
940d23ebe8STom Stellard // and can be retrieved by DAG->getPressureDif(SU).
950d23ebe8STom Stellard TempTracker.getUpwardPressure(SU->getInstr(), Pressure, MaxPressure);
960d23ebe8STom Stellard }
970d23ebe8STom Stellard
98dd476645SStanislav Mekhanoshin unsigned NewSGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
99dd476645SStanislav Mekhanoshin unsigned NewVGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
1000d23ebe8STom Stellard
1010d23ebe8STom Stellard // If two instructions increase the pressure of different register sets
1020d23ebe8STom Stellard // by the same amount, the generic scheduler will prefer to schedule the
1030d23ebe8STom Stellard // instruction that increases the set with the least amount of registers,
1040d23ebe8STom Stellard // which in our case would be SGPRs. This is rarely what we want, so
1050d23ebe8STom Stellard // when we report excess/critical register pressure, we do it either
1060d23ebe8STom Stellard // only for VGPRs or only for SGPRs.
1070d23ebe8STom Stellard
1080d23ebe8STom Stellard // FIXME: Better heuristics to determine whether to prefer SGPRs or VGPRs.
109582a5237SStanislav Mekhanoshin const unsigned MaxVGPRPressureInc = 16;
1100d23ebe8STom Stellard bool ShouldTrackVGPRs = VGPRPressure + MaxVGPRPressureInc >= VGPRExcessLimit;
1110d23ebe8STom Stellard bool ShouldTrackSGPRs = !ShouldTrackVGPRs && SGPRPressure >= SGPRExcessLimit;
1120d23ebe8STom Stellard
1130d23ebe8STom Stellard
1140d23ebe8STom Stellard // FIXME: We have to enter REG-EXCESS before we reach the actual threshold
1150d23ebe8STom Stellard // to increase the likelihood we don't go over the limits. We should improve
1160d23ebe8STom Stellard // the analysis to look through dependencies to find the path with the least
1170d23ebe8STom Stellard // register pressure.
1180d23ebe8STom Stellard
11902eb6a44SMatt Arsenault // We only need to update the RPDelta for instructions that increase register
12002eb6a44SMatt Arsenault // pressure. Instructions that decrease or keep reg pressure the same will be
12102eb6a44SMatt Arsenault // marked as RegExcess in tryCandidate() when they are compared with
12202eb6a44SMatt Arsenault // instructions that increase the register pressure.
1230d23ebe8STom Stellard if (ShouldTrackVGPRs && NewVGPRPressure >= VGPRExcessLimit) {
124799c50feSStanislav Mekhanoshin HasExcessPressure = true;
125dd476645SStanislav Mekhanoshin Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
1260d23ebe8STom Stellard Cand.RPDelta.Excess.setUnitInc(NewVGPRPressure - VGPRExcessLimit);
1270d23ebe8STom Stellard }
1280d23ebe8STom Stellard
1290d23ebe8STom Stellard if (ShouldTrackSGPRs && NewSGPRPressure >= SGPRExcessLimit) {
130799c50feSStanislav Mekhanoshin HasExcessPressure = true;
131dd476645SStanislav Mekhanoshin Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
13275d1de90SValery Pykhtin Cand.RPDelta.Excess.setUnitInc(NewSGPRPressure - SGPRExcessLimit);
1330d23ebe8STom Stellard }
1340d23ebe8STom Stellard
1350d23ebe8STom Stellard // Register pressure is considered 'CRITICAL' if it is approaching a value
1360d23ebe8STom Stellard // that would reduce the wave occupancy for the execution unit. When
137d1f45ed5SNeubauer, Sebastian // register pressure is 'CRITICAL', increasing SGPR and VGPR pressure both
1380d23ebe8STom Stellard // has the same cost, so we don't need to prefer one over the other.
1390d23ebe8STom Stellard
1400d23ebe8STom Stellard int SGPRDelta = NewSGPRPressure - SGPRCriticalLimit;
1410d23ebe8STom Stellard int VGPRDelta = NewVGPRPressure - VGPRCriticalLimit;
1420d23ebe8STom Stellard
1430d23ebe8STom Stellard if (SGPRDelta >= 0 || VGPRDelta >= 0) {
144799c50feSStanislav Mekhanoshin HasExcessPressure = true;
1450d23ebe8STom Stellard if (SGPRDelta > VGPRDelta) {
146dd476645SStanislav Mekhanoshin Cand.RPDelta.CriticalMax =
147dd476645SStanislav Mekhanoshin PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
1480d23ebe8STom Stellard Cand.RPDelta.CriticalMax.setUnitInc(SGPRDelta);
1490d23ebe8STom Stellard } else {
150dd476645SStanislav Mekhanoshin Cand.RPDelta.CriticalMax =
151dd476645SStanislav Mekhanoshin PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
1520d23ebe8STom Stellard Cand.RPDelta.CriticalMax.setUnitInc(VGPRDelta);
1530d23ebe8STom Stellard }
1540d23ebe8STom Stellard }
1550d23ebe8STom Stellard }
1560d23ebe8STom Stellard
1570d23ebe8STom Stellard // This function is mostly cut and pasted from
1580d23ebe8STom Stellard // GenericScheduler::pickNodeFromQueue()
pickNodeFromQueue(SchedBoundary & Zone,const CandPolicy & ZonePolicy,const RegPressureTracker & RPTracker,SchedCandidate & Cand)1590d23ebe8STom Stellard void GCNMaxOccupancySchedStrategy::pickNodeFromQueue(SchedBoundary &Zone,
1600d23ebe8STom Stellard const CandPolicy &ZonePolicy,
1610d23ebe8STom Stellard const RegPressureTracker &RPTracker,
1620d23ebe8STom Stellard SchedCandidate &Cand) {
1630d23ebe8STom Stellard const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo*>(TRI);
1640d23ebe8STom Stellard ArrayRef<unsigned> Pressure = RPTracker.getRegSetPressureAtPos();
165dd476645SStanislav Mekhanoshin unsigned SGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
166dd476645SStanislav Mekhanoshin unsigned VGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
1670d23ebe8STom Stellard ReadyQueue &Q = Zone.Available;
1680d23ebe8STom Stellard for (SUnit *SU : Q) {
1690d23ebe8STom Stellard
1700d23ebe8STom Stellard SchedCandidate TryCand(ZonePolicy);
1710d23ebe8STom Stellard initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI,
172582a5237SStanislav Mekhanoshin SGPRPressure, VGPRPressure);
1730d23ebe8STom Stellard // Pass SchedBoundary only when comparing nodes from the same boundary.
1740d23ebe8STom Stellard SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
1750d23ebe8STom Stellard GenericScheduler::tryCandidate(Cand, TryCand, ZoneArg);
1760d23ebe8STom Stellard if (TryCand.Reason != NoCand) {
1770d23ebe8STom Stellard // Initialize resource delta if needed in case future heuristics query it.
1780d23ebe8STom Stellard if (TryCand.ResDelta == SchedResourceDelta())
1790d23ebe8STom Stellard TryCand.initResourceDelta(Zone.DAG, SchedModel);
1800d23ebe8STom Stellard Cand.setBest(TryCand);
18160d419e5SJay Foad LLVM_DEBUG(traceCandidate(Cand));
1820d23ebe8STom Stellard }
1830d23ebe8STom Stellard }
1840d23ebe8STom Stellard }
1850d23ebe8STom Stellard
1860d23ebe8STom Stellard // This function is mostly cut and pasted from
1870d23ebe8STom Stellard // GenericScheduler::pickNodeBidirectional()
pickNodeBidirectional(bool & IsTopNode)1880d23ebe8STom Stellard SUnit *GCNMaxOccupancySchedStrategy::pickNodeBidirectional(bool &IsTopNode) {
1890d23ebe8STom Stellard // Schedule as far as possible in the direction of no choice. This is most
1900d23ebe8STom Stellard // efficient, but also provides the best heuristics for CriticalPSets.
1910d23ebe8STom Stellard if (SUnit *SU = Bot.pickOnlyChoice()) {
1920d23ebe8STom Stellard IsTopNode = false;
1930d23ebe8STom Stellard return SU;
1940d23ebe8STom Stellard }
1950d23ebe8STom Stellard if (SUnit *SU = Top.pickOnlyChoice()) {
1960d23ebe8STom Stellard IsTopNode = true;
1970d23ebe8STom Stellard return SU;
1980d23ebe8STom Stellard }
1990d23ebe8STom Stellard // Set the bottom-up policy based on the state of the current bottom zone and
2000d23ebe8STom Stellard // the instructions outside the zone, including the top zone.
2010d23ebe8STom Stellard CandPolicy BotPolicy;
2020d23ebe8STom Stellard setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
2030d23ebe8STom Stellard // Set the top-down policy based on the state of the current top zone and
2040d23ebe8STom Stellard // the instructions outside the zone, including the bottom zone.
2050d23ebe8STom Stellard CandPolicy TopPolicy;
2060d23ebe8STom Stellard setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
2070d23ebe8STom Stellard
2080d23ebe8STom Stellard // See if BotCand is still valid (because we previously scheduled from Top).
209d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
2100d23ebe8STom Stellard if (!BotCand.isValid() || BotCand.SU->isScheduled ||
2110d23ebe8STom Stellard BotCand.Policy != BotPolicy) {
2120d23ebe8STom Stellard BotCand.reset(CandPolicy());
2130d23ebe8STom Stellard pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
2140d23ebe8STom Stellard assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2150d23ebe8STom Stellard } else {
216d34e60caSNicola Zaghen LLVM_DEBUG(traceCandidate(BotCand));
217e5368000SJay Foad #ifndef NDEBUG
218e5368000SJay Foad if (VerifyScheduling) {
219e5368000SJay Foad SchedCandidate TCand;
220e5368000SJay Foad TCand.reset(CandPolicy());
221e5368000SJay Foad pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
222e5368000SJay Foad assert(TCand.SU == BotCand.SU &&
223e5368000SJay Foad "Last pick result should correspond to re-picking right now");
224e5368000SJay Foad }
225e5368000SJay Foad #endif
2260d23ebe8STom Stellard }
2270d23ebe8STom Stellard
2280d23ebe8STom Stellard // Check if the top Q has a better candidate.
229d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Picking from Top:\n");
2300d23ebe8STom Stellard if (!TopCand.isValid() || TopCand.SU->isScheduled ||
2310d23ebe8STom Stellard TopCand.Policy != TopPolicy) {
2320d23ebe8STom Stellard TopCand.reset(CandPolicy());
2330d23ebe8STom Stellard pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
2340d23ebe8STom Stellard assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2350d23ebe8STom Stellard } else {
236d34e60caSNicola Zaghen LLVM_DEBUG(traceCandidate(TopCand));
237e5368000SJay Foad #ifndef NDEBUG
238e5368000SJay Foad if (VerifyScheduling) {
239e5368000SJay Foad SchedCandidate TCand;
240e5368000SJay Foad TCand.reset(CandPolicy());
241e5368000SJay Foad pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
242e5368000SJay Foad assert(TCand.SU == TopCand.SU &&
243e5368000SJay Foad "Last pick result should correspond to re-picking right now");
244e5368000SJay Foad }
245e5368000SJay Foad #endif
2460d23ebe8STom Stellard }
2470d23ebe8STom Stellard
2480d23ebe8STom Stellard // Pick best from BotCand and TopCand.
249d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Top Cand: "; traceCandidate(TopCand);
250d34e60caSNicola Zaghen dbgs() << "Bot Cand: "; traceCandidate(BotCand););
25143830790SJay Foad SchedCandidate Cand = BotCand;
2520d23ebe8STom Stellard TopCand.Reason = NoCand;
2530d23ebe8STom Stellard GenericScheduler::tryCandidate(Cand, TopCand, nullptr);
2540d23ebe8STom Stellard if (TopCand.Reason != NoCand) {
2550d23ebe8STom Stellard Cand.setBest(TopCand);
2560d23ebe8STom Stellard }
257d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Picking: "; traceCandidate(Cand););
2580d23ebe8STom Stellard
2590d23ebe8STom Stellard IsTopNode = Cand.AtTop;
2600d23ebe8STom Stellard return Cand.SU;
2610d23ebe8STom Stellard }
2620d23ebe8STom Stellard
2630d23ebe8STom Stellard // This function is mostly cut and pasted from
2640d23ebe8STom Stellard // GenericScheduler::pickNode()
pickNode(bool & IsTopNode)2650d23ebe8STom Stellard SUnit *GCNMaxOccupancySchedStrategy::pickNode(bool &IsTopNode) {
2660d23ebe8STom Stellard if (DAG->top() == DAG->bottom()) {
2670d23ebe8STom Stellard assert(Top.Available.empty() && Top.Pending.empty() &&
2680d23ebe8STom Stellard Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2690d23ebe8STom Stellard return nullptr;
2700d23ebe8STom Stellard }
2710d23ebe8STom Stellard SUnit *SU;
2720d23ebe8STom Stellard do {
2730d23ebe8STom Stellard if (RegionPolicy.OnlyTopDown) {
2740d23ebe8STom Stellard SU = Top.pickOnlyChoice();
2750d23ebe8STom Stellard if (!SU) {
2760d23ebe8STom Stellard CandPolicy NoPolicy;
2770d23ebe8STom Stellard TopCand.reset(NoPolicy);
2780d23ebe8STom Stellard pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
2790d23ebe8STom Stellard assert(TopCand.Reason != NoCand && "failed to find a candidate");
2800d23ebe8STom Stellard SU = TopCand.SU;
2810d23ebe8STom Stellard }
2820d23ebe8STom Stellard IsTopNode = true;
2830d23ebe8STom Stellard } else if (RegionPolicy.OnlyBottomUp) {
2840d23ebe8STom Stellard SU = Bot.pickOnlyChoice();
2850d23ebe8STom Stellard if (!SU) {
2860d23ebe8STom Stellard CandPolicy NoPolicy;
2870d23ebe8STom Stellard BotCand.reset(NoPolicy);
2880d23ebe8STom Stellard pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
2890d23ebe8STom Stellard assert(BotCand.Reason != NoCand && "failed to find a candidate");
2900d23ebe8STom Stellard SU = BotCand.SU;
2910d23ebe8STom Stellard }
2920d23ebe8STom Stellard IsTopNode = false;
2930d23ebe8STom Stellard } else {
2940d23ebe8STom Stellard SU = pickNodeBidirectional(IsTopNode);
2950d23ebe8STom Stellard }
2960d23ebe8STom Stellard } while (SU->isScheduled);
2970d23ebe8STom Stellard
2980d23ebe8STom Stellard if (SU->isTopReady())
2990d23ebe8STom Stellard Top.removeReady(SU);
3000d23ebe8STom Stellard if (SU->isBottomReady())
3010d23ebe8STom Stellard Bot.removeReady(SU);
3020d23ebe8STom Stellard
303635993f0SStanislav Mekhanoshin if (!HasClusteredNodes && SU->getInstr()->mayLoadOrStore()) {
304635993f0SStanislav Mekhanoshin for (SDep &Dep : SU->Preds) {
305635993f0SStanislav Mekhanoshin if (Dep.isCluster()) {
306635993f0SStanislav Mekhanoshin HasClusteredNodes = true;
307635993f0SStanislav Mekhanoshin break;
308635993f0SStanislav Mekhanoshin }
309635993f0SStanislav Mekhanoshin }
310635993f0SStanislav Mekhanoshin }
311635993f0SStanislav Mekhanoshin
312d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
313d34e60caSNicola Zaghen << *SU->getInstr());
3140d23ebe8STom Stellard return SU;
3150d23ebe8STom Stellard }
316582a5237SStanislav Mekhanoshin
GCNScheduleDAGMILive(MachineSchedContext * C,std::unique_ptr<MachineSchedStrategy> S)317*7ca9e471SAustin Kerbow GCNScheduleDAGMILive::GCNScheduleDAGMILive(
318*7ca9e471SAustin Kerbow MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S)
319*7ca9e471SAustin Kerbow : ScheduleDAGMILive(C, std::move(S)), ST(MF.getSubtarget<GCNSubtarget>()),
320357d3db0SStanislav Mekhanoshin MFI(*MF.getInfo<SIMachineFunctionInfo>()),
321*7ca9e471SAustin Kerbow StartingOccupancy(MFI.getOccupancy()), MinOccupancy(StartingOccupancy) {
322357d3db0SStanislav Mekhanoshin
323d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Starting occupancy is " << StartingOccupancy << ".\n");
324357d3db0SStanislav Mekhanoshin }
325357d3db0SStanislav Mekhanoshin
schedule()326582a5237SStanislav Mekhanoshin void GCNScheduleDAGMILive::schedule() {
327*7ca9e471SAustin Kerbow // Collect all scheduling regions. The actual scheduling is performed in
328*7ca9e471SAustin Kerbow // GCNScheduleDAGMILive::finalizeSchedule.
329b1086078SStanislav Mekhanoshin Regions.push_back(std::make_pair(RegionBegin, RegionEnd));
330b1086078SStanislav Mekhanoshin }
331b1086078SStanislav Mekhanoshin
332*7ca9e471SAustin Kerbow GCNRegPressure
getRealRegPressure(unsigned RegionIdx) const333*7ca9e471SAustin Kerbow GCNScheduleDAGMILive::getRealRegPressure(unsigned RegionIdx) const {
334464cecf8SStanislav Mekhanoshin GCNDownwardRPTracker RPTracker(*LIS);
335b1086078SStanislav Mekhanoshin RPTracker.advance(begin(), end(), &LiveIns[RegionIdx]);
336464cecf8SStanislav Mekhanoshin return RPTracker.moveMaxPressure();
337282e8e4aSStanislav Mekhanoshin }
338282e8e4aSStanislav Mekhanoshin
computeBlockPressure(unsigned RegionIdx,const MachineBasicBlock * MBB)339*7ca9e471SAustin Kerbow void GCNScheduleDAGMILive::computeBlockPressure(unsigned RegionIdx,
340*7ca9e471SAustin Kerbow const MachineBasicBlock *MBB) {
341b1086078SStanislav Mekhanoshin GCNDownwardRPTracker RPTracker(*LIS);
342b1086078SStanislav Mekhanoshin
343b1086078SStanislav Mekhanoshin // If the block has the only successor then live-ins of that successor are
344b1086078SStanislav Mekhanoshin // live-outs of the current block. We can reuse calculated live set if the
345b1086078SStanislav Mekhanoshin // successor will be sent to scheduling past current block.
346b1086078SStanislav Mekhanoshin const MachineBasicBlock *OnlySucc = nullptr;
347b1086078SStanislav Mekhanoshin if (MBB->succ_size() == 1 && !(*MBB->succ_begin())->empty()) {
348b1086078SStanislav Mekhanoshin SlotIndexes *Ind = LIS->getSlotIndexes();
349b1086078SStanislav Mekhanoshin if (Ind->getMBBStartIdx(MBB) < Ind->getMBBStartIdx(*MBB->succ_begin()))
350b1086078SStanislav Mekhanoshin OnlySucc = *MBB->succ_begin();
351b1086078SStanislav Mekhanoshin }
352b1086078SStanislav Mekhanoshin
353b1086078SStanislav Mekhanoshin // Scheduler sends regions from the end of the block upwards.
354b1086078SStanislav Mekhanoshin size_t CurRegion = RegionIdx;
355b1086078SStanislav Mekhanoshin for (size_t E = Regions.size(); CurRegion != E; ++CurRegion)
356b1086078SStanislav Mekhanoshin if (Regions[CurRegion].first->getParent() != MBB)
357b1086078SStanislav Mekhanoshin break;
358b1086078SStanislav Mekhanoshin --CurRegion;
359b1086078SStanislav Mekhanoshin
360b1086078SStanislav Mekhanoshin auto I = MBB->begin();
361b1086078SStanislav Mekhanoshin auto LiveInIt = MBBLiveIns.find(MBB);
3622ca194ffSVang Thao auto &Rgn = Regions[CurRegion];
3632ca194ffSVang Thao auto *NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
364b1086078SStanislav Mekhanoshin if (LiveInIt != MBBLiveIns.end()) {
365b1086078SStanislav Mekhanoshin auto LiveIn = std::move(LiveInIt->second);
366b1086078SStanislav Mekhanoshin RPTracker.reset(*MBB->begin(), &LiveIn);
367b1086078SStanislav Mekhanoshin MBBLiveIns.erase(LiveInIt);
368b1086078SStanislav Mekhanoshin } else {
3697e854e1cSValery Pykhtin I = Rgn.first;
3707e854e1cSValery Pykhtin auto LRS = BBLiveInMap.lookup(NonDbgMI);
371bb16efe2SStanislav Mekhanoshin #ifdef EXPENSIVE_CHECKS
3727e854e1cSValery Pykhtin assert(isEqual(getLiveRegsBefore(*NonDbgMI, *LIS), LRS));
373bb16efe2SStanislav Mekhanoshin #endif
3747e854e1cSValery Pykhtin RPTracker.reset(*I, &LRS);
375b1086078SStanislav Mekhanoshin }
376b1086078SStanislav Mekhanoshin
377b1086078SStanislav Mekhanoshin for (;;) {
378b1086078SStanislav Mekhanoshin I = RPTracker.getNext();
379b1086078SStanislav Mekhanoshin
3802ca194ffSVang Thao if (Regions[CurRegion].first == I || NonDbgMI == I) {
381b1086078SStanislav Mekhanoshin LiveIns[CurRegion] = RPTracker.getLiveRegs();
382b1086078SStanislav Mekhanoshin RPTracker.clearMaxPressure();
383b1086078SStanislav Mekhanoshin }
384b1086078SStanislav Mekhanoshin
385b1086078SStanislav Mekhanoshin if (Regions[CurRegion].second == I) {
386b1086078SStanislav Mekhanoshin Pressure[CurRegion] = RPTracker.moveMaxPressure();
387b1086078SStanislav Mekhanoshin if (CurRegion-- == RegionIdx)
388b1086078SStanislav Mekhanoshin break;
389b1086078SStanislav Mekhanoshin }
390b1086078SStanislav Mekhanoshin RPTracker.advanceToNext();
391b1086078SStanislav Mekhanoshin RPTracker.advanceBeforeNext();
392b1086078SStanislav Mekhanoshin }
393b1086078SStanislav Mekhanoshin
394b1086078SStanislav Mekhanoshin if (OnlySucc) {
395b1086078SStanislav Mekhanoshin if (I != MBB->end()) {
396b1086078SStanislav Mekhanoshin RPTracker.advanceToNext();
397b1086078SStanislav Mekhanoshin RPTracker.advance(MBB->end());
398b1086078SStanislav Mekhanoshin }
399b1086078SStanislav Mekhanoshin RPTracker.reset(*OnlySucc->begin(), &RPTracker.getLiveRegs());
400b1086078SStanislav Mekhanoshin RPTracker.advanceBeforeNext();
401b1086078SStanislav Mekhanoshin MBBLiveIns[OnlySucc] = RPTracker.moveLiveRegs();
402b1086078SStanislav Mekhanoshin }
403b1086078SStanislav Mekhanoshin }
404b1086078SStanislav Mekhanoshin
4057e854e1cSValery Pykhtin DenseMap<MachineInstr *, GCNRPTracker::LiveRegSet>
getBBLiveInMap() const4067e854e1cSValery Pykhtin GCNScheduleDAGMILive::getBBLiveInMap() const {
4077e854e1cSValery Pykhtin assert(!Regions.empty());
4087e854e1cSValery Pykhtin std::vector<MachineInstr *> BBStarters;
4097e854e1cSValery Pykhtin BBStarters.reserve(Regions.size());
4107e854e1cSValery Pykhtin auto I = Regions.rbegin(), E = Regions.rend();
4117e854e1cSValery Pykhtin auto *BB = I->first->getParent();
4127e854e1cSValery Pykhtin do {
4137e854e1cSValery Pykhtin auto *MI = &*skipDebugInstructionsForward(I->first, I->second);
4147e854e1cSValery Pykhtin BBStarters.push_back(MI);
4157e854e1cSValery Pykhtin do {
4167e854e1cSValery Pykhtin ++I;
4177e854e1cSValery Pykhtin } while (I != E && I->first->getParent() == BB);
4187e854e1cSValery Pykhtin } while (I != E);
4197e854e1cSValery Pykhtin return getLiveRegMap(BBStarters, false /*After*/, *LIS);
4207e854e1cSValery Pykhtin }
4217e854e1cSValery Pykhtin
finalizeSchedule()422282e8e4aSStanislav Mekhanoshin void GCNScheduleDAGMILive::finalizeSchedule() {
423*7ca9e471SAustin Kerbow // Start actual scheduling here. This function is called by the base
424*7ca9e471SAustin Kerbow // MachineScheduler after all regions have been recorded by
425*7ca9e471SAustin Kerbow // GCNScheduleDAGMILive::schedule().
426b1086078SStanislav Mekhanoshin LiveIns.resize(Regions.size());
427b1086078SStanislav Mekhanoshin Pressure.resize(Regions.size());
42853eb0f8cSStanislav Mekhanoshin RescheduleRegions.resize(Regions.size());
429799c50feSStanislav Mekhanoshin RegionsWithClusters.resize(Regions.size());
430799c50feSStanislav Mekhanoshin RegionsWithHighRP.resize(Regions.size());
43128322c25SVang Thao RegionsWithMinOcc.resize(Regions.size());
43253eb0f8cSStanislav Mekhanoshin RescheduleRegions.set();
433799c50feSStanislav Mekhanoshin RegionsWithClusters.reset();
434799c50feSStanislav Mekhanoshin RegionsWithHighRP.reset();
43528322c25SVang Thao RegionsWithMinOcc.reset();
436b1086078SStanislav Mekhanoshin
437*7ca9e471SAustin Kerbow runSchedStages();
438*7ca9e471SAustin Kerbow }
439*7ca9e471SAustin Kerbow
runSchedStages()440*7ca9e471SAustin Kerbow void GCNScheduleDAGMILive::runSchedStages() {
441*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "All regions recorded, starting actual scheduling.\n");
442*7ca9e471SAustin Kerbow InitialScheduleStage S0(GCNSchedStageID::InitialSchedule, *this);
443*7ca9e471SAustin Kerbow UnclusteredRescheduleStage S1(GCNSchedStageID::UnclusteredReschedule, *this);
444*7ca9e471SAustin Kerbow ClusteredLowOccStage S2(GCNSchedStageID::ClusteredLowOccupancyReschedule,
445*7ca9e471SAustin Kerbow *this);
446*7ca9e471SAustin Kerbow PreRARematStage S3(GCNSchedStageID::PreRARematerialize, *this);
447*7ca9e471SAustin Kerbow GCNSchedStage *SchedStages[] = {&S0, &S1, &S2, &S3};
448*7ca9e471SAustin Kerbow
4497e854e1cSValery Pykhtin if (!Regions.empty())
4507e854e1cSValery Pykhtin BBLiveInMap = getBBLiveInMap();
4517e854e1cSValery Pykhtin
452*7ca9e471SAustin Kerbow for (auto *Stage : SchedStages) {
453*7ca9e471SAustin Kerbow if (!Stage->initGCNSchedStage())
45453eb0f8cSStanislav Mekhanoshin continue;
455*7ca9e471SAustin Kerbow
456*7ca9e471SAustin Kerbow for (auto Region : Regions) {
457*7ca9e471SAustin Kerbow RegionBegin = Region.first;
458*7ca9e471SAustin Kerbow RegionEnd = Region.second;
459*7ca9e471SAustin Kerbow // Setup for scheduling the region and check whether it should be skipped.
460*7ca9e471SAustin Kerbow if (!Stage->initGCNRegion()) {
461*7ca9e471SAustin Kerbow Stage->advanceRegion();
462*7ca9e471SAustin Kerbow exitRegion();
463*7ca9e471SAustin Kerbow continue;
46453eb0f8cSStanislav Mekhanoshin }
46553eb0f8cSStanislav Mekhanoshin
466*7ca9e471SAustin Kerbow ScheduleDAGMILive::schedule();
467*7ca9e471SAustin Kerbow Stage->finalizeGCNRegion();
468*7ca9e471SAustin Kerbow }
469*7ca9e471SAustin Kerbow
470*7ca9e471SAustin Kerbow Stage->finalizeGCNSchedStage();
471*7ca9e471SAustin Kerbow }
472*7ca9e471SAustin Kerbow }
473*7ca9e471SAustin Kerbow
474*7ca9e471SAustin Kerbow #ifndef NDEBUG
operator <<(raw_ostream & OS,const GCNSchedStageID & StageID)475*7ca9e471SAustin Kerbow raw_ostream &llvm::operator<<(raw_ostream &OS, const GCNSchedStageID &StageID) {
476*7ca9e471SAustin Kerbow switch (StageID) {
477*7ca9e471SAustin Kerbow case GCNSchedStageID::InitialSchedule:
478*7ca9e471SAustin Kerbow OS << "Initial Schedule";
479b1086078SStanislav Mekhanoshin break;
480*7ca9e471SAustin Kerbow case GCNSchedStageID::UnclusteredReschedule:
481*7ca9e471SAustin Kerbow OS << "Unclustered Reschedule";
482*7ca9e471SAustin Kerbow break;
483*7ca9e471SAustin Kerbow case GCNSchedStageID::ClusteredLowOccupancyReschedule:
484*7ca9e471SAustin Kerbow OS << "Clustered Low Occupancy Reschedule";
485*7ca9e471SAustin Kerbow break;
486*7ca9e471SAustin Kerbow case GCNSchedStageID::PreRARematerialize:
487*7ca9e471SAustin Kerbow OS << "Pre-RA Rematerialize";
488*7ca9e471SAustin Kerbow break;
489*7ca9e471SAustin Kerbow }
490*7ca9e471SAustin Kerbow return OS;
491*7ca9e471SAustin Kerbow }
492*7ca9e471SAustin Kerbow #endif
493*7ca9e471SAustin Kerbow
GCNSchedStage(GCNSchedStageID StageID,GCNScheduleDAGMILive & DAG)494*7ca9e471SAustin Kerbow GCNSchedStage::GCNSchedStage(GCNSchedStageID StageID, GCNScheduleDAGMILive &DAG)
495*7ca9e471SAustin Kerbow : DAG(DAG), S(static_cast<GCNMaxOccupancySchedStrategy &>(*DAG.SchedImpl)),
496*7ca9e471SAustin Kerbow MF(DAG.MF), MFI(DAG.MFI), ST(DAG.ST), StageID(StageID) {}
497*7ca9e471SAustin Kerbow
initGCNSchedStage()498*7ca9e471SAustin Kerbow bool GCNSchedStage::initGCNSchedStage() {
499*7ca9e471SAustin Kerbow if (!DAG.LIS)
500*7ca9e471SAustin Kerbow return false;
501*7ca9e471SAustin Kerbow
502*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Starting scheduling stage: " << StageID << "\n");
503*7ca9e471SAustin Kerbow return true;
504*7ca9e471SAustin Kerbow }
505*7ca9e471SAustin Kerbow
initGCNSchedStage()506*7ca9e471SAustin Kerbow bool UnclusteredRescheduleStage::initGCNSchedStage() {
507*7ca9e471SAustin Kerbow if (!GCNSchedStage::initGCNSchedStage())
508*7ca9e471SAustin Kerbow return false;
509*7ca9e471SAustin Kerbow
510*7ca9e471SAustin Kerbow if (DAG.RescheduleRegions.none())
511*7ca9e471SAustin Kerbow return false;
512*7ca9e471SAustin Kerbow
513*7ca9e471SAustin Kerbow SavedMutations.swap(DAG.Mutations);
514*7ca9e471SAustin Kerbow
515*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Retrying function scheduling without clustering.\n");
516*7ca9e471SAustin Kerbow return true;
517*7ca9e471SAustin Kerbow }
518*7ca9e471SAustin Kerbow
initGCNSchedStage()519*7ca9e471SAustin Kerbow bool ClusteredLowOccStage::initGCNSchedStage() {
520*7ca9e471SAustin Kerbow if (!GCNSchedStage::initGCNSchedStage())
521*7ca9e471SAustin Kerbow return false;
522*7ca9e471SAustin Kerbow
523*7ca9e471SAustin Kerbow // Don't bother trying to improve ILP in lower RP regions if occupancy has not
524*7ca9e471SAustin Kerbow // been dropped. All regions will have already been scheduled with the ideal
525*7ca9e471SAustin Kerbow // occupancy targets.
526*7ca9e471SAustin Kerbow if (DAG.StartingOccupancy <= DAG.MinOccupancy)
527*7ca9e471SAustin Kerbow return false;
528357d3db0SStanislav Mekhanoshin
529d34e60caSNicola Zaghen LLVM_DEBUG(
530*7ca9e471SAustin Kerbow dbgs() << "Retrying function scheduling with lowest recorded occupancy "
531*7ca9e471SAustin Kerbow << DAG.MinOccupancy << ".\n");
532*7ca9e471SAustin Kerbow return true;
533b1086078SStanislav Mekhanoshin }
53428322c25SVang Thao
initGCNSchedStage()535*7ca9e471SAustin Kerbow bool PreRARematStage::initGCNSchedStage() {
536*7ca9e471SAustin Kerbow if (!GCNSchedStage::initGCNSchedStage())
537*7ca9e471SAustin Kerbow return false;
53828322c25SVang Thao
539*7ca9e471SAustin Kerbow if (DAG.RegionsWithMinOcc.none() || DAG.Regions.size() == 1)
540*7ca9e471SAustin Kerbow return false;
541*7ca9e471SAustin Kerbow
54228322c25SVang Thao const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
54328322c25SVang Thao // Check maximum occupancy
54428322c25SVang Thao if (ST.computeOccupancy(MF.getFunction(), MFI.getLDSSize()) ==
545*7ca9e471SAustin Kerbow DAG.MinOccupancy)
546*7ca9e471SAustin Kerbow return false;
54728322c25SVang Thao
548311edc6bSVang Thao // FIXME: This pass will invalidate cached MBBLiveIns for regions
549311edc6bSVang Thao // inbetween the defs and region we sinked the def to. Cached pressure
550311edc6bSVang Thao // for regions where a def is sinked from will also be invalidated. Will
551311edc6bSVang Thao // need to be fixed if there is another pass after this pass.
55228322c25SVang Thao
553311edc6bSVang Thao collectRematerializableInstructions();
554311edc6bSVang Thao if (RematerializableInsts.empty() || !sinkTriviallyRematInsts(ST, TII))
555*7ca9e471SAustin Kerbow return false;
55628322c25SVang Thao
55728322c25SVang Thao LLVM_DEBUG(
55828322c25SVang Thao dbgs() << "Retrying function scheduling with improved occupancy of "
559*7ca9e471SAustin Kerbow << DAG.MinOccupancy << " from rematerializing\n");
560*7ca9e471SAustin Kerbow return true;
56153eb0f8cSStanislav Mekhanoshin }
56253eb0f8cSStanislav Mekhanoshin
finalizeGCNSchedStage()563*7ca9e471SAustin Kerbow void GCNSchedStage::finalizeGCNSchedStage() {
564*7ca9e471SAustin Kerbow DAG.finishBlock();
565*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Ending scheduling stage: " << StageID << "\n");
56604bd5b52SVang Thao }
56753eb0f8cSStanislav Mekhanoshin
finalizeGCNSchedStage()568*7ca9e471SAustin Kerbow void UnclusteredRescheduleStage::finalizeGCNSchedStage() {
569*7ca9e471SAustin Kerbow SavedMutations.swap(DAG.Mutations);
570357d3db0SStanislav Mekhanoshin
571*7ca9e471SAustin Kerbow GCNSchedStage::finalizeGCNSchedStage();
572357d3db0SStanislav Mekhanoshin }
573357d3db0SStanislav Mekhanoshin
initGCNRegion()574*7ca9e471SAustin Kerbow bool GCNSchedStage::initGCNRegion() {
575*7ca9e471SAustin Kerbow // Check whether this new region is also a new block.
576*7ca9e471SAustin Kerbow if (DAG.RegionBegin->getParent() != CurrentMBB)
577*7ca9e471SAustin Kerbow setupNewBlock();
578*7ca9e471SAustin Kerbow
579*7ca9e471SAustin Kerbow unsigned NumRegionInstrs = std::distance(DAG.begin(), DAG.end());
580*7ca9e471SAustin Kerbow DAG.enterRegion(CurrentMBB, DAG.begin(), DAG.end(), NumRegionInstrs);
581357d3db0SStanislav Mekhanoshin
582357d3db0SStanislav Mekhanoshin // Skip empty scheduling regions (0 or 1 schedulable instructions).
583*7ca9e471SAustin Kerbow if (DAG.begin() == DAG.end() || DAG.begin() == std::prev(DAG.end()))
584*7ca9e471SAustin Kerbow return false;
585b1086078SStanislav Mekhanoshin
586d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
587*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << MF.getName() << ":" << printMBBReference(*CurrentMBB)
588*7ca9e471SAustin Kerbow << " " << CurrentMBB->getName()
589*7ca9e471SAustin Kerbow << "\n From: " << *DAG.begin() << " To: ";
590*7ca9e471SAustin Kerbow if (DAG.RegionEnd != CurrentMBB->end()) dbgs() << *DAG.RegionEnd;
591357d3db0SStanislav Mekhanoshin else dbgs() << "End";
592357d3db0SStanislav Mekhanoshin dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
593357d3db0SStanislav Mekhanoshin
594*7ca9e471SAustin Kerbow // Save original instruction order before scheduling for possible revert.
595*7ca9e471SAustin Kerbow Unsched.clear();
596*7ca9e471SAustin Kerbow Unsched.reserve(DAG.NumRegionInstrs);
597*7ca9e471SAustin Kerbow for (auto &I : DAG)
598*7ca9e471SAustin Kerbow Unsched.push_back(&I);
599357d3db0SStanislav Mekhanoshin
600*7ca9e471SAustin Kerbow PressureBefore = DAG.Pressure[RegionIdx];
601b1086078SStanislav Mekhanoshin
602*7ca9e471SAustin Kerbow LLVM_DEBUG(
603*7ca9e471SAustin Kerbow dbgs() << "Pressure before scheduling:\nRegion live-ins:";
604*7ca9e471SAustin Kerbow GCNRPTracker::printLiveRegs(dbgs(), DAG.LiveIns[RegionIdx], DAG.MRI);
605*7ca9e471SAustin Kerbow dbgs() << "Region live-in pressure: ";
606*7ca9e471SAustin Kerbow llvm::getRegPressure(DAG.MRI, DAG.LiveIns[RegionIdx]).print(dbgs());
607*7ca9e471SAustin Kerbow dbgs() << "Region register pressure: "; PressureBefore.print(dbgs()));
608*7ca9e471SAustin Kerbow
609*7ca9e471SAustin Kerbow // Set HasClusteredNodes to true for late stages where we have already
610*7ca9e471SAustin Kerbow // collected it. That way pickNode() will not scan SDep's when not needed.
611*7ca9e471SAustin Kerbow S.HasClusteredNodes = StageID > GCNSchedStageID::InitialSchedule;
612*7ca9e471SAustin Kerbow S.HasExcessPressure = false;
613*7ca9e471SAustin Kerbow
614*7ca9e471SAustin Kerbow return true;
615282e8e4aSStanislav Mekhanoshin }
61628322c25SVang Thao
initGCNRegion()617*7ca9e471SAustin Kerbow bool UnclusteredRescheduleStage::initGCNRegion() {
618*7ca9e471SAustin Kerbow if (!DAG.RescheduleRegions[RegionIdx])
619*7ca9e471SAustin Kerbow return false;
620*7ca9e471SAustin Kerbow
621*7ca9e471SAustin Kerbow return GCNSchedStage::initGCNRegion();
622*7ca9e471SAustin Kerbow }
623*7ca9e471SAustin Kerbow
initGCNRegion()624*7ca9e471SAustin Kerbow bool ClusteredLowOccStage::initGCNRegion() {
625*7ca9e471SAustin Kerbow // We may need to reschedule this region if it doesn't have clusters so it
626*7ca9e471SAustin Kerbow // wasn't rescheduled in the last stage, or if we found it was testing
627*7ca9e471SAustin Kerbow // critical register pressure limits in the unclustered reschedule stage. The
628*7ca9e471SAustin Kerbow // later is because we may not have been able to raise the min occupancy in
629*7ca9e471SAustin Kerbow // the previous stage so the region may be overly constrained even if it was
630*7ca9e471SAustin Kerbow // already rescheduled.
631*7ca9e471SAustin Kerbow if (!DAG.RegionsWithClusters[RegionIdx] && !DAG.RegionsWithHighRP[RegionIdx])
632*7ca9e471SAustin Kerbow return false;
633*7ca9e471SAustin Kerbow
634*7ca9e471SAustin Kerbow return GCNSchedStage::initGCNRegion();
635*7ca9e471SAustin Kerbow }
636*7ca9e471SAustin Kerbow
initGCNRegion()637*7ca9e471SAustin Kerbow bool PreRARematStage::initGCNRegion() {
638*7ca9e471SAustin Kerbow if (!DAG.RescheduleRegions[RegionIdx])
639*7ca9e471SAustin Kerbow return false;
640*7ca9e471SAustin Kerbow
641*7ca9e471SAustin Kerbow return GCNSchedStage::initGCNRegion();
642*7ca9e471SAustin Kerbow }
643*7ca9e471SAustin Kerbow
setupNewBlock()644*7ca9e471SAustin Kerbow void GCNSchedStage::setupNewBlock() {
645*7ca9e471SAustin Kerbow if (CurrentMBB)
646*7ca9e471SAustin Kerbow DAG.finishBlock();
647*7ca9e471SAustin Kerbow
648*7ca9e471SAustin Kerbow CurrentMBB = DAG.RegionBegin->getParent();
649*7ca9e471SAustin Kerbow DAG.startBlock(CurrentMBB);
650*7ca9e471SAustin Kerbow // Get real RP for the region if it hasn't be calculated before. After the
651*7ca9e471SAustin Kerbow // initial schedule stage real RP will be collected after scheduling.
652*7ca9e471SAustin Kerbow if (StageID == GCNSchedStageID::InitialSchedule)
653*7ca9e471SAustin Kerbow DAG.computeBlockPressure(RegionIdx, CurrentMBB);
654*7ca9e471SAustin Kerbow }
655*7ca9e471SAustin Kerbow
finalizeGCNRegion()656*7ca9e471SAustin Kerbow void GCNSchedStage::finalizeGCNRegion() {
657*7ca9e471SAustin Kerbow DAG.Regions[RegionIdx] = std::make_pair(DAG.RegionBegin, DAG.RegionEnd);
658*7ca9e471SAustin Kerbow DAG.RescheduleRegions[RegionIdx] = false;
659*7ca9e471SAustin Kerbow if (S.HasExcessPressure)
660*7ca9e471SAustin Kerbow DAG.RegionsWithHighRP[RegionIdx] = true;
661*7ca9e471SAustin Kerbow
662*7ca9e471SAustin Kerbow // Revert scheduling if we have dropped occupancy or there is some other
663*7ca9e471SAustin Kerbow // reason that the original schedule is better.
664*7ca9e471SAustin Kerbow checkScheduling();
665*7ca9e471SAustin Kerbow
666*7ca9e471SAustin Kerbow DAG.exitRegion();
667*7ca9e471SAustin Kerbow RegionIdx++;
668*7ca9e471SAustin Kerbow }
669*7ca9e471SAustin Kerbow
finalizeGCNRegion()670*7ca9e471SAustin Kerbow void InitialScheduleStage::finalizeGCNRegion() {
671*7ca9e471SAustin Kerbow // Record which regions have clustered nodes for the next unclustered
672*7ca9e471SAustin Kerbow // reschedule stage.
673*7ca9e471SAustin Kerbow assert(nextStage(StageID) == GCNSchedStageID::UnclusteredReschedule);
674*7ca9e471SAustin Kerbow if (S.HasClusteredNodes)
675*7ca9e471SAustin Kerbow DAG.RegionsWithClusters[RegionIdx] = true;
676*7ca9e471SAustin Kerbow
677*7ca9e471SAustin Kerbow GCNSchedStage::finalizeGCNRegion();
678*7ca9e471SAustin Kerbow }
679*7ca9e471SAustin Kerbow
checkScheduling()680*7ca9e471SAustin Kerbow void GCNSchedStage::checkScheduling() {
681*7ca9e471SAustin Kerbow // Check the results of scheduling.
682*7ca9e471SAustin Kerbow PressureAfter = DAG.getRealRegPressure(RegionIdx);
683*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Pressure after scheduling: ";
684*7ca9e471SAustin Kerbow PressureAfter.print(dbgs()));
685*7ca9e471SAustin Kerbow
686*7ca9e471SAustin Kerbow if (PressureAfter.getSGPRNum() <= S.SGPRCriticalLimit &&
687*7ca9e471SAustin Kerbow PressureAfter.getVGPRNum(ST.hasGFX90AInsts()) <= S.VGPRCriticalLimit) {
688*7ca9e471SAustin Kerbow DAG.Pressure[RegionIdx] = PressureAfter;
689*7ca9e471SAustin Kerbow DAG.RegionsWithMinOcc[RegionIdx] =
690*7ca9e471SAustin Kerbow PressureAfter.getOccupancy(ST) == DAG.MinOccupancy;
691*7ca9e471SAustin Kerbow
692*7ca9e471SAustin Kerbow // Early out if we have achieve the occupancy target.
693*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Pressure in desired limits, done.\n");
694*7ca9e471SAustin Kerbow return;
695*7ca9e471SAustin Kerbow }
696*7ca9e471SAustin Kerbow
697*7ca9e471SAustin Kerbow unsigned WavesAfter =
698*7ca9e471SAustin Kerbow std::min(S.getTargetOccupancy(), PressureAfter.getOccupancy(ST));
699*7ca9e471SAustin Kerbow unsigned WavesBefore =
700*7ca9e471SAustin Kerbow std::min(S.getTargetOccupancy(), PressureBefore.getOccupancy(ST));
701*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Occupancy before scheduling: " << WavesBefore
702*7ca9e471SAustin Kerbow << ", after " << WavesAfter << ".\n");
703*7ca9e471SAustin Kerbow
704*7ca9e471SAustin Kerbow // We may not be able to keep the current target occupancy because of the just
705*7ca9e471SAustin Kerbow // scheduled region. We might still be able to revert scheduling if the
706*7ca9e471SAustin Kerbow // occupancy before was higher, or if the current schedule has register
707*7ca9e471SAustin Kerbow // pressure higher than the excess limits which could lead to more spilling.
708*7ca9e471SAustin Kerbow unsigned NewOccupancy = std::max(WavesAfter, WavesBefore);
709*7ca9e471SAustin Kerbow
710*7ca9e471SAustin Kerbow // Allow memory bound functions to drop to 4 waves if not limited by an
711*7ca9e471SAustin Kerbow // attribute.
712*7ca9e471SAustin Kerbow if (WavesAfter < WavesBefore && WavesAfter < DAG.MinOccupancy &&
713*7ca9e471SAustin Kerbow WavesAfter >= MFI.getMinAllowedOccupancy()) {
714*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Function is memory bound, allow occupancy drop up to "
715*7ca9e471SAustin Kerbow << MFI.getMinAllowedOccupancy() << " waves\n");
716*7ca9e471SAustin Kerbow NewOccupancy = WavesAfter;
717*7ca9e471SAustin Kerbow }
718*7ca9e471SAustin Kerbow
719*7ca9e471SAustin Kerbow if (NewOccupancy < DAG.MinOccupancy) {
720*7ca9e471SAustin Kerbow DAG.MinOccupancy = NewOccupancy;
721*7ca9e471SAustin Kerbow MFI.limitOccupancy(DAG.MinOccupancy);
722*7ca9e471SAustin Kerbow DAG.RegionsWithMinOcc.reset();
723*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Occupancy lowered for the function to "
724*7ca9e471SAustin Kerbow << DAG.MinOccupancy << ".\n");
725*7ca9e471SAustin Kerbow }
726*7ca9e471SAustin Kerbow
727*7ca9e471SAustin Kerbow unsigned MaxVGPRs = ST.getMaxNumVGPRs(MF);
728*7ca9e471SAustin Kerbow unsigned MaxSGPRs = ST.getMaxNumSGPRs(MF);
729*7ca9e471SAustin Kerbow if (PressureAfter.getVGPRNum(false) > MaxVGPRs ||
730*7ca9e471SAustin Kerbow PressureAfter.getAGPRNum() > MaxVGPRs ||
731*7ca9e471SAustin Kerbow PressureAfter.getSGPRNum() > MaxSGPRs) {
732*7ca9e471SAustin Kerbow DAG.RescheduleRegions[RegionIdx] = true;
733*7ca9e471SAustin Kerbow DAG.RegionsWithHighRP[RegionIdx] = true;
734*7ca9e471SAustin Kerbow }
735*7ca9e471SAustin Kerbow
736*7ca9e471SAustin Kerbow // Revert if this region's schedule would cause a drop in occupancy or
737*7ca9e471SAustin Kerbow // spilling.
738*7ca9e471SAustin Kerbow if (shouldRevertScheduling(WavesAfter)) {
739*7ca9e471SAustin Kerbow revertScheduling();
740*7ca9e471SAustin Kerbow } else {
741*7ca9e471SAustin Kerbow DAG.Pressure[RegionIdx] = PressureAfter;
742*7ca9e471SAustin Kerbow DAG.RegionsWithMinOcc[RegionIdx] =
743*7ca9e471SAustin Kerbow PressureAfter.getOccupancy(ST) == DAG.MinOccupancy;
744*7ca9e471SAustin Kerbow }
745*7ca9e471SAustin Kerbow }
746*7ca9e471SAustin Kerbow
shouldRevertScheduling(unsigned WavesAfter)747*7ca9e471SAustin Kerbow bool GCNSchedStage::shouldRevertScheduling(unsigned WavesAfter) {
748*7ca9e471SAustin Kerbow if (WavesAfter < DAG.MinOccupancy)
749*7ca9e471SAustin Kerbow return true;
750*7ca9e471SAustin Kerbow
751*7ca9e471SAustin Kerbow return false;
752*7ca9e471SAustin Kerbow }
753*7ca9e471SAustin Kerbow
shouldRevertScheduling(unsigned WavesAfter)754*7ca9e471SAustin Kerbow bool InitialScheduleStage::shouldRevertScheduling(unsigned WavesAfter) {
755*7ca9e471SAustin Kerbow if (GCNSchedStage::shouldRevertScheduling(WavesAfter))
756*7ca9e471SAustin Kerbow return true;
757*7ca9e471SAustin Kerbow
758*7ca9e471SAustin Kerbow if (mayCauseSpilling(WavesAfter))
759*7ca9e471SAustin Kerbow return true;
760*7ca9e471SAustin Kerbow
761*7ca9e471SAustin Kerbow assert(nextStage(StageID) == GCNSchedStageID::UnclusteredReschedule);
762*7ca9e471SAustin Kerbow // Don't reschedule the region in the next stage if it doesn't have clusters.
763*7ca9e471SAustin Kerbow if (!DAG.RegionsWithClusters[RegionIdx])
764*7ca9e471SAustin Kerbow DAG.RescheduleRegions[RegionIdx] = false;
765*7ca9e471SAustin Kerbow
766*7ca9e471SAustin Kerbow return false;
767*7ca9e471SAustin Kerbow }
768*7ca9e471SAustin Kerbow
shouldRevertScheduling(unsigned WavesAfter)769*7ca9e471SAustin Kerbow bool UnclusteredRescheduleStage::shouldRevertScheduling(unsigned WavesAfter) {
770*7ca9e471SAustin Kerbow if (GCNSchedStage::shouldRevertScheduling(WavesAfter))
771*7ca9e471SAustin Kerbow return true;
772*7ca9e471SAustin Kerbow
773*7ca9e471SAustin Kerbow // If RP is not reduced in the unclustred reschedule stage, revert to the old
774*7ca9e471SAustin Kerbow // schedule.
775*7ca9e471SAustin Kerbow if (!PressureAfter.less(ST, PressureBefore)) {
776*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Unclustered reschedule did not help.\n");
777*7ca9e471SAustin Kerbow return true;
778*7ca9e471SAustin Kerbow }
779*7ca9e471SAustin Kerbow
780*7ca9e471SAustin Kerbow return false;
781*7ca9e471SAustin Kerbow }
782*7ca9e471SAustin Kerbow
shouldRevertScheduling(unsigned WavesAfter)783*7ca9e471SAustin Kerbow bool ClusteredLowOccStage::shouldRevertScheduling(unsigned WavesAfter) {
784*7ca9e471SAustin Kerbow if (GCNSchedStage::shouldRevertScheduling(WavesAfter))
785*7ca9e471SAustin Kerbow return true;
786*7ca9e471SAustin Kerbow
787*7ca9e471SAustin Kerbow if (mayCauseSpilling(WavesAfter))
788*7ca9e471SAustin Kerbow return true;
789*7ca9e471SAustin Kerbow
790*7ca9e471SAustin Kerbow return false;
791*7ca9e471SAustin Kerbow }
792*7ca9e471SAustin Kerbow
shouldRevertScheduling(unsigned WavesAfter)793*7ca9e471SAustin Kerbow bool PreRARematStage::shouldRevertScheduling(unsigned WavesAfter) {
794*7ca9e471SAustin Kerbow if (GCNSchedStage::shouldRevertScheduling(WavesAfter))
795*7ca9e471SAustin Kerbow return true;
796*7ca9e471SAustin Kerbow
797*7ca9e471SAustin Kerbow if (mayCauseSpilling(WavesAfter))
798*7ca9e471SAustin Kerbow return true;
799*7ca9e471SAustin Kerbow
800*7ca9e471SAustin Kerbow return false;
801*7ca9e471SAustin Kerbow }
802*7ca9e471SAustin Kerbow
mayCauseSpilling(unsigned WavesAfter)803*7ca9e471SAustin Kerbow bool GCNSchedStage::mayCauseSpilling(unsigned WavesAfter) {
804*7ca9e471SAustin Kerbow if (WavesAfter <= MFI.getMinWavesPerEU() &&
805*7ca9e471SAustin Kerbow !PressureAfter.less(ST, PressureBefore) &&
806*7ca9e471SAustin Kerbow DAG.RescheduleRegions[RegionIdx]) {
807*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "New pressure will result in more spilling.\n");
808*7ca9e471SAustin Kerbow return true;
809*7ca9e471SAustin Kerbow }
810*7ca9e471SAustin Kerbow
811*7ca9e471SAustin Kerbow return false;
812*7ca9e471SAustin Kerbow }
813*7ca9e471SAustin Kerbow
revertScheduling()814*7ca9e471SAustin Kerbow void GCNSchedStage::revertScheduling() {
815*7ca9e471SAustin Kerbow DAG.RegionsWithMinOcc[RegionIdx] =
816*7ca9e471SAustin Kerbow PressureBefore.getOccupancy(ST) == DAG.MinOccupancy;
817*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Attempting to revert scheduling.\n");
818*7ca9e471SAustin Kerbow DAG.RescheduleRegions[RegionIdx] =
819*7ca9e471SAustin Kerbow DAG.RegionsWithClusters[RegionIdx] ||
820*7ca9e471SAustin Kerbow (nextStage(StageID)) != GCNSchedStageID::UnclusteredReschedule;
821*7ca9e471SAustin Kerbow DAG.RegionEnd = DAG.RegionBegin;
822*7ca9e471SAustin Kerbow int SkippedDebugInstr = 0;
823*7ca9e471SAustin Kerbow for (MachineInstr *MI : Unsched) {
824*7ca9e471SAustin Kerbow if (MI->isDebugInstr()) {
825*7ca9e471SAustin Kerbow ++SkippedDebugInstr;
826*7ca9e471SAustin Kerbow continue;
827*7ca9e471SAustin Kerbow }
828*7ca9e471SAustin Kerbow
829*7ca9e471SAustin Kerbow if (MI->getIterator() != DAG.RegionEnd) {
830*7ca9e471SAustin Kerbow DAG.BB->remove(MI);
831*7ca9e471SAustin Kerbow DAG.BB->insert(DAG.RegionEnd, MI);
832*7ca9e471SAustin Kerbow if (!MI->isDebugInstr())
833*7ca9e471SAustin Kerbow DAG.LIS->handleMove(*MI, true);
834*7ca9e471SAustin Kerbow }
835*7ca9e471SAustin Kerbow
836*7ca9e471SAustin Kerbow // Reset read-undef flags and update them later.
837*7ca9e471SAustin Kerbow for (auto &Op : MI->operands())
838*7ca9e471SAustin Kerbow if (Op.isReg() && Op.isDef())
839*7ca9e471SAustin Kerbow Op.setIsUndef(false);
840*7ca9e471SAustin Kerbow RegisterOperands RegOpers;
841*7ca9e471SAustin Kerbow RegOpers.collect(*MI, *DAG.TRI, DAG.MRI, DAG.ShouldTrackLaneMasks, false);
842*7ca9e471SAustin Kerbow if (!MI->isDebugInstr()) {
843*7ca9e471SAustin Kerbow if (DAG.ShouldTrackLaneMasks) {
844*7ca9e471SAustin Kerbow // Adjust liveness and add missing dead+read-undef flags.
845*7ca9e471SAustin Kerbow SlotIndex SlotIdx = DAG.LIS->getInstructionIndex(*MI).getRegSlot();
846*7ca9e471SAustin Kerbow RegOpers.adjustLaneLiveness(*DAG.LIS, DAG.MRI, SlotIdx, MI);
847*7ca9e471SAustin Kerbow } else {
848*7ca9e471SAustin Kerbow // Adjust for missing dead-def flags.
849*7ca9e471SAustin Kerbow RegOpers.detectDeadDefs(*MI, *DAG.LIS);
850*7ca9e471SAustin Kerbow }
851*7ca9e471SAustin Kerbow }
852*7ca9e471SAustin Kerbow DAG.RegionEnd = MI->getIterator();
853*7ca9e471SAustin Kerbow ++DAG.RegionEnd;
854*7ca9e471SAustin Kerbow LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
855*7ca9e471SAustin Kerbow }
856*7ca9e471SAustin Kerbow
857*7ca9e471SAustin Kerbow // After reverting schedule, debug instrs will now be at the end of the block
858*7ca9e471SAustin Kerbow // and RegionEnd will point to the first debug instr. Increment RegionEnd
859*7ca9e471SAustin Kerbow // pass debug instrs to the actual end of the scheduling region.
860*7ca9e471SAustin Kerbow while (SkippedDebugInstr-- > 0)
861*7ca9e471SAustin Kerbow ++DAG.RegionEnd;
862*7ca9e471SAustin Kerbow
863*7ca9e471SAustin Kerbow // If Unsched.front() instruction is a debug instruction, this will actually
864*7ca9e471SAustin Kerbow // shrink the region since we moved all debug instructions to the end of the
865*7ca9e471SAustin Kerbow // block. Find the first instruction that is not a debug instruction.
866*7ca9e471SAustin Kerbow DAG.RegionBegin = Unsched.front()->getIterator();
867*7ca9e471SAustin Kerbow if (DAG.RegionBegin->isDebugInstr()) {
868*7ca9e471SAustin Kerbow for (MachineInstr *MI : Unsched) {
869*7ca9e471SAustin Kerbow if (MI->isDebugInstr())
870*7ca9e471SAustin Kerbow continue;
871*7ca9e471SAustin Kerbow DAG.RegionBegin = MI->getIterator();
872*7ca9e471SAustin Kerbow break;
873*7ca9e471SAustin Kerbow }
874*7ca9e471SAustin Kerbow }
875*7ca9e471SAustin Kerbow
876*7ca9e471SAustin Kerbow // Then move the debug instructions back into their correct place and set
877*7ca9e471SAustin Kerbow // RegionBegin and RegionEnd if needed.
878*7ca9e471SAustin Kerbow DAG.placeDebugValues();
879*7ca9e471SAustin Kerbow
880*7ca9e471SAustin Kerbow DAG.Regions[RegionIdx] = std::make_pair(DAG.RegionBegin, DAG.RegionEnd);
881*7ca9e471SAustin Kerbow }
882*7ca9e471SAustin Kerbow
collectRematerializableInstructions()883*7ca9e471SAustin Kerbow void PreRARematStage::collectRematerializableInstructions() {
884*7ca9e471SAustin Kerbow const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo *>(DAG.TRI);
885*7ca9e471SAustin Kerbow for (unsigned I = 0, E = DAG.MRI.getNumVirtRegs(); I != E; ++I) {
88628322c25SVang Thao Register Reg = Register::index2VirtReg(I);
887*7ca9e471SAustin Kerbow if (!DAG.LIS->hasInterval(Reg))
88828322c25SVang Thao continue;
88928322c25SVang Thao
89028322c25SVang Thao // TODO: Handle AGPR and SGPR rematerialization
891*7ca9e471SAustin Kerbow if (!SRI->isVGPRClass(DAG.MRI.getRegClass(Reg)) ||
892*7ca9e471SAustin Kerbow !DAG.MRI.hasOneDef(Reg) || !DAG.MRI.hasOneNonDBGUse(Reg))
89328322c25SVang Thao continue;
89428322c25SVang Thao
895*7ca9e471SAustin Kerbow MachineOperand *Op = DAG.MRI.getOneDef(Reg);
896cd107117SVang Thao MachineInstr *Def = Op->getParent();
8978d0383ebSMatt Arsenault if (Op->getSubReg() != 0 || !isTriviallyReMaterializable(*Def))
89828322c25SVang Thao continue;
89928322c25SVang Thao
900*7ca9e471SAustin Kerbow MachineInstr *UseI = &*DAG.MRI.use_instr_nodbg_begin(Reg);
90128322c25SVang Thao if (Def->getParent() == UseI->getParent())
90228322c25SVang Thao continue;
90328322c25SVang Thao
904311edc6bSVang Thao // We are only collecting defs that are defined in another block and are
905311edc6bSVang Thao // live-through or used inside regions at MinOccupancy. This means that the
906311edc6bSVang Thao // register must be in the live-in set for the region.
907311edc6bSVang Thao bool AddedToRematList = false;
908*7ca9e471SAustin Kerbow for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
909*7ca9e471SAustin Kerbow auto It = DAG.LiveIns[I].find(Reg);
910*7ca9e471SAustin Kerbow if (It != DAG.LiveIns[I].end() && !It->second.none()) {
911*7ca9e471SAustin Kerbow if (DAG.RegionsWithMinOcc[I]) {
912311edc6bSVang Thao RematerializableInsts[I][Def] = UseI;
913311edc6bSVang Thao AddedToRematList = true;
914311edc6bSVang Thao }
915311edc6bSVang Thao
916311edc6bSVang Thao // Collect regions with rematerializable reg as live-in to avoid
917311edc6bSVang Thao // searching later when updating RP.
918311edc6bSVang Thao RematDefToLiveInRegions[Def].push_back(I);
919311edc6bSVang Thao }
920311edc6bSVang Thao }
921311edc6bSVang Thao if (!AddedToRematList)
922311edc6bSVang Thao RematDefToLiveInRegions.erase(Def);
92328322c25SVang Thao }
92428322c25SVang Thao }
92528322c25SVang Thao
sinkTriviallyRematInsts(const GCNSubtarget & ST,const TargetInstrInfo * TII)926*7ca9e471SAustin Kerbow bool PreRARematStage::sinkTriviallyRematInsts(const GCNSubtarget &ST,
927311edc6bSVang Thao const TargetInstrInfo *TII) {
928311edc6bSVang Thao // Temporary copies of cached variables we will be modifying and replacing if
929311edc6bSVang Thao // sinking succeeds.
930311edc6bSVang Thao SmallVector<
931311edc6bSVang Thao std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>, 32>
932311edc6bSVang Thao NewRegions;
933311edc6bSVang Thao DenseMap<unsigned, GCNRPTracker::LiveRegSet> NewLiveIns;
934311edc6bSVang Thao DenseMap<unsigned, GCNRegPressure> NewPressure;
935311edc6bSVang Thao BitVector NewRescheduleRegions;
936*7ca9e471SAustin Kerbow LiveIntervals *LIS = DAG.LIS;
93728322c25SVang Thao
938*7ca9e471SAustin Kerbow NewRegions.resize(DAG.Regions.size());
939*7ca9e471SAustin Kerbow NewRescheduleRegions.resize(DAG.Regions.size());
940311edc6bSVang Thao
941311edc6bSVang Thao // Collect only regions that has a rematerializable def as a live-in.
942311edc6bSVang Thao SmallSet<unsigned, 16> ImpactedRegions;
943311edc6bSVang Thao for (const auto &It : RematDefToLiveInRegions)
944311edc6bSVang Thao ImpactedRegions.insert(It.second.begin(), It.second.end());
945311edc6bSVang Thao
946311edc6bSVang Thao // Make copies of register pressure and live-ins cache that will be updated
947311edc6bSVang Thao // as we rematerialize.
948311edc6bSVang Thao for (auto Idx : ImpactedRegions) {
949*7ca9e471SAustin Kerbow NewPressure[Idx] = DAG.Pressure[Idx];
950*7ca9e471SAustin Kerbow NewLiveIns[Idx] = DAG.LiveIns[Idx];
951311edc6bSVang Thao }
952*7ca9e471SAustin Kerbow NewRegions = DAG.Regions;
953311edc6bSVang Thao NewRescheduleRegions.reset();
954311edc6bSVang Thao
955311edc6bSVang Thao DenseMap<MachineInstr *, MachineInstr *> InsertedMIToOldDef;
956311edc6bSVang Thao bool Improved = false;
957311edc6bSVang Thao for (auto I : ImpactedRegions) {
958*7ca9e471SAustin Kerbow if (!DAG.RegionsWithMinOcc[I])
959311edc6bSVang Thao continue;
960311edc6bSVang Thao
961311edc6bSVang Thao Improved = false;
962311edc6bSVang Thao int VGPRUsage = NewPressure[I].getVGPRNum(ST.hasGFX90AInsts());
963311edc6bSVang Thao int SGPRUsage = NewPressure[I].getSGPRNum();
96428322c25SVang Thao
96528322c25SVang Thao // TODO: Handle occupancy drop due to AGPR and SGPR.
966311edc6bSVang Thao // Check if cause of occupancy drop is due to VGPR usage and not SGPR.
967*7ca9e471SAustin Kerbow if (ST.getOccupancyWithNumSGPRs(SGPRUsage) == DAG.MinOccupancy)
968311edc6bSVang Thao break;
96928322c25SVang Thao
970311edc6bSVang Thao // The occupancy of this region could have been improved by a previous
971311edc6bSVang Thao // iteration's sinking of defs.
972*7ca9e471SAustin Kerbow if (NewPressure[I].getOccupancy(ST) > DAG.MinOccupancy) {
973311edc6bSVang Thao NewRescheduleRegions[I] = true;
974311edc6bSVang Thao Improved = true;
975311edc6bSVang Thao continue;
976311edc6bSVang Thao }
977311edc6bSVang Thao
97828322c25SVang Thao // First check if we have enough trivially rematerializable instructions to
97928322c25SVang Thao // improve occupancy. Optimistically assume all instructions we are able to
98028322c25SVang Thao // sink decreased RP.
98128322c25SVang Thao int TotalSinkableRegs = 0;
982311edc6bSVang Thao for (const auto &It : RematerializableInsts[I]) {
983311edc6bSVang Thao MachineInstr *Def = It.first;
984311edc6bSVang Thao Register DefReg = Def->getOperand(0).getReg();
985311edc6bSVang Thao TotalSinkableRegs +=
986311edc6bSVang Thao SIRegisterInfo::getNumCoveredRegs(NewLiveIns[I][DefReg]);
98728322c25SVang Thao }
98828322c25SVang Thao int VGPRsAfterSink = VGPRUsage - TotalSinkableRegs;
98928322c25SVang Thao unsigned OptimisticOccupancy = ST.getOccupancyWithNumVGPRs(VGPRsAfterSink);
99028322c25SVang Thao // If in the most optimistic scenario, we cannot improve occupancy, then do
99128322c25SVang Thao // not attempt to sink any instructions.
992*7ca9e471SAustin Kerbow if (OptimisticOccupancy <= DAG.MinOccupancy)
993311edc6bSVang Thao break;
99428322c25SVang Thao
99528322c25SVang Thao unsigned ImproveOccupancy = 0;
996311edc6bSVang Thao SmallVector<MachineInstr *, 4> SinkedDefs;
997311edc6bSVang Thao for (auto &It : RematerializableInsts[I]) {
99828322c25SVang Thao MachineInstr *Def = It.first;
99928322c25SVang Thao MachineBasicBlock::iterator InsertPos =
100028322c25SVang Thao MachineBasicBlock::iterator(It.second);
100128322c25SVang Thao Register Reg = Def->getOperand(0).getReg();
100228322c25SVang Thao // Rematerialize MI to its use block. Since we are only rematerializing
100328322c25SVang Thao // instructions that do not have any virtual reg uses, we do not need to
100428322c25SVang Thao // call LiveRangeEdit::allUsesAvailableAt() and
100528322c25SVang Thao // LiveRangeEdit::canRematerializeAt().
100628322c25SVang Thao TII->reMaterialize(*InsertPos->getParent(), InsertPos, Reg,
1007*7ca9e471SAustin Kerbow Def->getOperand(0).getSubReg(), *Def, *DAG.TRI);
100828322c25SVang Thao MachineInstr *NewMI = &*(--InsertPos);
100928322c25SVang Thao LIS->InsertMachineInstrInMaps(*NewMI);
101028322c25SVang Thao LIS->removeInterval(Reg);
101128322c25SVang Thao LIS->createAndComputeVirtRegInterval(Reg);
101228322c25SVang Thao InsertedMIToOldDef[NewMI] = Def;
101328322c25SVang Thao
1014311edc6bSVang Thao // Update region boundaries in scheduling region we sinked from since we
1015311edc6bSVang Thao // may sink an instruction that was at the beginning or end of its region
1016*7ca9e471SAustin Kerbow DAG.updateRegionBoundaries(NewRegions, Def, /*NewMI =*/nullptr,
1017311edc6bSVang Thao /*Removing =*/true);
1018311edc6bSVang Thao
1019311edc6bSVang Thao // Update region boundaries in region we sinked to.
1020*7ca9e471SAustin Kerbow DAG.updateRegionBoundaries(NewRegions, InsertPos, NewMI);
1021311edc6bSVang Thao
1022311edc6bSVang Thao LaneBitmask PrevMask = NewLiveIns[I][Reg];
1023311edc6bSVang Thao // FIXME: Also update cached pressure for where the def was sinked from.
1024311edc6bSVang Thao // Update RP for all regions that has this reg as a live-in and remove
1025311edc6bSVang Thao // the reg from all regions as a live-in.
1026311edc6bSVang Thao for (auto Idx : RematDefToLiveInRegions[Def]) {
1027311edc6bSVang Thao NewLiveIns[Idx].erase(Reg);
1028*7ca9e471SAustin Kerbow if (InsertPos->getParent() != DAG.Regions[Idx].first->getParent()) {
1029311edc6bSVang Thao // Def is live-through and not used in this block.
1030*7ca9e471SAustin Kerbow NewPressure[Idx].inc(Reg, PrevMask, LaneBitmask::getNone(), DAG.MRI);
1031311edc6bSVang Thao } else {
1032311edc6bSVang Thao // Def is used and rematerialized into this block.
1033311edc6bSVang Thao GCNDownwardRPTracker RPT(*LIS);
1034311edc6bSVang Thao auto *NonDbgMI = &*skipDebugInstructionsForward(
1035311edc6bSVang Thao NewRegions[Idx].first, NewRegions[Idx].second);
1036311edc6bSVang Thao RPT.reset(*NonDbgMI, &NewLiveIns[Idx]);
1037311edc6bSVang Thao RPT.advance(NewRegions[Idx].second);
1038311edc6bSVang Thao NewPressure[Idx] = RPT.moveMaxPressure();
1039311edc6bSVang Thao }
1040311edc6bSVang Thao }
1041311edc6bSVang Thao
1042311edc6bSVang Thao SinkedDefs.push_back(Def);
1043311edc6bSVang Thao ImproveOccupancy = NewPressure[I].getOccupancy(ST);
1044*7ca9e471SAustin Kerbow if (ImproveOccupancy > DAG.MinOccupancy)
104528322c25SVang Thao break;
104628322c25SVang Thao }
104728322c25SVang Thao
1048311edc6bSVang Thao // Remove defs we just sinked from all regions' list of sinkable defs
1049311edc6bSVang Thao for (auto &Def : SinkedDefs)
1050311edc6bSVang Thao for (auto TrackedIdx : RematDefToLiveInRegions[Def])
1051311edc6bSVang Thao RematerializableInsts[TrackedIdx].erase(Def);
1052311edc6bSVang Thao
1053*7ca9e471SAustin Kerbow if (ImproveOccupancy <= DAG.MinOccupancy)
1054311edc6bSVang Thao break;
1055311edc6bSVang Thao
1056311edc6bSVang Thao NewRescheduleRegions[I] = true;
1057311edc6bSVang Thao Improved = true;
1058311edc6bSVang Thao }
1059311edc6bSVang Thao
1060311edc6bSVang Thao if (!Improved) {
1061311edc6bSVang Thao // Occupancy was not improved for all regions that were at MinOccupancy.
1062311edc6bSVang Thao // Undo sinking and remove newly rematerialized instructions.
106328322c25SVang Thao for (auto &Entry : InsertedMIToOldDef) {
106428322c25SVang Thao MachineInstr *MI = Entry.first;
106528322c25SVang Thao MachineInstr *OldMI = Entry.second;
106628322c25SVang Thao Register Reg = MI->getOperand(0).getReg();
106728322c25SVang Thao LIS->RemoveMachineInstrFromMaps(*MI);
106828322c25SVang Thao MI->eraseFromParent();
106928322c25SVang Thao OldMI->clearRegisterDeads(Reg);
107028322c25SVang Thao LIS->removeInterval(Reg);
107128322c25SVang Thao LIS->createAndComputeVirtRegInterval(Reg);
107228322c25SVang Thao }
107328322c25SVang Thao return false;
107428322c25SVang Thao }
107528322c25SVang Thao
1076311edc6bSVang Thao // Occupancy was improved for all regions.
107728322c25SVang Thao for (auto &Entry : InsertedMIToOldDef) {
107828322c25SVang Thao MachineInstr *MI = Entry.first;
107928322c25SVang Thao MachineInstr *OldMI = Entry.second;
108028322c25SVang Thao
108128322c25SVang Thao // Remove OldMI from BBLiveInMap since we are sinking it from its MBB.
1082*7ca9e471SAustin Kerbow DAG.BBLiveInMap.erase(OldMI);
108328322c25SVang Thao
108428322c25SVang Thao // Remove OldMI and update LIS
108528322c25SVang Thao Register Reg = MI->getOperand(0).getReg();
108628322c25SVang Thao LIS->RemoveMachineInstrFromMaps(*OldMI);
108728322c25SVang Thao OldMI->eraseFromParent();
108828322c25SVang Thao LIS->removeInterval(Reg);
108928322c25SVang Thao LIS->createAndComputeVirtRegInterval(Reg);
109028322c25SVang Thao }
109128322c25SVang Thao
1092311edc6bSVang Thao // Update live-ins, register pressure, and regions caches.
1093311edc6bSVang Thao for (auto Idx : ImpactedRegions) {
1094*7ca9e471SAustin Kerbow DAG.LiveIns[Idx] = NewLiveIns[Idx];
1095*7ca9e471SAustin Kerbow DAG.Pressure[Idx] = NewPressure[Idx];
1096*7ca9e471SAustin Kerbow DAG.MBBLiveIns.erase(DAG.Regions[Idx].first->getParent());
1097311edc6bSVang Thao }
1098*7ca9e471SAustin Kerbow DAG.Regions = NewRegions;
1099*7ca9e471SAustin Kerbow DAG.RescheduleRegions = NewRescheduleRegions;
110028322c25SVang Thao
110128322c25SVang Thao SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
1102*7ca9e471SAustin Kerbow MFI.increaseOccupancy(MF, ++DAG.MinOccupancy);
110328322c25SVang Thao
110428322c25SVang Thao return true;
110528322c25SVang Thao }
110628322c25SVang Thao
110728322c25SVang Thao // Copied from MachineLICM
isTriviallyReMaterializable(const MachineInstr & MI)1108*7ca9e471SAustin Kerbow bool PreRARematStage::isTriviallyReMaterializable(const MachineInstr &MI) {
1109*7ca9e471SAustin Kerbow if (!DAG.TII->isTriviallyReMaterializable(MI))
111028322c25SVang Thao return false;
111128322c25SVang Thao
111228322c25SVang Thao for (const MachineOperand &MO : MI.operands())
111328322c25SVang Thao if (MO.isReg() && MO.isUse() && MO.getReg().isVirtual())
111428322c25SVang Thao return false;
111528322c25SVang Thao
111628322c25SVang Thao return true;
111728322c25SVang Thao }
111828322c25SVang Thao
111928322c25SVang Thao // When removing, we will have to check both beginning and ending of the region.
112028322c25SVang Thao // When inserting, we will only have to check if we are inserting NewMI in front
112128322c25SVang Thao // of a scheduling region and do not need to check the ending since we will only
112228322c25SVang Thao // ever be inserting before an already existing MI.
updateRegionBoundaries(SmallVectorImpl<std::pair<MachineBasicBlock::iterator,MachineBasicBlock::iterator>> & RegionBoundaries,MachineBasicBlock::iterator MI,MachineInstr * NewMI,bool Removing)112328322c25SVang Thao void GCNScheduleDAGMILive::updateRegionBoundaries(
1124311edc6bSVang Thao SmallVectorImpl<std::pair<MachineBasicBlock::iterator,
1125311edc6bSVang Thao MachineBasicBlock::iterator>> &RegionBoundaries,
112628322c25SVang Thao MachineBasicBlock::iterator MI, MachineInstr *NewMI, bool Removing) {
1127311edc6bSVang Thao unsigned I = 0, E = RegionBoundaries.size();
112828322c25SVang Thao // Search for first region of the block where MI is located
1129311edc6bSVang Thao while (I != E && MI->getParent() != RegionBoundaries[I].first->getParent())
113028322c25SVang Thao ++I;
113128322c25SVang Thao
113228322c25SVang Thao for (; I != E; ++I) {
1133311edc6bSVang Thao if (MI->getParent() != RegionBoundaries[I].first->getParent())
113428322c25SVang Thao return;
113528322c25SVang Thao
1136311edc6bSVang Thao if (Removing && MI == RegionBoundaries[I].first &&
1137311edc6bSVang Thao MI == RegionBoundaries[I].second) {
113828322c25SVang Thao // MI is in a region with size 1, after removing, the region will be
113928322c25SVang Thao // size 0, set RegionBegin and RegionEnd to pass end of block iterator.
1140311edc6bSVang Thao RegionBoundaries[I] =
114128322c25SVang Thao std::make_pair(MI->getParent()->end(), MI->getParent()->end());
114228322c25SVang Thao return;
114328322c25SVang Thao }
1144311edc6bSVang Thao if (MI == RegionBoundaries[I].first) {
114528322c25SVang Thao if (Removing)
1146311edc6bSVang Thao RegionBoundaries[I] =
1147311edc6bSVang Thao std::make_pair(std::next(MI), RegionBoundaries[I].second);
114828322c25SVang Thao else
114928322c25SVang Thao // Inserted NewMI in front of region, set new RegionBegin to NewMI
1150311edc6bSVang Thao RegionBoundaries[I] = std::make_pair(MachineBasicBlock::iterator(NewMI),
1151311edc6bSVang Thao RegionBoundaries[I].second);
115228322c25SVang Thao return;
115328322c25SVang Thao }
1154311edc6bSVang Thao if (Removing && MI == RegionBoundaries[I].second) {
1155311edc6bSVang Thao RegionBoundaries[I] =
1156311edc6bSVang Thao std::make_pair(RegionBoundaries[I].first, std::prev(MI));
115728322c25SVang Thao return;
115828322c25SVang Thao }
115928322c25SVang Thao }
116028322c25SVang Thao }
1161