1 //===-- GCNSchedStrategy.cpp - GCN Scheduler Strategy ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This contains a MachineSchedStrategy implementation for maximizing wave
11 /// occupancy on GCN hardware.
12 //===----------------------------------------------------------------------===//
13 
14 #include "GCNSchedStrategy.h"
15 #include "AMDGPUSubtarget.h"
16 #include "SIMachineFunctionInfo.h"
17 
18 #define DEBUG_TYPE "machine-scheduler"
19 
20 using namespace llvm;
21 
22 GCNMaxOccupancySchedStrategy::GCNMaxOccupancySchedStrategy(
23     const MachineSchedContext *C) :
24     GenericScheduler(C), TargetOccupancy(0), MF(nullptr) { }
25 
26 void GCNMaxOccupancySchedStrategy::initialize(ScheduleDAGMI *DAG) {
27   GenericScheduler::initialize(DAG);
28 
29   const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo*>(TRI);
30 
31   MF = &DAG->MF;
32 
33   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
34 
35   // FIXME: This is also necessary, because some passes that run after
36   // scheduling and before regalloc increase register pressure.
37   const int ErrorMargin = 3;
38 
39   SGPRExcessLimit = Context->RegClassInfo
40     ->getNumAllocatableRegs(&AMDGPU::SGPR_32RegClass) - ErrorMargin;
41   VGPRExcessLimit = Context->RegClassInfo
42     ->getNumAllocatableRegs(&AMDGPU::VGPR_32RegClass) - ErrorMargin;
43   if (TargetOccupancy) {
44     SGPRCriticalLimit = ST.getMaxNumSGPRs(TargetOccupancy, true);
45     VGPRCriticalLimit = ST.getMaxNumVGPRs(TargetOccupancy);
46   } else {
47     SGPRCriticalLimit = SRI->getRegPressureSetLimit(DAG->MF,
48         AMDGPU::RegisterPressureSets::SReg_32);
49     VGPRCriticalLimit = SRI->getRegPressureSetLimit(DAG->MF,
50         AMDGPU::RegisterPressureSets::VGPR_32);
51   }
52 
53   SGPRCriticalLimit -= ErrorMargin;
54   VGPRCriticalLimit -= ErrorMargin;
55 }
56 
57 void GCNMaxOccupancySchedStrategy::initCandidate(SchedCandidate &Cand, SUnit *SU,
58                                      bool AtTop, const RegPressureTracker &RPTracker,
59                                      const SIRegisterInfo *SRI,
60                                      unsigned SGPRPressure,
61                                      unsigned VGPRPressure) {
62 
63   Cand.SU = SU;
64   Cand.AtTop = AtTop;
65 
66   // getDownwardPressure() and getUpwardPressure() make temporary changes to
67   // the tracker, so we need to pass those function a non-const copy.
68   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
69 
70   Pressure.clear();
71   MaxPressure.clear();
72 
73   if (AtTop)
74     TempTracker.getDownwardPressure(SU->getInstr(), Pressure, MaxPressure);
75   else {
76     // FIXME: I think for bottom up scheduling, the register pressure is cached
77     // and can be retrieved by DAG->getPressureDif(SU).
78     TempTracker.getUpwardPressure(SU->getInstr(), Pressure, MaxPressure);
79   }
80 
81   unsigned NewSGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
82   unsigned NewVGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
83 
84   // If two instructions increase the pressure of different register sets
85   // by the same amount, the generic scheduler will prefer to schedule the
86   // instruction that increases the set with the least amount of registers,
87   // which in our case would be SGPRs.  This is rarely what we want, so
88   // when we report excess/critical register pressure, we do it either
89   // only for VGPRs or only for SGPRs.
90 
91   // FIXME: Better heuristics to determine whether to prefer SGPRs or VGPRs.
92   const unsigned MaxVGPRPressureInc = 16;
93   bool ShouldTrackVGPRs = VGPRPressure + MaxVGPRPressureInc >= VGPRExcessLimit;
94   bool ShouldTrackSGPRs = !ShouldTrackVGPRs && SGPRPressure >= SGPRExcessLimit;
95 
96 
97   // FIXME: We have to enter REG-EXCESS before we reach the actual threshold
98   // to increase the likelihood we don't go over the limits.  We should improve
99   // the analysis to look through dependencies to find the path with the least
100   // register pressure.
101 
102   // We only need to update the RPDelta for instructions that increase register
103   // pressure. Instructions that decrease or keep reg pressure the same will be
104   // marked as RegExcess in tryCandidate() when they are compared with
105   // instructions that increase the register pressure.
106   if (ShouldTrackVGPRs && NewVGPRPressure >= VGPRExcessLimit) {
107     Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
108     Cand.RPDelta.Excess.setUnitInc(NewVGPRPressure - VGPRExcessLimit);
109   }
110 
111   if (ShouldTrackSGPRs && NewSGPRPressure >= SGPRExcessLimit) {
112     Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
113     Cand.RPDelta.Excess.setUnitInc(NewSGPRPressure - SGPRExcessLimit);
114   }
115 
116   // Register pressure is considered 'CRITICAL' if it is approaching a value
117   // that would reduce the wave occupancy for the execution unit.  When
118   // register pressure is 'CRITICAL', increading SGPR and VGPR pressure both
119   // has the same cost, so we don't need to prefer one over the other.
120 
121   int SGPRDelta = NewSGPRPressure - SGPRCriticalLimit;
122   int VGPRDelta = NewVGPRPressure - VGPRCriticalLimit;
123 
124   if (SGPRDelta >= 0 || VGPRDelta >= 0) {
125     if (SGPRDelta > VGPRDelta) {
126       Cand.RPDelta.CriticalMax =
127         PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
128       Cand.RPDelta.CriticalMax.setUnitInc(SGPRDelta);
129     } else {
130       Cand.RPDelta.CriticalMax =
131         PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
132       Cand.RPDelta.CriticalMax.setUnitInc(VGPRDelta);
133     }
134   }
135 }
136 
137 // This function is mostly cut and pasted from
138 // GenericScheduler::pickNodeFromQueue()
139 void GCNMaxOccupancySchedStrategy::pickNodeFromQueue(SchedBoundary &Zone,
140                                          const CandPolicy &ZonePolicy,
141                                          const RegPressureTracker &RPTracker,
142                                          SchedCandidate &Cand) {
143   const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo*>(TRI);
144   ArrayRef<unsigned> Pressure = RPTracker.getRegSetPressureAtPos();
145   unsigned SGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
146   unsigned VGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
147   ReadyQueue &Q = Zone.Available;
148   for (SUnit *SU : Q) {
149 
150     SchedCandidate TryCand(ZonePolicy);
151     initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI,
152                   SGPRPressure, VGPRPressure);
153     // Pass SchedBoundary only when comparing nodes from the same boundary.
154     SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
155     GenericScheduler::tryCandidate(Cand, TryCand, ZoneArg);
156     if (TryCand.Reason != NoCand) {
157       // Initialize resource delta if needed in case future heuristics query it.
158       if (TryCand.ResDelta == SchedResourceDelta())
159         TryCand.initResourceDelta(Zone.DAG, SchedModel);
160       Cand.setBest(TryCand);
161       LLVM_DEBUG(traceCandidate(Cand));
162     }
163   }
164 }
165 
166 // This function is mostly cut and pasted from
167 // GenericScheduler::pickNodeBidirectional()
168 SUnit *GCNMaxOccupancySchedStrategy::pickNodeBidirectional(bool &IsTopNode) {
169   // Schedule as far as possible in the direction of no choice. This is most
170   // efficient, but also provides the best heuristics for CriticalPSets.
171   if (SUnit *SU = Bot.pickOnlyChoice()) {
172     IsTopNode = false;
173     return SU;
174   }
175   if (SUnit *SU = Top.pickOnlyChoice()) {
176     IsTopNode = true;
177     return SU;
178   }
179   // Set the bottom-up policy based on the state of the current bottom zone and
180   // the instructions outside the zone, including the top zone.
181   CandPolicy BotPolicy;
182   setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
183   // Set the top-down policy based on the state of the current top zone and
184   // the instructions outside the zone, including the bottom zone.
185   CandPolicy TopPolicy;
186   setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
187 
188   // See if BotCand is still valid (because we previously scheduled from Top).
189   LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
190   if (!BotCand.isValid() || BotCand.SU->isScheduled ||
191       BotCand.Policy != BotPolicy) {
192     BotCand.reset(CandPolicy());
193     pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
194     assert(BotCand.Reason != NoCand && "failed to find the first candidate");
195   } else {
196     LLVM_DEBUG(traceCandidate(BotCand));
197 #ifndef NDEBUG
198     if (VerifyScheduling) {
199       SchedCandidate TCand;
200       TCand.reset(CandPolicy());
201       pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
202       assert(TCand.SU == BotCand.SU &&
203              "Last pick result should correspond to re-picking right now");
204     }
205 #endif
206   }
207 
208   // Check if the top Q has a better candidate.
209   LLVM_DEBUG(dbgs() << "Picking from Top:\n");
210   if (!TopCand.isValid() || TopCand.SU->isScheduled ||
211       TopCand.Policy != TopPolicy) {
212     TopCand.reset(CandPolicy());
213     pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
214     assert(TopCand.Reason != NoCand && "failed to find the first candidate");
215   } else {
216     LLVM_DEBUG(traceCandidate(TopCand));
217 #ifndef NDEBUG
218     if (VerifyScheduling) {
219       SchedCandidate TCand;
220       TCand.reset(CandPolicy());
221       pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
222       assert(TCand.SU == TopCand.SU &&
223            "Last pick result should correspond to re-picking right now");
224     }
225 #endif
226   }
227 
228   // Pick best from BotCand and TopCand.
229   LLVM_DEBUG(dbgs() << "Top Cand: "; traceCandidate(TopCand);
230              dbgs() << "Bot Cand: "; traceCandidate(BotCand););
231   SchedCandidate Cand = BotCand;
232   TopCand.Reason = NoCand;
233   GenericScheduler::tryCandidate(Cand, TopCand, nullptr);
234   if (TopCand.Reason != NoCand) {
235     Cand.setBest(TopCand);
236   }
237   LLVM_DEBUG(dbgs() << "Picking: "; traceCandidate(Cand););
238 
239   IsTopNode = Cand.AtTop;
240   return Cand.SU;
241 }
242 
243 // This function is mostly cut and pasted from
244 // GenericScheduler::pickNode()
245 SUnit *GCNMaxOccupancySchedStrategy::pickNode(bool &IsTopNode) {
246   if (DAG->top() == DAG->bottom()) {
247     assert(Top.Available.empty() && Top.Pending.empty() &&
248            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
249     return nullptr;
250   }
251   SUnit *SU;
252   do {
253     if (RegionPolicy.OnlyTopDown) {
254       SU = Top.pickOnlyChoice();
255       if (!SU) {
256         CandPolicy NoPolicy;
257         TopCand.reset(NoPolicy);
258         pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
259         assert(TopCand.Reason != NoCand && "failed to find a candidate");
260         SU = TopCand.SU;
261       }
262       IsTopNode = true;
263     } else if (RegionPolicy.OnlyBottomUp) {
264       SU = Bot.pickOnlyChoice();
265       if (!SU) {
266         CandPolicy NoPolicy;
267         BotCand.reset(NoPolicy);
268         pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
269         assert(BotCand.Reason != NoCand && "failed to find a candidate");
270         SU = BotCand.SU;
271       }
272       IsTopNode = false;
273     } else {
274       SU = pickNodeBidirectional(IsTopNode);
275     }
276   } while (SU->isScheduled);
277 
278   if (SU->isTopReady())
279     Top.removeReady(SU);
280   if (SU->isBottomReady())
281     Bot.removeReady(SU);
282 
283   LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
284                     << *SU->getInstr());
285   return SU;
286 }
287 
288 GCNScheduleDAGMILive::GCNScheduleDAGMILive(MachineSchedContext *C,
289                         std::unique_ptr<MachineSchedStrategy> S) :
290   ScheduleDAGMILive(C, std::move(S)),
291   ST(MF.getSubtarget<GCNSubtarget>()),
292   MFI(*MF.getInfo<SIMachineFunctionInfo>()),
293   StartingOccupancy(MFI.getOccupancy()),
294   MinOccupancy(StartingOccupancy), Stage(Collect), RegionIdx(0) {
295 
296   LLVM_DEBUG(dbgs() << "Starting occupancy is " << StartingOccupancy << ".\n");
297 }
298 
299 void GCNScheduleDAGMILive::schedule() {
300   if (Stage == Collect) {
301     // Just record regions at the first pass.
302     Regions.push_back(std::make_pair(RegionBegin, RegionEnd));
303     return;
304   }
305 
306   std::vector<MachineInstr*> Unsched;
307   Unsched.reserve(NumRegionInstrs);
308   for (auto &I : *this) {
309     Unsched.push_back(&I);
310   }
311 
312   GCNRegPressure PressureBefore;
313   if (LIS) {
314     PressureBefore = Pressure[RegionIdx];
315 
316     LLVM_DEBUG(dbgs() << "Pressure before scheduling:\nRegion live-ins:";
317                GCNRPTracker::printLiveRegs(dbgs(), LiveIns[RegionIdx], MRI);
318                dbgs() << "Region live-in pressure:  ";
319                llvm::getRegPressure(MRI, LiveIns[RegionIdx]).print(dbgs());
320                dbgs() << "Region register pressure: ";
321                PressureBefore.print(dbgs()));
322   }
323 
324   ScheduleDAGMILive::schedule();
325   Regions[RegionIdx] = std::make_pair(RegionBegin, RegionEnd);
326   RescheduleRegions[RegionIdx] = false;
327 
328   if (!LIS)
329     return;
330 
331   // Check the results of scheduling.
332   GCNMaxOccupancySchedStrategy &S = (GCNMaxOccupancySchedStrategy&)*SchedImpl;
333   auto PressureAfter = getRealRegPressure();
334 
335   LLVM_DEBUG(dbgs() << "Pressure after scheduling: ";
336              PressureAfter.print(dbgs()));
337 
338   if (PressureAfter.getSGPRNum() <= S.SGPRCriticalLimit &&
339       PressureAfter.getVGPRNum() <= S.VGPRCriticalLimit) {
340     Pressure[RegionIdx] = PressureAfter;
341     LLVM_DEBUG(dbgs() << "Pressure in desired limits, done.\n");
342     return;
343   }
344   unsigned Occ = MFI.getOccupancy();
345   unsigned WavesAfter = std::min(Occ, PressureAfter.getOccupancy(ST));
346   unsigned WavesBefore = std::min(Occ, PressureBefore.getOccupancy(ST));
347   LLVM_DEBUG(dbgs() << "Occupancy before scheduling: " << WavesBefore
348                     << ", after " << WavesAfter << ".\n");
349 
350   // We could not keep current target occupancy because of the just scheduled
351   // region. Record new occupancy for next scheduling cycle.
352   unsigned NewOccupancy = std::max(WavesAfter, WavesBefore);
353   // Allow memory bound functions to drop to 4 waves if not limited by an
354   // attribute.
355   if (WavesAfter < WavesBefore && WavesAfter < MinOccupancy &&
356       WavesAfter >= MFI.getMinAllowedOccupancy()) {
357     LLVM_DEBUG(dbgs() << "Function is memory bound, allow occupancy drop up to "
358                       << MFI.getMinAllowedOccupancy() << " waves\n");
359     NewOccupancy = WavesAfter;
360   }
361   if (NewOccupancy < MinOccupancy) {
362     MinOccupancy = NewOccupancy;
363     MFI.limitOccupancy(MinOccupancy);
364     LLVM_DEBUG(dbgs() << "Occupancy lowered for the function to "
365                       << MinOccupancy << ".\n");
366   }
367 
368   unsigned MaxVGPRs = ST.getMaxNumVGPRs(MF);
369   unsigned MaxSGPRs = ST.getMaxNumSGPRs(MF);
370   if (PressureAfter.getVGPRNum() > MaxVGPRs ||
371       PressureAfter.getSGPRNum() > MaxSGPRs)
372     RescheduleRegions[RegionIdx] = true;
373 
374   if (WavesAfter >= MinOccupancy) {
375     if (Stage == UnclusteredReschedule &&
376         !PressureAfter.less(ST, PressureBefore)) {
377       LLVM_DEBUG(dbgs() << "Unclustered reschedule did not help.\n");
378     } else if (WavesAfter > MFI.getMinWavesPerEU() ||
379         PressureAfter.less(ST, PressureBefore) ||
380         !RescheduleRegions[RegionIdx]) {
381       Pressure[RegionIdx] = PressureAfter;
382       return;
383     } else {
384       LLVM_DEBUG(dbgs() << "New pressure will result in more spilling.\n");
385     }
386   }
387 
388   LLVM_DEBUG(dbgs() << "Attempting to revert scheduling.\n");
389   RescheduleRegions[RegionIdx] = true;
390   RegionEnd = RegionBegin;
391   for (MachineInstr *MI : Unsched) {
392     if (MI->isDebugInstr())
393       continue;
394 
395     if (MI->getIterator() != RegionEnd) {
396       BB->remove(MI);
397       BB->insert(RegionEnd, MI);
398       if (!MI->isDebugInstr())
399         LIS->handleMove(*MI, true);
400     }
401     // Reset read-undef flags and update them later.
402     for (auto &Op : MI->operands())
403       if (Op.isReg() && Op.isDef())
404         Op.setIsUndef(false);
405     RegisterOperands RegOpers;
406     RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
407     if (!MI->isDebugInstr()) {
408       if (ShouldTrackLaneMasks) {
409         // Adjust liveness and add missing dead+read-undef flags.
410         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
411         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
412       } else {
413         // Adjust for missing dead-def flags.
414         RegOpers.detectDeadDefs(*MI, *LIS);
415       }
416     }
417     RegionEnd = MI->getIterator();
418     ++RegionEnd;
419     LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
420   }
421   RegionBegin = Unsched.front()->getIterator();
422   Regions[RegionIdx] = std::make_pair(RegionBegin, RegionEnd);
423 
424   placeDebugValues();
425 }
426 
427 GCNRegPressure GCNScheduleDAGMILive::getRealRegPressure() const {
428   GCNDownwardRPTracker RPTracker(*LIS);
429   RPTracker.advance(begin(), end(), &LiveIns[RegionIdx]);
430   return RPTracker.moveMaxPressure();
431 }
432 
433 void GCNScheduleDAGMILive::computeBlockPressure(const MachineBasicBlock *MBB) {
434   GCNDownwardRPTracker RPTracker(*LIS);
435 
436   // If the block has the only successor then live-ins of that successor are
437   // live-outs of the current block. We can reuse calculated live set if the
438   // successor will be sent to scheduling past current block.
439   const MachineBasicBlock *OnlySucc = nullptr;
440   if (MBB->succ_size() == 1 && !(*MBB->succ_begin())->empty()) {
441     SlotIndexes *Ind = LIS->getSlotIndexes();
442     if (Ind->getMBBStartIdx(MBB) < Ind->getMBBStartIdx(*MBB->succ_begin()))
443       OnlySucc = *MBB->succ_begin();
444   }
445 
446   // Scheduler sends regions from the end of the block upwards.
447   size_t CurRegion = RegionIdx;
448   for (size_t E = Regions.size(); CurRegion != E; ++CurRegion)
449     if (Regions[CurRegion].first->getParent() != MBB)
450       break;
451   --CurRegion;
452 
453   auto I = MBB->begin();
454   auto LiveInIt = MBBLiveIns.find(MBB);
455   if (LiveInIt != MBBLiveIns.end()) {
456     auto LiveIn = std::move(LiveInIt->second);
457     RPTracker.reset(*MBB->begin(), &LiveIn);
458     MBBLiveIns.erase(LiveInIt);
459   } else {
460     auto &Rgn = Regions[CurRegion];
461     I = Rgn.first;
462     auto *NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
463     auto LRS = BBLiveInMap.lookup(NonDbgMI);
464     assert(isEqual(getLiveRegsBefore(*NonDbgMI, *LIS), LRS));
465     RPTracker.reset(*I, &LRS);
466   }
467 
468   for ( ; ; ) {
469     I = RPTracker.getNext();
470 
471     if (Regions[CurRegion].first == I) {
472       LiveIns[CurRegion] = RPTracker.getLiveRegs();
473       RPTracker.clearMaxPressure();
474     }
475 
476     if (Regions[CurRegion].second == I) {
477       Pressure[CurRegion] = RPTracker.moveMaxPressure();
478       if (CurRegion-- == RegionIdx)
479         break;
480     }
481     RPTracker.advanceToNext();
482     RPTracker.advanceBeforeNext();
483   }
484 
485   if (OnlySucc) {
486     if (I != MBB->end()) {
487       RPTracker.advanceToNext();
488       RPTracker.advance(MBB->end());
489     }
490     RPTracker.reset(*OnlySucc->begin(), &RPTracker.getLiveRegs());
491     RPTracker.advanceBeforeNext();
492     MBBLiveIns[OnlySucc] = RPTracker.moveLiveRegs();
493   }
494 }
495 
496 DenseMap<MachineInstr *, GCNRPTracker::LiveRegSet>
497 GCNScheduleDAGMILive::getBBLiveInMap() const {
498   assert(!Regions.empty());
499   std::vector<MachineInstr *> BBStarters;
500   BBStarters.reserve(Regions.size());
501   auto I = Regions.rbegin(), E = Regions.rend();
502   auto *BB = I->first->getParent();
503   do {
504     auto *MI = &*skipDebugInstructionsForward(I->first, I->second);
505     BBStarters.push_back(MI);
506     do {
507       ++I;
508     } while (I != E && I->first->getParent() == BB);
509   } while (I != E);
510   return getLiveRegMap(BBStarters, false /*After*/, *LIS);
511 }
512 
513 void GCNScheduleDAGMILive::finalizeSchedule() {
514   GCNMaxOccupancySchedStrategy &S = (GCNMaxOccupancySchedStrategy&)*SchedImpl;
515   LLVM_DEBUG(dbgs() << "All regions recorded, starting actual scheduling.\n");
516 
517   LiveIns.resize(Regions.size());
518   Pressure.resize(Regions.size());
519   RescheduleRegions.resize(Regions.size());
520   RescheduleRegions.set();
521 
522   if (!Regions.empty())
523     BBLiveInMap = getBBLiveInMap();
524 
525   std::vector<std::unique_ptr<ScheduleDAGMutation>> SavedMutations;
526 
527   do {
528     Stage++;
529     RegionIdx = 0;
530     MachineBasicBlock *MBB = nullptr;
531 
532     if (Stage > InitialSchedule) {
533       if (!LIS)
534         break;
535 
536       // Retry function scheduling if we found resulting occupancy and it is
537       // lower than used for first pass scheduling. This will give more freedom
538       // to schedule low register pressure blocks.
539       // Code is partially copied from MachineSchedulerBase::scheduleRegions().
540 
541       if (Stage == UnclusteredReschedule) {
542         if (RescheduleRegions.none())
543           continue;
544         LLVM_DEBUG(dbgs() <<
545           "Retrying function scheduling without clustering.\n");
546       }
547 
548       if (Stage == ClusteredLowOccupancyReschedule) {
549         if (StartingOccupancy <= MinOccupancy)
550           break;
551 
552         LLVM_DEBUG(
553             dbgs()
554             << "Retrying function scheduling with lowest recorded occupancy "
555             << MinOccupancy << ".\n");
556 
557         S.setTargetOccupancy(MinOccupancy);
558       }
559     }
560 
561     if (Stage == UnclusteredReschedule)
562       SavedMutations.swap(Mutations);
563 
564     for (auto Region : Regions) {
565       if (Stage == UnclusteredReschedule && !RescheduleRegions[RegionIdx]) {
566         ++RegionIdx;
567         continue;
568       }
569 
570       RegionBegin = Region.first;
571       RegionEnd = Region.second;
572 
573       if (RegionBegin->getParent() != MBB) {
574         if (MBB) finishBlock();
575         MBB = RegionBegin->getParent();
576         startBlock(MBB);
577         if (Stage == InitialSchedule)
578           computeBlockPressure(MBB);
579       }
580 
581       unsigned NumRegionInstrs = std::distance(begin(), end());
582       enterRegion(MBB, begin(), end(), NumRegionInstrs);
583 
584       // Skip empty scheduling regions (0 or 1 schedulable instructions).
585       if (begin() == end() || begin() == std::prev(end())) {
586         exitRegion();
587         continue;
588       }
589 
590       LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
591       LLVM_DEBUG(dbgs() << MF.getName() << ":" << printMBBReference(*MBB) << " "
592                         << MBB->getName() << "\n  From: " << *begin()
593                         << "    To: ";
594                  if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
595                  else dbgs() << "End";
596                  dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
597 
598       schedule();
599 
600       exitRegion();
601       ++RegionIdx;
602     }
603     finishBlock();
604 
605     if (Stage == UnclusteredReschedule)
606       SavedMutations.swap(Mutations);
607   } while (Stage != LastStage);
608 }
609