1 //===--------------------- GCNIterativeScheduler.cpp - --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "GCNIterativeScheduler.h"
15 #include "GCNSchedStrategy.h"
16 #include "SIMachineFunctionInfo.h"
17 
18 using namespace llvm;
19 
20 #define DEBUG_TYPE "misched"
21 
22 namespace llvm {
23   std::vector<const SUnit*> makeMinRegSchedule(ArrayRef<const SUnit*> TopRoots,
24     const ScheduleDAG &DAG);
25 }
26 
27 // shim accessors for different order containers
28 static inline MachineInstr *getMachineInstr(MachineInstr *MI) {
29   return MI;
30 }
31 static inline MachineInstr *getMachineInstr(const SUnit *SU) {
32   return SU->getInstr();
33 }
34 static inline MachineInstr *getMachineInstr(const SUnit &SU) {
35   return SU.getInstr();
36 }
37 
38 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
39 LLVM_DUMP_METHOD
40 static void printRegion(raw_ostream &OS,
41                         MachineBasicBlock::iterator Begin,
42                         MachineBasicBlock::iterator End,
43                         const LiveIntervals *LIS,
44                         unsigned MaxInstNum =
45                           std::numeric_limits<unsigned>::max()) {
46   auto BB = Begin->getParent();
47   OS << BB->getParent()->getName() << ":BB#" << BB->getNumber()
48      << ' ' << BB->getName() << ":\n";
49   auto I = Begin;
50   MaxInstNum = std::max(MaxInstNum, 1u);
51   for (; I != End && MaxInstNum; ++I, --MaxInstNum) {
52     if (!I->isDebugValue() && LIS)
53       OS << LIS->getInstructionIndex(*I);
54     OS << '\t' << *I;
55   }
56   if (I != End) {
57     OS << "\t...\n";
58     I = std::prev(End);
59     if (!I->isDebugValue() && LIS)
60       OS << LIS->getInstructionIndex(*I);
61     OS << '\t' << *I;
62   }
63   if (End != BB->end()) { // print boundary inst if present
64     OS << "----\n";
65     if (LIS) OS << LIS->getInstructionIndex(*End) << '\t';
66     OS << *End;
67   }
68 }
69 
70 LLVM_DUMP_METHOD
71 static void printLivenessInfo(raw_ostream &OS,
72                               MachineBasicBlock::iterator Begin,
73                               MachineBasicBlock::iterator End,
74                               const LiveIntervals *LIS) {
75   const auto BB = Begin->getParent();
76   const auto &MRI = BB->getParent()->getRegInfo();
77 
78   const auto LiveIns = getLiveRegsBefore(*Begin, *LIS);
79   OS << "LIn RP: ";
80   getRegPressure(MRI, LiveIns).print(OS);
81 
82   const auto BottomMI = End == BB->end() ? std::prev(End) : End;
83   const auto LiveOuts = getLiveRegsAfter(*BottomMI, *LIS);
84   OS << "LOt RP: ";
85   getRegPressure(MRI, LiveOuts).print(OS);
86 }
87 
88 LLVM_DUMP_METHOD
89 void GCNIterativeScheduler::printRegions(raw_ostream &OS) const {
90   const auto &ST = MF.getSubtarget<SISubtarget>();
91   for (const auto R : Regions) {
92     OS << "Region to schedule ";
93     printRegion(OS, R->Begin, R->End, LIS, 1);
94     printLivenessInfo(OS, R->Begin, R->End, LIS);
95     OS << "Max RP: ";
96     R->MaxPressure.print(OS, &ST);
97   }
98 }
99 
100 LLVM_DUMP_METHOD
101 void GCNIterativeScheduler::printSchedResult(raw_ostream &OS,
102                                              const Region *R,
103                                              const GCNRegPressure &RP) const {
104   OS << "\nAfter scheduling ";
105   printRegion(OS, R->Begin, R->End, LIS);
106   printSchedRP(OS, R->MaxPressure, RP);
107   OS << '\n';
108 }
109 
110 LLVM_DUMP_METHOD
111 void GCNIterativeScheduler::printSchedRP(raw_ostream &OS,
112                                          const GCNRegPressure &Before,
113                                          const GCNRegPressure &After) const {
114   const auto &ST = MF.getSubtarget<SISubtarget>();
115   OS << "RP before: ";
116   Before.print(OS, &ST);
117   OS << "RP after:  ";
118   After.print(OS, &ST);
119 }
120 
121 #endif
122 
123 // DAG builder helper
124 class GCNIterativeScheduler::BuildDAG {
125   GCNIterativeScheduler &Sch;
126   SmallVector<SUnit*, 8> TopRoots;
127 public:
128   BuildDAG(const Region &R, GCNIterativeScheduler &_Sch)
129     : Sch(_Sch) {
130     auto BB = R.Begin->getParent();
131     Sch.BaseClass::startBlock(BB);
132     Sch.BaseClass::enterRegion(BB, R.Begin, R.End, R.NumRegionInstrs);
133 
134     Sch.buildSchedGraph(Sch.AA, nullptr, nullptr, nullptr,
135                         /*TrackLaneMask*/true);
136     Sch.Topo.InitDAGTopologicalSorting();
137 
138     SmallVector<SUnit*, 8> BotRoots;
139     Sch.findRootsAndBiasEdges(TopRoots, BotRoots);
140   }
141   ~BuildDAG() {
142     Sch.BaseClass::exitRegion();
143     Sch.BaseClass::finishBlock();
144   }
145   ArrayRef<const SUnit*> getTopRoots() const {
146     return TopRoots;
147   }
148 };
149 
150 class GCNIterativeScheduler::OverrideLegacyStrategy {
151   GCNIterativeScheduler &Sch;
152   Region &Rgn;
153   std::unique_ptr<MachineSchedStrategy> SaveSchedImpl;
154   GCNRegPressure SaveMaxRP;
155 public:
156   OverrideLegacyStrategy(Region &R,
157                          MachineSchedStrategy &OverrideStrategy,
158                          GCNIterativeScheduler &_Sch)
159     : Sch(_Sch)
160     , Rgn(R)
161     , SaveSchedImpl(std::move(_Sch.SchedImpl))
162     , SaveMaxRP(R.MaxPressure) {
163     Sch.SchedImpl.reset(&OverrideStrategy);
164     auto BB = R.Begin->getParent();
165     Sch.BaseClass::startBlock(BB);
166     Sch.BaseClass::enterRegion(BB, R.Begin, R.End, R.NumRegionInstrs);
167   }
168   ~OverrideLegacyStrategy() {
169     Sch.BaseClass::exitRegion();
170     Sch.BaseClass::finishBlock();
171     Sch.SchedImpl.release();
172     Sch.SchedImpl = std::move(SaveSchedImpl);
173   }
174   void schedule() {
175     assert(Sch.RegionBegin == Rgn.Begin && Sch.RegionEnd == Rgn.End);
176     DEBUG(dbgs() << "\nScheduling ";
177       printRegion(dbgs(), Rgn.Begin, Rgn.End, Sch.LIS, 2));
178     Sch.BaseClass::schedule();
179 
180     // Unfortunatelly placeDebugValues incorrectly modifies RegionEnd, restore
181     Sch.RegionEnd = Rgn.End;
182     //assert(Rgn.End == Sch.RegionEnd);
183     Rgn.Begin = Sch.RegionBegin;
184     Rgn.MaxPressure.clear();
185   }
186   void restoreOrder() {
187     assert(Sch.RegionBegin == Rgn.Begin && Sch.RegionEnd == Rgn.End);
188     // DAG SUnits are stored using original region's order
189     // so just use SUnits as the restoring schedule
190     Sch.scheduleRegion(Rgn, Sch.SUnits, SaveMaxRP);
191   }
192 };
193 
194 // just a stub to make base class happy
195 class SchedStrategyStub : public MachineSchedStrategy {
196 public:
197   bool shouldTrackPressure() const override { return false; }
198   bool shouldTrackLaneMasks() const override { return false; }
199   void initialize(ScheduleDAGMI *DAG) override {}
200   SUnit *pickNode(bool &IsTopNode) override { return nullptr; }
201   void schedNode(SUnit *SU, bool IsTopNode) override {}
202   void releaseTopNode(SUnit *SU) override {}
203   void releaseBottomNode(SUnit *SU) override {}
204 };
205 
206 GCNIterativeScheduler::GCNIterativeScheduler(MachineSchedContext *C,
207                                              StrategyKind S)
208   : BaseClass(C, llvm::make_unique<SchedStrategyStub>())
209   , Context(C)
210   , Strategy(S)
211   , UPTracker(*LIS) {
212 }
213 
214 // returns max pressure for a region
215 GCNRegPressure
216 GCNIterativeScheduler::getRegionPressure(MachineBasicBlock::iterator Begin,
217                                          MachineBasicBlock::iterator End)
218   const {
219   // For the purpose of pressure tracking bottom inst of the region should
220   // be also processed. End is either BB end, BB terminator inst or sched
221   // boundary inst.
222   auto const BBEnd = Begin->getParent()->end();
223   auto const BottomMI = End == BBEnd ? std::prev(End) : End;
224 
225   // scheduleRegions walks bottom to top, so its likely we just get next
226   // instruction to track
227   auto AfterBottomMI = std::next(BottomMI);
228   if (AfterBottomMI == BBEnd ||
229       &*AfterBottomMI != UPTracker.getLastTrackedMI()) {
230     UPTracker.reset(*BottomMI);
231   } else {
232     assert(UPTracker.isValid());
233   }
234 
235   for (auto I = BottomMI; I != Begin; --I)
236     UPTracker.recede(*I);
237 
238   UPTracker.recede(*Begin);
239 
240   assert(UPTracker.isValid() ||
241          (dbgs() << "Tracked region ",
242           printRegion(dbgs(), Begin, End, LIS), false));
243   return UPTracker.moveMaxPressure();
244 }
245 
246 // returns max pressure for a tentative schedule
247 template <typename Range> GCNRegPressure
248 GCNIterativeScheduler::getSchedulePressure(const Region &R,
249                                            Range &&Schedule) const {
250   auto const BBEnd = R.Begin->getParent()->end();
251   GCNUpwardRPTracker RPTracker(*LIS);
252   if (R.End != BBEnd) {
253     // R.End points to the boundary instruction but the
254     // schedule doesn't include it
255     RPTracker.reset(*R.End);
256     RPTracker.recede(*R.End);
257   } else {
258     // R.End doesn't point to the boundary instruction
259     RPTracker.reset(*std::prev(BBEnd));
260   }
261   for (auto I = Schedule.end(), B = Schedule.begin(); I != B;) {
262     RPTracker.recede(*getMachineInstr(*--I));
263   }
264   return RPTracker.moveMaxPressure();
265 }
266 
267 void GCNIterativeScheduler::enterRegion(MachineBasicBlock *BB, // overriden
268                                         MachineBasicBlock::iterator Begin,
269                                         MachineBasicBlock::iterator End,
270                                         unsigned NumRegionInstrs) {
271   BaseClass::enterRegion(BB, Begin, End, NumRegionInstrs);
272   if (NumRegionInstrs > 2) {
273     Regions.push_back(
274       new (Alloc.Allocate())
275       Region { Begin, End, NumRegionInstrs,
276                getRegionPressure(Begin, End), nullptr });
277   }
278 }
279 
280 void GCNIterativeScheduler::schedule() { // overriden
281   // do nothing
282   DEBUG(
283     printLivenessInfo(dbgs(), RegionBegin, RegionEnd, LIS);
284     if (!Regions.empty() && Regions.back()->Begin == RegionBegin) {
285       dbgs() << "Max RP: ";
286       Regions.back()->MaxPressure.print(dbgs(), &MF.getSubtarget<SISubtarget>());
287     }
288     dbgs() << '\n';
289   );
290 }
291 
292 void GCNIterativeScheduler::finalizeSchedule() { // overriden
293   if (Regions.empty())
294     return;
295   switch (Strategy) {
296   case SCHEDULE_MINREGONLY: scheduleMinReg(); break;
297   case SCHEDULE_MINREGFORCED: scheduleMinReg(true); break;
298   case SCHEDULE_LEGACYMAXOCCUPANCY: scheduleLegacyMaxOccupancy(); break;
299   }
300 }
301 
302 // Detach schedule from SUnits and interleave it with debug values.
303 // Returned schedule becomes independent of DAG state.
304 std::vector<MachineInstr*>
305 GCNIterativeScheduler::detachSchedule(ScheduleRef Schedule) const {
306   std::vector<MachineInstr*> Res;
307   Res.reserve(Schedule.size() * 2);
308 
309   if (FirstDbgValue)
310     Res.push_back(FirstDbgValue);
311 
312   const auto DbgB = DbgValues.begin(), DbgE = DbgValues.end();
313   for (auto SU : Schedule) {
314     Res.push_back(SU->getInstr());
315     const auto &D = std::find_if(DbgB, DbgE, [SU](decltype(*DbgB) &P) {
316       return P.second == SU->getInstr();
317     });
318     if (D != DbgE)
319       Res.push_back(D->first);
320   }
321   return Res;
322 }
323 
324 void GCNIterativeScheduler::setBestSchedule(Region &R,
325                                             ScheduleRef Schedule,
326                                             const GCNRegPressure &MaxRP) {
327   R.BestSchedule.reset(
328     new TentativeSchedule{ detachSchedule(Schedule), MaxRP });
329 }
330 
331 void GCNIterativeScheduler::scheduleBest(Region &R) {
332   assert(R.BestSchedule.get() && "No schedule specified");
333   scheduleRegion(R, R.BestSchedule->Schedule, R.BestSchedule->MaxPressure);
334   R.BestSchedule.reset();
335 }
336 
337 // minimal required region scheduler, works for ranges of SUnits*,
338 // SUnits or MachineIntrs*
339 template <typename Range>
340 void GCNIterativeScheduler::scheduleRegion(Region &R, Range &&Schedule,
341                                            const GCNRegPressure &MaxRP) {
342   assert(RegionBegin == R.Begin && RegionEnd == R.End);
343   assert(LIS != nullptr);
344 #ifndef NDEBUG
345   const auto SchedMaxRP = getSchedulePressure(R, Schedule);
346 #endif
347   auto BB = R.Begin->getParent();
348   auto Top = R.Begin;
349   for (const auto &I : Schedule) {
350     auto MI = getMachineInstr(I);
351     if (MI != &*Top) {
352       BB->remove(MI);
353       BB->insert(Top, MI);
354       if (!MI->isDebugValue())
355         LIS->handleMove(*MI, true);
356     }
357     if (!MI->isDebugValue()) {
358       // Reset read - undef flags and update them later.
359       for (auto &Op : MI->operands())
360         if (Op.isReg() && Op.isDef())
361           Op.setIsUndef(false);
362 
363       RegisterOperands RegOpers;
364       RegOpers.collect(*MI, *TRI, MRI, /*ShouldTrackLaneMasks*/true,
365                                        /*IgnoreDead*/false);
366       // Adjust liveness and add missing dead+read-undef flags.
367       auto SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
368       RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
369     }
370     Top = std::next(MI->getIterator());
371   }
372   RegionBegin = getMachineInstr(Schedule.front());
373 
374   // Schedule consisting of MachineInstr* is considered 'detached'
375   // and already interleaved with debug values
376   if (!std::is_same<decltype(*Schedule.begin()), MachineInstr*>::value) {
377     placeDebugValues();
378     // Unfortunatelly placeDebugValues incorrectly modifies RegionEnd, restore
379     //assert(R.End == RegionEnd);
380     RegionEnd = R.End;
381   }
382 
383   R.Begin = RegionBegin;
384   R.MaxPressure = MaxRP;
385 
386 #ifndef NDEBUG
387   const auto RegionMaxRP = getRegionPressure(R);
388   const auto &ST = MF.getSubtarget<SISubtarget>();
389 #endif
390   assert((SchedMaxRP == RegionMaxRP && (MaxRP.empty() || SchedMaxRP == MaxRP))
391   || (dbgs() << "Max RP mismatch!!!\n"
392                 "RP for schedule (calculated): ",
393       SchedMaxRP.print(dbgs(), &ST),
394       dbgs() << "RP for schedule (reported): ",
395       MaxRP.print(dbgs(), &ST),
396       dbgs() << "RP after scheduling: ",
397       RegionMaxRP.print(dbgs(), &ST),
398       false));
399 }
400 
401 // Sort recorded regions by pressure - highest at the front
402 void GCNIterativeScheduler::sortRegionsByPressure(unsigned TargetOcc) {
403   const auto &ST = MF.getSubtarget<SISubtarget>();
404   std::sort(Regions.begin(), Regions.end(),
405     [&ST, TargetOcc](const Region *R1, const Region *R2) {
406     return R2->MaxPressure.less(ST, R1->MaxPressure, TargetOcc);
407   });
408 }
409 
410 ///////////////////////////////////////////////////////////////////////////////
411 // Legacy MaxOccupancy Strategy
412 
413 // Tries to increase occupancy applying minreg scheduler for a sequence of
414 // most demanding regions. Obtained schedules are saved as BestSchedule for a
415 // region.
416 // TargetOcc is the best achievable occupancy for a kernel.
417 // Returns better occupancy on success or current occupancy on fail.
418 // BestSchedules aren't deleted on fail.
419 unsigned GCNIterativeScheduler::tryMaximizeOccupancy(unsigned TargetOcc) {
420   // TODO: assert Regions are sorted descending by pressure
421   const auto &ST = MF.getSubtarget<SISubtarget>();
422   const auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
423   DEBUG(dbgs() << "Trying to to improve occupancy, target = " << TargetOcc
424                << ", current = " << Occ << '\n');
425 
426   auto NewOcc = TargetOcc;
427   for (auto R : Regions) {
428     if (R->MaxPressure.getOccupancy(ST) >= NewOcc)
429       break;
430 
431     DEBUG(printRegion(dbgs(), R->Begin, R->End, LIS, 3);
432           printLivenessInfo(dbgs(), R->Begin, R->End, LIS));
433 
434     BuildDAG DAG(*R, *this);
435     const auto MinSchedule = makeMinRegSchedule(DAG.getTopRoots(), *this);
436     const auto MaxRP = getSchedulePressure(*R, MinSchedule);
437     DEBUG(dbgs() << "Occupancy improvement attempt:\n";
438           printSchedRP(dbgs(), R->MaxPressure, MaxRP));
439 
440     NewOcc = std::min(NewOcc, MaxRP.getOccupancy(ST));
441     if (NewOcc <= Occ)
442       break;
443 
444     setBestSchedule(*R, MinSchedule, MaxRP);
445   }
446   DEBUG(dbgs() << "New occupancy = " << NewOcc
447                << ", prev occupancy = " << Occ << '\n');
448   return std::max(NewOcc, Occ);
449 }
450 
451 void GCNIterativeScheduler::scheduleLegacyMaxOccupancy(
452   bool TryMaximizeOccupancy) {
453   const auto &ST = MF.getSubtarget<SISubtarget>();
454   auto TgtOcc = ST.getOccupancyWithLocalMemSize(MF);
455 
456   sortRegionsByPressure(TgtOcc);
457   auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
458 
459   if (TryMaximizeOccupancy && Occ < TgtOcc)
460     Occ = tryMaximizeOccupancy(TgtOcc);
461 
462   // This is really weird but for some magic scheduling regions twice
463   // gives performance improvement
464   const int NumPasses = Occ < TgtOcc ? 2 : 1;
465 
466   TgtOcc = std::min(Occ, TgtOcc);
467   DEBUG(dbgs() << "Scheduling using default scheduler, "
468                   "target occupancy = " << TgtOcc << '\n');
469   GCNMaxOccupancySchedStrategy LStrgy(Context);
470 
471   for (int I = 0; I < NumPasses; ++I) {
472     // running first pass with TargetOccupancy = 0 mimics previous scheduling
473     // approach and is a performance magic
474     LStrgy.setTargetOccupancy(I == 0 ? 0 : TgtOcc);
475     for (auto R : Regions) {
476       OverrideLegacyStrategy Ovr(*R, LStrgy, *this);
477 
478       Ovr.schedule();
479       const auto RP = getRegionPressure(*R);
480       DEBUG(printSchedRP(dbgs(), R->MaxPressure, RP));
481 
482       if (RP.getOccupancy(ST) < TgtOcc) {
483         DEBUG(dbgs() << "Didn't fit into target occupancy O" << TgtOcc);
484         if (R->BestSchedule.get() &&
485             R->BestSchedule->MaxPressure.getOccupancy(ST) >= TgtOcc) {
486           DEBUG(dbgs() << ", scheduling minimal register\n");
487           scheduleBest(*R);
488         } else {
489           DEBUG(dbgs() << ", restoring\n");
490           Ovr.restoreOrder();
491           assert(R->MaxPressure.getOccupancy(ST) >= TgtOcc);
492         }
493       }
494     }
495   }
496 }
497 
498 ///////////////////////////////////////////////////////////////////////////////
499 // Minimal Register Strategy
500 
501 void GCNIterativeScheduler::scheduleMinReg(bool force) {
502   const auto &ST = MF.getSubtarget<SISubtarget>();
503   const auto TgtOcc = ST.getOccupancyWithLocalMemSize(MF);
504   sortRegionsByPressure(TgtOcc);
505 
506   auto MaxPressure = Regions.front()->MaxPressure;
507   for (auto R : Regions) {
508     if (!force && R->MaxPressure.less(ST, MaxPressure, TgtOcc))
509       break;
510 
511     BuildDAG DAG(*R, *this);
512     const auto MinSchedule = makeMinRegSchedule(DAG.getTopRoots(), *this);
513 
514     const auto RP = getSchedulePressure(*R, MinSchedule);
515     DEBUG(if (R->MaxPressure.less(ST, RP, TgtOcc)) {
516       dbgs() << "\nWarning: Pressure becomes worse after minreg!";
517       printSchedRP(dbgs(), R->MaxPressure, RP);
518     });
519 
520     if (!force && MaxPressure.less(ST, RP, TgtOcc))
521       break;
522 
523     scheduleRegion(*R, MinSchedule, RP);
524     DEBUG(printSchedResult(dbgs(), R, RP));
525 
526     MaxPressure = RP;
527   }
528 }
529