1 //===-- SIMachineScheduler.cpp - SI Scheduler Interface -------------------===//
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 /// SI Machine Scheduler interface
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIMachineScheduler.h"
15 #include "AMDGPU.h"
16 #include "SIInstrInfo.h"
17 #include "SIRegisterInfo.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/CodeGen/LiveInterval.h"
22 #include "llvm/CodeGen/LiveIntervals.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/MachineScheduler.h"
26 #include "llvm/CodeGen/RegisterPressure.h"
27 #include "llvm/CodeGen/SlotIndexes.h"
28 #include "llvm/CodeGen/TargetRegisterInfo.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <map>
35 #include <set>
36 #include <utility>
37 #include <vector>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "machine-scheduler"
42 
43 // This scheduler implements a different scheduling algorithm than
44 // GenericScheduler.
45 //
46 // There are several specific architecture behaviours that can't be modelled
47 // for GenericScheduler:
48 // . When accessing the result of an SGPR load instruction, you have to wait
49 // for all the SGPR load instructions before your current instruction to
50 // have finished.
51 // . When accessing the result of an VGPR load instruction, you have to wait
52 // for all the VGPR load instructions previous to the VGPR load instruction
53 // you are interested in to finish.
54 // . The less the register pressure, the best load latencies are hidden
55 //
56 // Moreover some specifities (like the fact a lot of instructions in the shader
57 // have few dependencies) makes the generic scheduler have some unpredictable
58 // behaviours. For example when register pressure becomes high, it can either
59 // manage to prevent register pressure from going too high, or it can
60 // increase register pressure even more than if it hadn't taken register
61 // pressure into account.
62 //
63 // Also some other bad behaviours are generated, like loading at the beginning
64 // of the shader a constant in VGPR you won't need until the end of the shader.
65 //
66 // The scheduling problem for SI can distinguish three main parts:
67 // . Hiding high latencies (texture sampling, etc)
68 // . Hiding low latencies (SGPR constant loading, etc)
69 // . Keeping register usage low for better latency hiding and general
70 //   performance
71 //
72 // Some other things can also affect performance, but are hard to predict
73 // (cache usage, the fact the HW can issue several instructions from different
74 // wavefronts if different types, etc)
75 //
76 // This scheduler tries to solve the scheduling problem by dividing it into
77 // simpler sub-problems. It divides the instructions into blocks, schedules
78 // locally inside the blocks where it takes care of low latencies, and then
79 // chooses the order of the blocks by taking care of high latencies.
80 // Dividing the instructions into blocks helps control keeping register
81 // usage low.
82 //
83 // First the instructions are put into blocks.
84 //   We want the blocks help control register usage and hide high latencies
85 //   later. To help control register usage, we typically want all local
86 //   computations, when for example you create a result that can be comsummed
87 //   right away, to be contained in a block. Block inputs and outputs would
88 //   typically be important results that are needed in several locations of
89 //   the shader. Since we do want blocks to help hide high latencies, we want
90 //   the instructions inside the block to have a minimal set of dependencies
91 //   on high latencies. It will make it easy to pick blocks to hide specific
92 //   high latencies.
93 //   The block creation algorithm is divided into several steps, and several
94 //   variants can be tried during the scheduling process.
95 //
96 // Second the order of the instructions inside the blocks is chosen.
97 //   At that step we do take into account only register usage and hiding
98 //   low latency instructions
99 //
100 // Third the block order is chosen, there we try to hide high latencies
101 // and keep register usage low.
102 //
103 // After the third step, a pass is done to improve the hiding of low
104 // latencies.
105 //
106 // Actually when talking about 'low latency' or 'high latency' it includes
107 // both the latency to get the cache (or global mem) data go to the register,
108 // and the bandwidth limitations.
109 // Increasing the number of active wavefronts helps hide the former, but it
110 // doesn't solve the latter, thus why even if wavefront count is high, we have
111 // to try have as many instructions hiding high latencies as possible.
112 // The OpenCL doc says for example latency of 400 cycles for a global mem access,
113 // which is hidden by 10 instructions if the wavefront count is 10.
114 
115 // Some figures taken from AMD docs:
116 // Both texture and constant L1 caches are 4-way associative with 64 bytes
117 // lines.
118 // Constant cache is shared with 4 CUs.
119 // For texture sampling, the address generation unit receives 4 texture
120 // addresses per cycle, thus we could expect texture sampling latency to be
121 // equivalent to 4 instructions in the very best case (a VGPR is 64 work items,
122 // instructions in a wavefront group are executed every 4 cycles),
123 // or 16 instructions if the other wavefronts associated to the 3 other VALUs
124 // of the CU do texture sampling too. (Don't take these figures too seriously,
125 // as I'm not 100% sure of the computation)
126 // Data exports should get similar latency.
127 // For constant loading, the cache is shader with 4 CUs.
128 // The doc says "a throughput of 16B/cycle for each of the 4 Compute Unit"
129 // I guess if the other CU don't read the cache, it can go up to 64B/cycle.
130 // It means a simple s_buffer_load should take one instruction to hide, as
131 // well as a s_buffer_loadx2 and potentially a s_buffer_loadx8 if on the same
132 // cache line.
133 //
134 // As of today the driver doesn't preload the constants in cache, thus the
135 // first loads get extra latency. The doc says global memory access can be
136 // 300-600 cycles. We do not specially take that into account when scheduling
137 // As we expect the driver to be able to preload the constants soon.
138 
139 // common code //
140 
141 #ifndef NDEBUG
142 
143 static const char *getReasonStr(SIScheduleCandReason Reason) {
144   switch (Reason) {
145   case NoCand:         return "NOCAND";
146   case RegUsage:       return "REGUSAGE";
147   case Latency:        return "LATENCY";
148   case Successor:      return "SUCCESSOR";
149   case Depth:          return "DEPTH";
150   case NodeOrder:      return "ORDER";
151   }
152   llvm_unreachable("Unknown reason!");
153 }
154 
155 #endif
156 
157 namespace llvm {
158 namespace SISched {
159 static bool tryLess(int TryVal, int CandVal,
160                     SISchedulerCandidate &TryCand,
161                     SISchedulerCandidate &Cand,
162                     SIScheduleCandReason Reason) {
163   if (TryVal < CandVal) {
164     TryCand.Reason = Reason;
165     return true;
166   }
167   if (TryVal > CandVal) {
168     if (Cand.Reason > Reason)
169       Cand.Reason = Reason;
170     return true;
171   }
172   Cand.setRepeat(Reason);
173   return false;
174 }
175 
176 static bool tryGreater(int TryVal, int CandVal,
177                        SISchedulerCandidate &TryCand,
178                        SISchedulerCandidate &Cand,
179                        SIScheduleCandReason Reason) {
180   if (TryVal > CandVal) {
181     TryCand.Reason = Reason;
182     return true;
183   }
184   if (TryVal < CandVal) {
185     if (Cand.Reason > Reason)
186       Cand.Reason = Reason;
187     return true;
188   }
189   Cand.setRepeat(Reason);
190   return false;
191 }
192 } // end namespace SISched
193 } // end namespace llvm
194 
195 // SIScheduleBlock //
196 
197 void SIScheduleBlock::addUnit(SUnit *SU) {
198   NodeNum2Index[SU->NodeNum] = SUnits.size();
199   SUnits.push_back(SU);
200 }
201 
202 #ifndef NDEBUG
203 void SIScheduleBlock::traceCandidate(const SISchedCandidate &Cand) {
204 
205   dbgs() << "  SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
206   dbgs() << '\n';
207 }
208 #endif
209 
210 void SIScheduleBlock::tryCandidateTopDown(SISchedCandidate &Cand,
211                                           SISchedCandidate &TryCand) {
212   // Initialize the candidate if needed.
213   if (!Cand.isValid()) {
214     TryCand.Reason = NodeOrder;
215     return;
216   }
217 
218   if (Cand.SGPRUsage > 60 &&
219       SISched::tryLess(TryCand.SGPRUsage, Cand.SGPRUsage,
220                        TryCand, Cand, RegUsage))
221     return;
222 
223   // Schedule low latency instructions as top as possible.
224   // Order of priority is:
225   // . Low latency instructions which do not depend on other low latency
226   //   instructions we haven't waited for
227   // . Other instructions which do not depend on low latency instructions
228   //   we haven't waited for
229   // . Low latencies
230   // . All other instructions
231   // Goal is to get: low latency instructions - independent instructions
232   //     - (eventually some more low latency instructions)
233   //     - instructions that depend on the first low latency instructions.
234   // If in the block there is a lot of constant loads, the SGPR usage
235   // could go quite high, thus above the arbitrary limit of 60 will encourage
236   // use the already loaded constants (in order to release some SGPRs) before
237   // loading more.
238   if (SISched::tryLess(TryCand.HasLowLatencyNonWaitedParent,
239                        Cand.HasLowLatencyNonWaitedParent,
240                        TryCand, Cand, SIScheduleCandReason::Depth))
241     return;
242 
243   if (SISched::tryGreater(TryCand.IsLowLatency, Cand.IsLowLatency,
244                           TryCand, Cand, SIScheduleCandReason::Depth))
245     return;
246 
247   if (TryCand.IsLowLatency &&
248       SISched::tryLess(TryCand.LowLatencyOffset, Cand.LowLatencyOffset,
249                        TryCand, Cand, SIScheduleCandReason::Depth))
250     return;
251 
252   if (SISched::tryLess(TryCand.VGPRUsage, Cand.VGPRUsage,
253                        TryCand, Cand, RegUsage))
254     return;
255 
256   // Fall through to original instruction order.
257   if (TryCand.SU->NodeNum < Cand.SU->NodeNum) {
258     TryCand.Reason = NodeOrder;
259   }
260 }
261 
262 SUnit* SIScheduleBlock::pickNode() {
263   SISchedCandidate TopCand;
264 
265   for (SUnit* SU : TopReadySUs) {
266     SISchedCandidate TryCand;
267     std::vector<unsigned> pressure;
268     std::vector<unsigned> MaxPressure;
269     // Predict register usage after this instruction.
270     TryCand.SU = SU;
271     TopRPTracker.getDownwardPressure(SU->getInstr(), pressure, MaxPressure);
272     TryCand.SGPRUsage = pressure[AMDGPU::RegisterPressureSets::SReg_32];
273     TryCand.VGPRUsage = pressure[AMDGPU::RegisterPressureSets::VGPR_32];
274     TryCand.IsLowLatency = DAG->IsLowLatencySU[SU->NodeNum];
275     TryCand.LowLatencyOffset = DAG->LowLatencyOffset[SU->NodeNum];
276     TryCand.HasLowLatencyNonWaitedParent =
277       HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]];
278     tryCandidateTopDown(TopCand, TryCand);
279     if (TryCand.Reason != NoCand)
280       TopCand.setBest(TryCand);
281   }
282 
283   return TopCand.SU;
284 }
285 
286 
287 // Schedule something valid.
288 void SIScheduleBlock::fastSchedule() {
289   TopReadySUs.clear();
290   if (Scheduled)
291     undoSchedule();
292 
293   for (SUnit* SU : SUnits) {
294     if (!SU->NumPredsLeft)
295       TopReadySUs.push_back(SU);
296   }
297 
298   while (!TopReadySUs.empty()) {
299     SUnit *SU = TopReadySUs[0];
300     ScheduledSUnits.push_back(SU);
301     nodeScheduled(SU);
302   }
303 
304   Scheduled = true;
305 }
306 
307 // Returns if the register was set between first and last.
308 static bool isDefBetween(unsigned Reg,
309                            SlotIndex First, SlotIndex Last,
310                            const MachineRegisterInfo *MRI,
311                            const LiveIntervals *LIS) {
312   for (MachineRegisterInfo::def_instr_iterator
313        UI = MRI->def_instr_begin(Reg),
314        UE = MRI->def_instr_end(); UI != UE; ++UI) {
315     const MachineInstr* MI = &*UI;
316     if (MI->isDebugValue())
317       continue;
318     SlotIndex InstSlot = LIS->getInstructionIndex(*MI).getRegSlot();
319     if (InstSlot >= First && InstSlot <= Last)
320       return true;
321   }
322   return false;
323 }
324 
325 void SIScheduleBlock::initRegPressure(MachineBasicBlock::iterator BeginBlock,
326                                       MachineBasicBlock::iterator EndBlock) {
327   IntervalPressure Pressure, BotPressure;
328   RegPressureTracker RPTracker(Pressure), BotRPTracker(BotPressure);
329   LiveIntervals *LIS = DAG->getLIS();
330   MachineRegisterInfo *MRI = DAG->getMRI();
331   DAG->initRPTracker(TopRPTracker);
332   DAG->initRPTracker(BotRPTracker);
333   DAG->initRPTracker(RPTracker);
334 
335   // Goes though all SU. RPTracker captures what had to be alive for the SUs
336   // to execute, and what is still alive at the end.
337   for (SUnit* SU : ScheduledSUnits) {
338     RPTracker.setPos(SU->getInstr());
339     RPTracker.advance();
340   }
341 
342   // Close the RPTracker to finalize live ins/outs.
343   RPTracker.closeRegion();
344 
345   // Initialize the live ins and live outs.
346   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
347   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
348 
349   // Do not Track Physical Registers, because it messes up.
350   for (const auto &RegMaskPair : RPTracker.getPressure().LiveInRegs) {
351     if (Register::isVirtualRegister(RegMaskPair.RegUnit))
352       LiveInRegs.insert(RegMaskPair.RegUnit);
353   }
354   LiveOutRegs.clear();
355   // There is several possibilities to distinguish:
356   // 1) Reg is not input to any instruction in the block, but is output of one
357   // 2) 1) + read in the block and not needed after it
358   // 3) 1) + read in the block but needed in another block
359   // 4) Reg is input of an instruction but another block will read it too
360   // 5) Reg is input of an instruction and then rewritten in the block.
361   //    result is not read in the block (implies used in another block)
362   // 6) Reg is input of an instruction and then rewritten in the block.
363   //    result is read in the block and not needed in another block
364   // 7) Reg is input of an instruction and then rewritten in the block.
365   //    result is read in the block but also needed in another block
366   // LiveInRegs will contains all the regs in situation 4, 5, 6, 7
367   // We want LiveOutRegs to contain only Regs whose content will be read after
368   // in another block, and whose content was written in the current block,
369   // that is we want it to get 1, 3, 5, 7
370   // Since we made the MIs of a block to be packed all together before
371   // scheduling, then the LiveIntervals were correct, and the RPTracker was
372   // able to correctly handle 5 vs 6, 2 vs 3.
373   // (Note: This is not sufficient for RPTracker to not do mistakes for case 4)
374   // The RPTracker's LiveOutRegs has 1, 3, (some correct or incorrect)4, 5, 7
375   // Comparing to LiveInRegs is not sufficient to differenciate 4 vs 5, 7
376   // The use of findDefBetween removes the case 4.
377   for (const auto &RegMaskPair : RPTracker.getPressure().LiveOutRegs) {
378     Register Reg = RegMaskPair.RegUnit;
379     if (Reg.isVirtual() &&
380         isDefBetween(Reg, LIS->getInstructionIndex(*BeginBlock).getRegSlot(),
381                      LIS->getInstructionIndex(*EndBlock).getRegSlot(), MRI,
382                      LIS)) {
383       LiveOutRegs.insert(Reg);
384     }
385   }
386 
387   // Pressure = sum_alive_registers register size
388   // Internally llvm will represent some registers as big 128 bits registers
389   // for example, but they actually correspond to 4 actual 32 bits registers.
390   // Thus Pressure is not equal to num_alive_registers * constant.
391   LiveInPressure = TopPressure.MaxSetPressure;
392   LiveOutPressure = BotPressure.MaxSetPressure;
393 
394   // Prepares TopRPTracker for top down scheduling.
395   TopRPTracker.closeTop();
396 }
397 
398 void SIScheduleBlock::schedule(MachineBasicBlock::iterator BeginBlock,
399                                MachineBasicBlock::iterator EndBlock) {
400   if (!Scheduled)
401     fastSchedule();
402 
403   // PreScheduling phase to set LiveIn and LiveOut.
404   initRegPressure(BeginBlock, EndBlock);
405   undoSchedule();
406 
407   // Schedule for real now.
408 
409   TopReadySUs.clear();
410 
411   for (SUnit* SU : SUnits) {
412     if (!SU->NumPredsLeft)
413       TopReadySUs.push_back(SU);
414   }
415 
416   while (!TopReadySUs.empty()) {
417     SUnit *SU = pickNode();
418     ScheduledSUnits.push_back(SU);
419     TopRPTracker.setPos(SU->getInstr());
420     TopRPTracker.advance();
421     nodeScheduled(SU);
422   }
423 
424   // TODO: compute InternalAdditionnalPressure.
425   InternalAdditionnalPressure.resize(TopPressure.MaxSetPressure.size());
426 
427   // Check everything is right.
428 #ifndef NDEBUG
429   assert(SUnits.size() == ScheduledSUnits.size() &&
430             TopReadySUs.empty());
431   for (SUnit* SU : SUnits) {
432     assert(SU->isScheduled &&
433               SU->NumPredsLeft == 0);
434   }
435 #endif
436 
437   Scheduled = true;
438 }
439 
440 void SIScheduleBlock::undoSchedule() {
441   for (SUnit* SU : SUnits) {
442     SU->isScheduled = false;
443     for (SDep& Succ : SU->Succs) {
444       if (BC->isSUInBlock(Succ.getSUnit(), ID))
445         undoReleaseSucc(SU, &Succ);
446     }
447   }
448   HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
449   ScheduledSUnits.clear();
450   Scheduled = false;
451 }
452 
453 void SIScheduleBlock::undoReleaseSucc(SUnit *SU, SDep *SuccEdge) {
454   SUnit *SuccSU = SuccEdge->getSUnit();
455 
456   if (SuccEdge->isWeak()) {
457     ++SuccSU->WeakPredsLeft;
458     return;
459   }
460   ++SuccSU->NumPredsLeft;
461 }
462 
463 void SIScheduleBlock::releaseSucc(SUnit *SU, SDep *SuccEdge) {
464   SUnit *SuccSU = SuccEdge->getSUnit();
465 
466   if (SuccEdge->isWeak()) {
467     --SuccSU->WeakPredsLeft;
468     return;
469   }
470 #ifndef NDEBUG
471   if (SuccSU->NumPredsLeft == 0) {
472     dbgs() << "*** Scheduling failed! ***\n";
473     DAG->dumpNode(*SuccSU);
474     dbgs() << " has been released too many times!\n";
475     llvm_unreachable(nullptr);
476   }
477 #endif
478 
479   --SuccSU->NumPredsLeft;
480 }
481 
482 /// Release Successors of the SU that are in the block or not.
483 void SIScheduleBlock::releaseSuccessors(SUnit *SU, bool InOrOutBlock) {
484   for (SDep& Succ : SU->Succs) {
485     SUnit *SuccSU = Succ.getSUnit();
486 
487     if (SuccSU->NodeNum >= DAG->SUnits.size())
488         continue;
489 
490     if (BC->isSUInBlock(SuccSU, ID) != InOrOutBlock)
491       continue;
492 
493     releaseSucc(SU, &Succ);
494     if (SuccSU->NumPredsLeft == 0 && InOrOutBlock)
495       TopReadySUs.push_back(SuccSU);
496   }
497 }
498 
499 void SIScheduleBlock::nodeScheduled(SUnit *SU) {
500   // Is in TopReadySUs
501   assert (!SU->NumPredsLeft);
502   std::vector<SUnit *>::iterator I = llvm::find(TopReadySUs, SU);
503   if (I == TopReadySUs.end()) {
504     dbgs() << "Data Structure Bug in SI Scheduler\n";
505     llvm_unreachable(nullptr);
506   }
507   TopReadySUs.erase(I);
508 
509   releaseSuccessors(SU, true);
510   // Scheduling this node will trigger a wait,
511   // thus propagate to other instructions that they do not need to wait either.
512   if (HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]])
513     HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
514 
515   if (DAG->IsLowLatencySU[SU->NodeNum]) {
516      for (SDep& Succ : SU->Succs) {
517       std::map<unsigned, unsigned>::iterator I =
518         NodeNum2Index.find(Succ.getSUnit()->NodeNum);
519       if (I != NodeNum2Index.end())
520         HasLowLatencyNonWaitedParent[I->second] = 1;
521     }
522   }
523   SU->isScheduled = true;
524 }
525 
526 void SIScheduleBlock::finalizeUnits() {
527   // We remove links from outside blocks to enable scheduling inside the block.
528   for (SUnit* SU : SUnits) {
529     releaseSuccessors(SU, false);
530     if (DAG->IsHighLatencySU[SU->NodeNum])
531       HighLatencyBlock = true;
532   }
533   HasLowLatencyNonWaitedParent.resize(SUnits.size(), 0);
534 }
535 
536 // we maintain ascending order of IDs
537 void SIScheduleBlock::addPred(SIScheduleBlock *Pred) {
538   unsigned PredID = Pred->getID();
539 
540   // Check if not already predecessor.
541   for (SIScheduleBlock* P : Preds) {
542     if (PredID == P->getID())
543       return;
544   }
545   Preds.push_back(Pred);
546 
547   assert(none_of(Succs,
548                  [=](std::pair<SIScheduleBlock*,
549                      SIScheduleBlockLinkKind> S) {
550                    return PredID == S.first->getID();
551                     }) &&
552          "Loop in the Block Graph!");
553 }
554 
555 void SIScheduleBlock::addSucc(SIScheduleBlock *Succ,
556                               SIScheduleBlockLinkKind Kind) {
557   unsigned SuccID = Succ->getID();
558 
559   // Check if not already predecessor.
560   for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> &S : Succs) {
561     if (SuccID == S.first->getID()) {
562       if (S.second == SIScheduleBlockLinkKind::NoData &&
563           Kind == SIScheduleBlockLinkKind::Data)
564         S.second = Kind;
565       return;
566     }
567   }
568   if (Succ->isHighLatencyBlock())
569     ++NumHighLatencySuccessors;
570   Succs.push_back(std::make_pair(Succ, Kind));
571 
572   assert(none_of(Preds,
573                  [=](SIScheduleBlock *P) { return SuccID == P->getID(); }) &&
574          "Loop in the Block Graph!");
575 }
576 
577 #ifndef NDEBUG
578 void SIScheduleBlock::printDebug(bool full) {
579   dbgs() << "Block (" << ID << ")\n";
580   if (!full)
581     return;
582 
583   dbgs() << "\nContains High Latency Instruction: "
584          << HighLatencyBlock << '\n';
585   dbgs() << "\nDepends On:\n";
586   for (SIScheduleBlock* P : Preds) {
587     P->printDebug(false);
588   }
589 
590   dbgs() << "\nSuccessors:\n";
591   for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> S : Succs) {
592     if (S.second == SIScheduleBlockLinkKind::Data)
593       dbgs() << "(Data Dep) ";
594     S.first->printDebug(false);
595   }
596 
597   if (Scheduled) {
598     dbgs() << "LiveInPressure "
599            << LiveInPressure[AMDGPU::RegisterPressureSets::SReg_32] << ' '
600            << LiveInPressure[AMDGPU::RegisterPressureSets::VGPR_32] << '\n';
601     dbgs() << "LiveOutPressure "
602            << LiveOutPressure[AMDGPU::RegisterPressureSets::SReg_32] << ' '
603            << LiveOutPressure[AMDGPU::RegisterPressureSets::VGPR_32] << "\n\n";
604     dbgs() << "LiveIns:\n";
605     for (unsigned Reg : LiveInRegs)
606       dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
607 
608     dbgs() << "\nLiveOuts:\n";
609     for (unsigned Reg : LiveOutRegs)
610       dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
611   }
612 
613   dbgs() << "\nInstructions:\n";
614   for (const SUnit* SU : SUnits)
615       DAG->dumpNode(*SU);
616 
617   dbgs() << "///////////////////////\n";
618 }
619 #endif
620 
621 // SIScheduleBlockCreator //
622 
623 SIScheduleBlockCreator::SIScheduleBlockCreator(SIScheduleDAGMI *DAG)
624     : DAG(DAG) {}
625 
626 SIScheduleBlocks
627 SIScheduleBlockCreator::getBlocks(SISchedulerBlockCreatorVariant BlockVariant) {
628   std::map<SISchedulerBlockCreatorVariant, SIScheduleBlocks>::iterator B =
629     Blocks.find(BlockVariant);
630   if (B == Blocks.end()) {
631     SIScheduleBlocks Res;
632     createBlocksForVariant(BlockVariant);
633     topologicalSort();
634     scheduleInsideBlocks();
635     fillStats();
636     Res.Blocks = CurrentBlocks;
637     Res.TopDownIndex2Block = TopDownIndex2Block;
638     Res.TopDownBlock2Index = TopDownBlock2Index;
639     Blocks[BlockVariant] = Res;
640     return Res;
641   } else {
642     return B->second;
643   }
644 }
645 
646 bool SIScheduleBlockCreator::isSUInBlock(SUnit *SU, unsigned ID) {
647   if (SU->NodeNum >= DAG->SUnits.size())
648     return false;
649   return CurrentBlocks[Node2CurrentBlock[SU->NodeNum]]->getID() == ID;
650 }
651 
652 void SIScheduleBlockCreator::colorHighLatenciesAlone() {
653   unsigned DAGSize = DAG->SUnits.size();
654 
655   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
656     SUnit *SU = &DAG->SUnits[i];
657     if (DAG->IsHighLatencySU[SU->NodeNum]) {
658       CurrentColoring[SU->NodeNum] = NextReservedID++;
659     }
660   }
661 }
662 
663 static bool
664 hasDataDependencyPred(const SUnit &SU, const SUnit &FromSU) {
665   for (const auto &PredDep : SU.Preds) {
666     if (PredDep.getSUnit() == &FromSU &&
667         PredDep.getKind() == llvm::SDep::Data)
668       return true;
669   }
670   return false;
671 }
672 
673 void SIScheduleBlockCreator::colorHighLatenciesGroups() {
674   unsigned DAGSize = DAG->SUnits.size();
675   unsigned NumHighLatencies = 0;
676   unsigned GroupSize;
677   int Color = NextReservedID;
678   unsigned Count = 0;
679   std::set<unsigned> FormingGroup;
680 
681   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
682     SUnit *SU = &DAG->SUnits[i];
683     if (DAG->IsHighLatencySU[SU->NodeNum])
684       ++NumHighLatencies;
685   }
686 
687   if (NumHighLatencies == 0)
688     return;
689 
690   if (NumHighLatencies <= 6)
691     GroupSize = 2;
692   else if (NumHighLatencies <= 12)
693     GroupSize = 3;
694   else
695     GroupSize = 4;
696 
697   for (unsigned SUNum : DAG->TopDownIndex2SU) {
698     const SUnit &SU = DAG->SUnits[SUNum];
699     if (DAG->IsHighLatencySU[SU.NodeNum]) {
700       unsigned CompatibleGroup = true;
701       int ProposedColor = Color;
702       std::vector<int> AdditionalElements;
703 
704       // We don't want to put in the same block
705       // two high latency instructions that depend
706       // on each other.
707       // One way would be to check canAddEdge
708       // in both directions, but that currently is not
709       // enough because there the high latency order is
710       // enforced (via links).
711       // Instead, look at the dependencies between the
712       // high latency instructions and deduce if it is
713       // a data dependency or not.
714       for (unsigned j : FormingGroup) {
715         bool HasSubGraph;
716         std::vector<int> SubGraph;
717         // By construction (topological order), if SU and
718         // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary
719         // in the parent graph of SU.
720 #ifndef NDEBUG
721         SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j],
722                                                HasSubGraph);
723         assert(!HasSubGraph);
724 #endif
725         SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU,
726                                                HasSubGraph);
727         if (!HasSubGraph)
728           continue; // No dependencies between each other
729         else if (SubGraph.size() > 5) {
730           // Too many elements would be required to be added to the block.
731           CompatibleGroup = false;
732           break;
733         }
734         else {
735           // Check the type of dependency
736           for (unsigned k : SubGraph) {
737             // If in the path to join the two instructions,
738             // there is another high latency instruction,
739             // or instructions colored for another block
740             // abort the merge.
741             if (DAG->IsHighLatencySU[k] ||
742                 (CurrentColoring[k] != ProposedColor &&
743                  CurrentColoring[k] != 0)) {
744               CompatibleGroup = false;
745               break;
746             }
747             // If one of the SU in the subgraph depends on the result of SU j,
748             // there'll be a data dependency.
749             if (hasDataDependencyPred(DAG->SUnits[k], DAG->SUnits[j])) {
750               CompatibleGroup = false;
751               break;
752             }
753           }
754           if (!CompatibleGroup)
755             break;
756           // Same check for the SU
757           if (hasDataDependencyPred(SU, DAG->SUnits[j])) {
758             CompatibleGroup = false;
759             break;
760           }
761           // Add all the required instructions to the block
762           // These cannot live in another block (because they
763           // depend (order dependency) on one of the
764           // instruction in the block, and are required for the
765           // high latency instruction we add.
766           llvm::append_range(AdditionalElements, SubGraph);
767         }
768       }
769       if (CompatibleGroup) {
770         FormingGroup.insert(SU.NodeNum);
771         for (unsigned j : AdditionalElements)
772           CurrentColoring[j] = ProposedColor;
773         CurrentColoring[SU.NodeNum] = ProposedColor;
774         ++Count;
775       }
776       // Found one incompatible instruction,
777       // or has filled a big enough group.
778       // -> start a new one.
779       if (!CompatibleGroup) {
780         FormingGroup.clear();
781         Color = ++NextReservedID;
782         ProposedColor = Color;
783         FormingGroup.insert(SU.NodeNum);
784         CurrentColoring[SU.NodeNum] = ProposedColor;
785         Count = 0;
786       } else if (Count == GroupSize) {
787         FormingGroup.clear();
788         Color = ++NextReservedID;
789         ProposedColor = Color;
790         Count = 0;
791       }
792     }
793   }
794 }
795 
796 void SIScheduleBlockCreator::colorComputeReservedDependencies() {
797   unsigned DAGSize = DAG->SUnits.size();
798   std::map<std::set<unsigned>, unsigned> ColorCombinations;
799 
800   CurrentTopDownReservedDependencyColoring.clear();
801   CurrentBottomUpReservedDependencyColoring.clear();
802 
803   CurrentTopDownReservedDependencyColoring.resize(DAGSize, 0);
804   CurrentBottomUpReservedDependencyColoring.resize(DAGSize, 0);
805 
806   // Traverse TopDown, and give different colors to SUs depending
807   // on which combination of High Latencies they depend on.
808 
809   for (unsigned SUNum : DAG->TopDownIndex2SU) {
810     SUnit *SU = &DAG->SUnits[SUNum];
811     std::set<unsigned> SUColors;
812 
813     // Already given.
814     if (CurrentColoring[SU->NodeNum]) {
815       CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
816         CurrentColoring[SU->NodeNum];
817       continue;
818     }
819 
820    for (SDep& PredDep : SU->Preds) {
821       SUnit *Pred = PredDep.getSUnit();
822       if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
823         continue;
824       if (CurrentTopDownReservedDependencyColoring[Pred->NodeNum] > 0)
825         SUColors.insert(CurrentTopDownReservedDependencyColoring[Pred->NodeNum]);
826     }
827     // Color 0 by default.
828     if (SUColors.empty())
829       continue;
830     // Same color than parents.
831     if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
832       CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
833         *SUColors.begin();
834     else {
835       std::map<std::set<unsigned>, unsigned>::iterator Pos =
836         ColorCombinations.find(SUColors);
837       if (Pos != ColorCombinations.end()) {
838           CurrentTopDownReservedDependencyColoring[SU->NodeNum] = Pos->second;
839       } else {
840         CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
841           NextNonReservedID;
842         ColorCombinations[SUColors] = NextNonReservedID++;
843       }
844     }
845   }
846 
847   ColorCombinations.clear();
848 
849   // Same as before, but BottomUp.
850 
851   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
852     SUnit *SU = &DAG->SUnits[SUNum];
853     std::set<unsigned> SUColors;
854 
855     // Already given.
856     if (CurrentColoring[SU->NodeNum]) {
857       CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
858         CurrentColoring[SU->NodeNum];
859       continue;
860     }
861 
862     for (SDep& SuccDep : SU->Succs) {
863       SUnit *Succ = SuccDep.getSUnit();
864       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
865         continue;
866       if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0)
867         SUColors.insert(CurrentBottomUpReservedDependencyColoring[Succ->NodeNum]);
868     }
869     // Keep color 0.
870     if (SUColors.empty())
871       continue;
872     // Same color than parents.
873     if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
874       CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
875         *SUColors.begin();
876     else {
877       std::map<std::set<unsigned>, unsigned>::iterator Pos =
878         ColorCombinations.find(SUColors);
879       if (Pos != ColorCombinations.end()) {
880         CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = Pos->second;
881       } else {
882         CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
883           NextNonReservedID;
884         ColorCombinations[SUColors] = NextNonReservedID++;
885       }
886     }
887   }
888 }
889 
890 void SIScheduleBlockCreator::colorAccordingToReservedDependencies() {
891   unsigned DAGSize = DAG->SUnits.size();
892   std::map<std::pair<unsigned, unsigned>, unsigned> ColorCombinations;
893 
894   // Every combination of colors given by the top down
895   // and bottom up Reserved node dependency
896 
897   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
898     SUnit *SU = &DAG->SUnits[i];
899     std::pair<unsigned, unsigned> SUColors;
900 
901     // High latency instructions: already given.
902     if (CurrentColoring[SU->NodeNum])
903       continue;
904 
905     SUColors.first = CurrentTopDownReservedDependencyColoring[SU->NodeNum];
906     SUColors.second = CurrentBottomUpReservedDependencyColoring[SU->NodeNum];
907 
908     std::map<std::pair<unsigned, unsigned>, unsigned>::iterator Pos =
909       ColorCombinations.find(SUColors);
910     if (Pos != ColorCombinations.end()) {
911       CurrentColoring[SU->NodeNum] = Pos->second;
912     } else {
913       CurrentColoring[SU->NodeNum] = NextNonReservedID;
914       ColorCombinations[SUColors] = NextNonReservedID++;
915     }
916   }
917 }
918 
919 void SIScheduleBlockCreator::colorEndsAccordingToDependencies() {
920   unsigned DAGSize = DAG->SUnits.size();
921   std::vector<int> PendingColoring = CurrentColoring;
922 
923   assert(DAGSize >= 1 &&
924          CurrentBottomUpReservedDependencyColoring.size() == DAGSize &&
925          CurrentTopDownReservedDependencyColoring.size() == DAGSize);
926   // If there is no reserved block at all, do nothing. We don't want
927   // everything in one block.
928   if (*std::max_element(CurrentBottomUpReservedDependencyColoring.begin(),
929                         CurrentBottomUpReservedDependencyColoring.end()) == 0 &&
930       *std::max_element(CurrentTopDownReservedDependencyColoring.begin(),
931                         CurrentTopDownReservedDependencyColoring.end()) == 0)
932     return;
933 
934   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
935     SUnit *SU = &DAG->SUnits[SUNum];
936     std::set<unsigned> SUColors;
937     std::set<unsigned> SUColorsPending;
938 
939     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
940       continue;
941 
942     if (CurrentBottomUpReservedDependencyColoring[SU->NodeNum] > 0 ||
943         CurrentTopDownReservedDependencyColoring[SU->NodeNum] > 0)
944       continue;
945 
946     for (SDep& SuccDep : SU->Succs) {
947       SUnit *Succ = SuccDep.getSUnit();
948       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
949         continue;
950       if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0 ||
951           CurrentTopDownReservedDependencyColoring[Succ->NodeNum] > 0)
952         SUColors.insert(CurrentColoring[Succ->NodeNum]);
953       SUColorsPending.insert(PendingColoring[Succ->NodeNum]);
954     }
955     // If there is only one child/parent block, and that block
956     // is not among the ones we are removing in this path, then
957     // merge the instruction to that block
958     if (SUColors.size() == 1 && SUColorsPending.size() == 1)
959       PendingColoring[SU->NodeNum] = *SUColors.begin();
960     else // TODO: Attribute new colors depending on color
961          // combination of children.
962       PendingColoring[SU->NodeNum] = NextNonReservedID++;
963   }
964   CurrentColoring = PendingColoring;
965 }
966 
967 
968 void SIScheduleBlockCreator::colorForceConsecutiveOrderInGroup() {
969   unsigned DAGSize = DAG->SUnits.size();
970   unsigned PreviousColor;
971   std::set<unsigned> SeenColors;
972 
973   if (DAGSize <= 1)
974     return;
975 
976   PreviousColor = CurrentColoring[0];
977 
978   for (unsigned i = 1, e = DAGSize; i != e; ++i) {
979     SUnit *SU = &DAG->SUnits[i];
980     unsigned CurrentColor = CurrentColoring[i];
981     unsigned PreviousColorSave = PreviousColor;
982     assert(i == SU->NodeNum);
983 
984     if (CurrentColor != PreviousColor)
985       SeenColors.insert(PreviousColor);
986     PreviousColor = CurrentColor;
987 
988     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
989       continue;
990 
991     if (SeenColors.find(CurrentColor) == SeenColors.end())
992       continue;
993 
994     if (PreviousColorSave != CurrentColor)
995       CurrentColoring[i] = NextNonReservedID++;
996     else
997       CurrentColoring[i] = CurrentColoring[i-1];
998   }
999 }
1000 
1001 void SIScheduleBlockCreator::colorMergeConstantLoadsNextGroup() {
1002   unsigned DAGSize = DAG->SUnits.size();
1003 
1004   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1005     SUnit *SU = &DAG->SUnits[SUNum];
1006     std::set<unsigned> SUColors;
1007 
1008     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1009       continue;
1010 
1011     // No predecessor: Vgpr constant loading.
1012     // Low latency instructions usually have a predecessor (the address)
1013     if (SU->Preds.size() > 0 && !DAG->IsLowLatencySU[SU->NodeNum])
1014       continue;
1015 
1016     for (SDep& SuccDep : SU->Succs) {
1017       SUnit *Succ = SuccDep.getSUnit();
1018       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1019         continue;
1020       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1021     }
1022     if (SUColors.size() == 1)
1023       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1024   }
1025 }
1026 
1027 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroup() {
1028   unsigned DAGSize = DAG->SUnits.size();
1029 
1030   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1031     SUnit *SU = &DAG->SUnits[SUNum];
1032     std::set<unsigned> SUColors;
1033 
1034     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1035       continue;
1036 
1037     for (SDep& SuccDep : SU->Succs) {
1038        SUnit *Succ = SuccDep.getSUnit();
1039       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1040         continue;
1041       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1042     }
1043     if (SUColors.size() == 1)
1044       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1045   }
1046 }
1047 
1048 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroupOnlyForReserved() {
1049   unsigned DAGSize = DAG->SUnits.size();
1050 
1051   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1052     SUnit *SU = &DAG->SUnits[SUNum];
1053     std::set<unsigned> SUColors;
1054 
1055     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1056       continue;
1057 
1058     for (SDep& SuccDep : SU->Succs) {
1059        SUnit *Succ = SuccDep.getSUnit();
1060       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1061         continue;
1062       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1063     }
1064     if (SUColors.size() == 1 && *SUColors.begin() <= DAGSize)
1065       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1066   }
1067 }
1068 
1069 void SIScheduleBlockCreator::colorMergeIfPossibleSmallGroupsToNextGroup() {
1070   unsigned DAGSize = DAG->SUnits.size();
1071   std::map<unsigned, unsigned> ColorCount;
1072 
1073   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1074     SUnit *SU = &DAG->SUnits[SUNum];
1075     unsigned color = CurrentColoring[SU->NodeNum];
1076      ++ColorCount[color];
1077   }
1078 
1079   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1080     SUnit *SU = &DAG->SUnits[SUNum];
1081     unsigned color = CurrentColoring[SU->NodeNum];
1082     std::set<unsigned> SUColors;
1083 
1084     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1085       continue;
1086 
1087     if (ColorCount[color] > 1)
1088       continue;
1089 
1090     for (SDep& SuccDep : SU->Succs) {
1091        SUnit *Succ = SuccDep.getSUnit();
1092       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1093         continue;
1094       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1095     }
1096     if (SUColors.size() == 1 && *SUColors.begin() != color) {
1097       --ColorCount[color];
1098       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1099       ++ColorCount[*SUColors.begin()];
1100     }
1101   }
1102 }
1103 
1104 void SIScheduleBlockCreator::cutHugeBlocks() {
1105   // TODO
1106 }
1107 
1108 void SIScheduleBlockCreator::regroupNoUserInstructions() {
1109   unsigned DAGSize = DAG->SUnits.size();
1110   int GroupID = NextNonReservedID++;
1111 
1112   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1113     SUnit *SU = &DAG->SUnits[SUNum];
1114     bool hasSuccessor = false;
1115 
1116     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1117       continue;
1118 
1119     for (SDep& SuccDep : SU->Succs) {
1120        SUnit *Succ = SuccDep.getSUnit();
1121       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1122         continue;
1123       hasSuccessor = true;
1124     }
1125     if (!hasSuccessor)
1126       CurrentColoring[SU->NodeNum] = GroupID;
1127   }
1128 }
1129 
1130 void SIScheduleBlockCreator::colorExports() {
1131   unsigned ExportColor = NextNonReservedID++;
1132   SmallVector<unsigned, 8> ExpGroup;
1133 
1134   // Put all exports together in a block.
1135   // The block will naturally end up being scheduled last,
1136   // thus putting exports at the end of the schedule, which
1137   // is better for performance.
1138   // However we must ensure, for safety, the exports can be put
1139   // together in the same block without any other instruction.
1140   // This could happen, for example, when scheduling after regalloc
1141   // if reloading a spilled register from memory using the same
1142   // register than used in a previous export.
1143   // If that happens, do not regroup the exports.
1144   for (unsigned SUNum : DAG->TopDownIndex2SU) {
1145     const SUnit &SU = DAG->SUnits[SUNum];
1146     if (SIInstrInfo::isEXP(*SU.getInstr())) {
1147       // Check the EXP can be added to the group safely,
1148       // ie without needing any other instruction.
1149       // The EXP is allowed to depend on other EXP
1150       // (they will be in the same group).
1151       for (unsigned j : ExpGroup) {
1152         bool HasSubGraph;
1153         std::vector<int> SubGraph;
1154         // By construction (topological order), if SU and
1155         // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary
1156         // in the parent graph of SU.
1157 #ifndef NDEBUG
1158         SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j],
1159                                                HasSubGraph);
1160         assert(!HasSubGraph);
1161 #endif
1162         SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU,
1163                                                HasSubGraph);
1164         if (!HasSubGraph)
1165           continue; // No dependencies between each other
1166 
1167         // SubGraph contains all the instructions required
1168         // between EXP SUnits[j] and EXP SU.
1169         for (unsigned k : SubGraph) {
1170           if (!SIInstrInfo::isEXP(*DAG->SUnits[k].getInstr()))
1171             // Other instructions than EXP would be required in the group.
1172             // Abort the groupping.
1173             return;
1174         }
1175       }
1176 
1177       ExpGroup.push_back(SUNum);
1178     }
1179   }
1180 
1181   // The group can be formed. Give the color.
1182   for (unsigned j : ExpGroup)
1183     CurrentColoring[j] = ExportColor;
1184 }
1185 
1186 void SIScheduleBlockCreator::createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant) {
1187   unsigned DAGSize = DAG->SUnits.size();
1188   std::map<unsigned,unsigned> RealID;
1189 
1190   CurrentBlocks.clear();
1191   CurrentColoring.clear();
1192   CurrentColoring.resize(DAGSize, 0);
1193   Node2CurrentBlock.clear();
1194 
1195   // Restore links previous scheduling variant has overridden.
1196   DAG->restoreSULinksLeft();
1197 
1198   NextReservedID = 1;
1199   NextNonReservedID = DAGSize + 1;
1200 
1201   LLVM_DEBUG(dbgs() << "Coloring the graph\n");
1202 
1203   if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesGrouped)
1204     colorHighLatenciesGroups();
1205   else
1206     colorHighLatenciesAlone();
1207   colorComputeReservedDependencies();
1208   colorAccordingToReservedDependencies();
1209   colorEndsAccordingToDependencies();
1210   if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesAlonePlusConsecutive)
1211     colorForceConsecutiveOrderInGroup();
1212   regroupNoUserInstructions();
1213   colorMergeConstantLoadsNextGroup();
1214   colorMergeIfPossibleNextGroupOnlyForReserved();
1215   colorExports();
1216 
1217   // Put SUs of same color into same block
1218   Node2CurrentBlock.resize(DAGSize, -1);
1219   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1220     SUnit *SU = &DAG->SUnits[i];
1221     unsigned Color = CurrentColoring[SU->NodeNum];
1222     if (RealID.find(Color) == RealID.end()) {
1223       int ID = CurrentBlocks.size();
1224       BlockPtrs.push_back(std::make_unique<SIScheduleBlock>(DAG, this, ID));
1225       CurrentBlocks.push_back(BlockPtrs.rbegin()->get());
1226       RealID[Color] = ID;
1227     }
1228     CurrentBlocks[RealID[Color]]->addUnit(SU);
1229     Node2CurrentBlock[SU->NodeNum] = RealID[Color];
1230   }
1231 
1232   // Build dependencies between blocks.
1233   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1234     SUnit *SU = &DAG->SUnits[i];
1235     int SUID = Node2CurrentBlock[i];
1236      for (SDep& SuccDep : SU->Succs) {
1237        SUnit *Succ = SuccDep.getSUnit();
1238       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1239         continue;
1240       if (Node2CurrentBlock[Succ->NodeNum] != SUID)
1241         CurrentBlocks[SUID]->addSucc(CurrentBlocks[Node2CurrentBlock[Succ->NodeNum]],
1242                                      SuccDep.isCtrl() ? NoData : Data);
1243     }
1244     for (SDep& PredDep : SU->Preds) {
1245       SUnit *Pred = PredDep.getSUnit();
1246       if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
1247         continue;
1248       if (Node2CurrentBlock[Pred->NodeNum] != SUID)
1249         CurrentBlocks[SUID]->addPred(CurrentBlocks[Node2CurrentBlock[Pred->NodeNum]]);
1250     }
1251   }
1252 
1253   // Free root and leafs of all blocks to enable scheduling inside them.
1254   for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1255     SIScheduleBlock *Block = CurrentBlocks[i];
1256     Block->finalizeUnits();
1257   }
1258   LLVM_DEBUG(dbgs() << "Blocks created:\n\n";
1259              for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1260                SIScheduleBlock *Block = CurrentBlocks[i];
1261                Block->printDebug(true);
1262              });
1263 }
1264 
1265 // Two functions taken from Codegen/MachineScheduler.cpp
1266 
1267 /// Non-const version.
1268 static MachineBasicBlock::iterator
1269 nextIfDebug(MachineBasicBlock::iterator I,
1270             MachineBasicBlock::const_iterator End) {
1271   for (; I != End; ++I) {
1272     if (!I->isDebugInstr())
1273       break;
1274   }
1275   return I;
1276 }
1277 
1278 void SIScheduleBlockCreator::topologicalSort() {
1279   unsigned DAGSize = CurrentBlocks.size();
1280   std::vector<int> WorkList;
1281 
1282   LLVM_DEBUG(dbgs() << "Topological Sort\n");
1283 
1284   WorkList.reserve(DAGSize);
1285   TopDownIndex2Block.resize(DAGSize);
1286   TopDownBlock2Index.resize(DAGSize);
1287   BottomUpIndex2Block.resize(DAGSize);
1288 
1289   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1290     SIScheduleBlock *Block = CurrentBlocks[i];
1291     unsigned Degree = Block->getSuccs().size();
1292     TopDownBlock2Index[i] = Degree;
1293     if (Degree == 0) {
1294       WorkList.push_back(i);
1295     }
1296   }
1297 
1298   int Id = DAGSize;
1299   while (!WorkList.empty()) {
1300     int i = WorkList.back();
1301     SIScheduleBlock *Block = CurrentBlocks[i];
1302     WorkList.pop_back();
1303     TopDownBlock2Index[i] = --Id;
1304     TopDownIndex2Block[Id] = i;
1305     for (SIScheduleBlock* Pred : Block->getPreds()) {
1306       if (!--TopDownBlock2Index[Pred->getID()])
1307         WorkList.push_back(Pred->getID());
1308     }
1309   }
1310 
1311 #ifndef NDEBUG
1312   // Check correctness of the ordering.
1313   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1314     SIScheduleBlock *Block = CurrentBlocks[i];
1315     for (SIScheduleBlock* Pred : Block->getPreds()) {
1316       assert(TopDownBlock2Index[i] > TopDownBlock2Index[Pred->getID()] &&
1317       "Wrong Top Down topological sorting");
1318     }
1319   }
1320 #endif
1321 
1322   BottomUpIndex2Block = std::vector<int>(TopDownIndex2Block.rbegin(),
1323                                          TopDownIndex2Block.rend());
1324 }
1325 
1326 void SIScheduleBlockCreator::scheduleInsideBlocks() {
1327   unsigned DAGSize = CurrentBlocks.size();
1328 
1329   LLVM_DEBUG(dbgs() << "\nScheduling Blocks\n\n");
1330 
1331   // We do schedule a valid scheduling such that a Block corresponds
1332   // to a range of instructions.
1333   LLVM_DEBUG(dbgs() << "First phase: Fast scheduling for Reg Liveness\n");
1334   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1335     SIScheduleBlock *Block = CurrentBlocks[i];
1336     Block->fastSchedule();
1337   }
1338 
1339   // Note: the following code, and the part restoring previous position
1340   // is by far the most expensive operation of the Scheduler.
1341 
1342   // Do not update CurrentTop.
1343   MachineBasicBlock::iterator CurrentTopFastSched = DAG->getCurrentTop();
1344   std::vector<MachineBasicBlock::iterator> PosOld;
1345   std::vector<MachineBasicBlock::iterator> PosNew;
1346   PosOld.reserve(DAG->SUnits.size());
1347   PosNew.reserve(DAG->SUnits.size());
1348 
1349   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1350     int BlockIndice = TopDownIndex2Block[i];
1351     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1352     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1353 
1354     for (SUnit* SU : SUs) {
1355       MachineInstr *MI = SU->getInstr();
1356       MachineBasicBlock::iterator Pos = MI;
1357       PosOld.push_back(Pos);
1358       if (&*CurrentTopFastSched == MI) {
1359         PosNew.push_back(Pos);
1360         CurrentTopFastSched = nextIfDebug(++CurrentTopFastSched,
1361                                           DAG->getCurrentBottom());
1362       } else {
1363         // Update the instruction stream.
1364         DAG->getBB()->splice(CurrentTopFastSched, DAG->getBB(), MI);
1365 
1366         // Update LiveIntervals.
1367         // Note: Moving all instructions and calling handleMove every time
1368         // is the most cpu intensive operation of the scheduler.
1369         // It would gain a lot if there was a way to recompute the
1370         // LiveIntervals for the entire scheduling region.
1371         DAG->getLIS()->handleMove(*MI, /*UpdateFlags=*/true);
1372         PosNew.push_back(CurrentTopFastSched);
1373       }
1374     }
1375   }
1376 
1377   // Now we have Block of SUs == Block of MI.
1378   // We do the final schedule for the instructions inside the block.
1379   // The property that all the SUs of the Block are grouped together as MI
1380   // is used for correct reg usage tracking.
1381   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1382     SIScheduleBlock *Block = CurrentBlocks[i];
1383     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1384     Block->schedule((*SUs.begin())->getInstr(), (*SUs.rbegin())->getInstr());
1385   }
1386 
1387   LLVM_DEBUG(dbgs() << "Restoring MI Pos\n");
1388   // Restore old ordering (which prevents a LIS->handleMove bug).
1389   for (unsigned i = PosOld.size(), e = 0; i != e; --i) {
1390     MachineBasicBlock::iterator POld = PosOld[i-1];
1391     MachineBasicBlock::iterator PNew = PosNew[i-1];
1392     if (PNew != POld) {
1393       // Update the instruction stream.
1394       DAG->getBB()->splice(POld, DAG->getBB(), PNew);
1395 
1396       // Update LiveIntervals.
1397       DAG->getLIS()->handleMove(*POld, /*UpdateFlags=*/true);
1398     }
1399   }
1400 
1401   LLVM_DEBUG(for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1402     SIScheduleBlock *Block = CurrentBlocks[i];
1403     Block->printDebug(true);
1404   });
1405 }
1406 
1407 void SIScheduleBlockCreator::fillStats() {
1408   unsigned DAGSize = CurrentBlocks.size();
1409 
1410   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1411     int BlockIndice = TopDownIndex2Block[i];
1412     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1413     if (Block->getPreds().empty())
1414       Block->Depth = 0;
1415     else {
1416       unsigned Depth = 0;
1417       for (SIScheduleBlock *Pred : Block->getPreds()) {
1418         if (Depth < Pred->Depth + Pred->getCost())
1419           Depth = Pred->Depth + Pred->getCost();
1420       }
1421       Block->Depth = Depth;
1422     }
1423   }
1424 
1425   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1426     int BlockIndice = BottomUpIndex2Block[i];
1427     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1428     if (Block->getSuccs().empty())
1429       Block->Height = 0;
1430     else {
1431       unsigned Height = 0;
1432       for (const auto &Succ : Block->getSuccs())
1433         Height = std::max(Height, Succ.first->Height + Succ.first->getCost());
1434       Block->Height = Height;
1435     }
1436   }
1437 }
1438 
1439 // SIScheduleBlockScheduler //
1440 
1441 SIScheduleBlockScheduler::SIScheduleBlockScheduler(SIScheduleDAGMI *DAG,
1442                                                    SISchedulerBlockSchedulerVariant Variant,
1443                                                    SIScheduleBlocks  BlocksStruct) :
1444   DAG(DAG), Variant(Variant), Blocks(BlocksStruct.Blocks),
1445   LastPosWaitedHighLatency(0), NumBlockScheduled(0), VregCurrentUsage(0),
1446   SregCurrentUsage(0), maxVregUsage(0), maxSregUsage(0) {
1447 
1448   // Fill the usage of every output
1449   // Warning: while by construction we always have a link between two blocks
1450   // when one needs a result from the other, the number of users of an output
1451   // is not the sum of child blocks having as input the same virtual register.
1452   // Here is an example. A produces x and y. B eats x and produces x'.
1453   // C eats x' and y. The register coalescer may have attributed the same
1454   // virtual register to x and x'.
1455   // To count accurately, we do a topological sort. In case the register is
1456   // found for several parents, we increment the usage of the one with the
1457   // highest topological index.
1458   LiveOutRegsNumUsages.resize(Blocks.size());
1459   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1460     SIScheduleBlock *Block = Blocks[i];
1461     for (unsigned Reg : Block->getInRegs()) {
1462       bool Found = false;
1463       int topoInd = -1;
1464       for (SIScheduleBlock* Pred: Block->getPreds()) {
1465         std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1466         std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1467 
1468         if (RegPos != PredOutRegs.end()) {
1469           Found = true;
1470           if (topoInd < BlocksStruct.TopDownBlock2Index[Pred->getID()]) {
1471             topoInd = BlocksStruct.TopDownBlock2Index[Pred->getID()];
1472           }
1473         }
1474       }
1475 
1476       if (!Found)
1477         continue;
1478 
1479       int PredID = BlocksStruct.TopDownIndex2Block[topoInd];
1480       ++LiveOutRegsNumUsages[PredID][Reg];
1481     }
1482   }
1483 
1484   LastPosHighLatencyParentScheduled.resize(Blocks.size(), 0);
1485   BlockNumPredsLeft.resize(Blocks.size());
1486   BlockNumSuccsLeft.resize(Blocks.size());
1487 
1488   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1489     SIScheduleBlock *Block = Blocks[i];
1490     BlockNumPredsLeft[i] = Block->getPreds().size();
1491     BlockNumSuccsLeft[i] = Block->getSuccs().size();
1492   }
1493 
1494 #ifndef NDEBUG
1495   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1496     SIScheduleBlock *Block = Blocks[i];
1497     assert(Block->getID() == i);
1498   }
1499 #endif
1500 
1501   std::set<unsigned> InRegs = DAG->getInRegs();
1502   addLiveRegs(InRegs);
1503 
1504   // Increase LiveOutRegsNumUsages for blocks
1505   // producing registers consumed in another
1506   // scheduling region.
1507   for (unsigned Reg : DAG->getOutRegs()) {
1508     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1509       // Do reverse traversal
1510       int ID = BlocksStruct.TopDownIndex2Block[Blocks.size()-1-i];
1511       SIScheduleBlock *Block = Blocks[ID];
1512       const std::set<unsigned> &OutRegs = Block->getOutRegs();
1513 
1514       if (OutRegs.find(Reg) == OutRegs.end())
1515         continue;
1516 
1517       ++LiveOutRegsNumUsages[ID][Reg];
1518       break;
1519     }
1520   }
1521 
1522   // Fill LiveRegsConsumers for regs that were already
1523   // defined before scheduling.
1524   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1525     SIScheduleBlock *Block = Blocks[i];
1526     for (unsigned Reg : Block->getInRegs()) {
1527       bool Found = false;
1528       for (SIScheduleBlock* Pred: Block->getPreds()) {
1529         std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1530         std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1531 
1532         if (RegPos != PredOutRegs.end()) {
1533           Found = true;
1534           break;
1535         }
1536       }
1537 
1538       if (!Found)
1539         ++LiveRegsConsumers[Reg];
1540     }
1541   }
1542 
1543   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1544     SIScheduleBlock *Block = Blocks[i];
1545     if (BlockNumPredsLeft[i] == 0) {
1546       ReadyBlocks.push_back(Block);
1547     }
1548   }
1549 
1550   while (SIScheduleBlock *Block = pickBlock()) {
1551     BlocksScheduled.push_back(Block);
1552     blockScheduled(Block);
1553   }
1554 
1555   LLVM_DEBUG(dbgs() << "Block Order:"; for (SIScheduleBlock *Block
1556                                             : BlocksScheduled) {
1557     dbgs() << ' ' << Block->getID();
1558   } dbgs() << '\n';);
1559 }
1560 
1561 bool SIScheduleBlockScheduler::tryCandidateLatency(SIBlockSchedCandidate &Cand,
1562                                                    SIBlockSchedCandidate &TryCand) {
1563   if (!Cand.isValid()) {
1564     TryCand.Reason = NodeOrder;
1565     return true;
1566   }
1567 
1568   // Try to hide high latencies.
1569   if (SISched::tryLess(TryCand.LastPosHighLatParentScheduled,
1570                  Cand.LastPosHighLatParentScheduled, TryCand, Cand, Latency))
1571     return true;
1572   // Schedule high latencies early so you can hide them better.
1573   if (SISched::tryGreater(TryCand.IsHighLatency, Cand.IsHighLatency,
1574                           TryCand, Cand, Latency))
1575     return true;
1576   if (TryCand.IsHighLatency && SISched::tryGreater(TryCand.Height, Cand.Height,
1577                                                    TryCand, Cand, Depth))
1578     return true;
1579   if (SISched::tryGreater(TryCand.NumHighLatencySuccessors,
1580                           Cand.NumHighLatencySuccessors,
1581                           TryCand, Cand, Successor))
1582     return true;
1583   return false;
1584 }
1585 
1586 bool SIScheduleBlockScheduler::tryCandidateRegUsage(SIBlockSchedCandidate &Cand,
1587                                                     SIBlockSchedCandidate &TryCand) {
1588   if (!Cand.isValid()) {
1589     TryCand.Reason = NodeOrder;
1590     return true;
1591   }
1592 
1593   if (SISched::tryLess(TryCand.VGPRUsageDiff > 0, Cand.VGPRUsageDiff > 0,
1594                        TryCand, Cand, RegUsage))
1595     return true;
1596   if (SISched::tryGreater(TryCand.NumSuccessors > 0,
1597                           Cand.NumSuccessors > 0,
1598                           TryCand, Cand, Successor))
1599     return true;
1600   if (SISched::tryGreater(TryCand.Height, Cand.Height, TryCand, Cand, Depth))
1601     return true;
1602   if (SISched::tryLess(TryCand.VGPRUsageDiff, Cand.VGPRUsageDiff,
1603                        TryCand, Cand, RegUsage))
1604     return true;
1605   return false;
1606 }
1607 
1608 SIScheduleBlock *SIScheduleBlockScheduler::pickBlock() {
1609   SIBlockSchedCandidate Cand;
1610   std::vector<SIScheduleBlock*>::iterator Best;
1611   SIScheduleBlock *Block;
1612   if (ReadyBlocks.empty())
1613     return nullptr;
1614 
1615   DAG->fillVgprSgprCost(LiveRegs.begin(), LiveRegs.end(),
1616                         VregCurrentUsage, SregCurrentUsage);
1617   if (VregCurrentUsage > maxVregUsage)
1618     maxVregUsage = VregCurrentUsage;
1619   if (SregCurrentUsage > maxSregUsage)
1620     maxSregUsage = SregCurrentUsage;
1621   LLVM_DEBUG(dbgs() << "Picking New Blocks\n"; dbgs() << "Available: ";
1622              for (SIScheduleBlock *Block
1623                   : ReadyBlocks) dbgs()
1624              << Block->getID() << ' ';
1625              dbgs() << "\nCurrent Live:\n";
1626              for (unsigned Reg
1627                   : LiveRegs) dbgs()
1628              << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
1629              dbgs() << '\n';
1630              dbgs() << "Current VGPRs: " << VregCurrentUsage << '\n';
1631              dbgs() << "Current SGPRs: " << SregCurrentUsage << '\n';);
1632 
1633   Cand.Block = nullptr;
1634   for (std::vector<SIScheduleBlock*>::iterator I = ReadyBlocks.begin(),
1635        E = ReadyBlocks.end(); I != E; ++I) {
1636     SIBlockSchedCandidate TryCand;
1637     TryCand.Block = *I;
1638     TryCand.IsHighLatency = TryCand.Block->isHighLatencyBlock();
1639     TryCand.VGPRUsageDiff =
1640       checkRegUsageImpact(TryCand.Block->getInRegs(),
1641           TryCand.Block->getOutRegs())[AMDGPU::RegisterPressureSets::VGPR_32];
1642     TryCand.NumSuccessors = TryCand.Block->getSuccs().size();
1643     TryCand.NumHighLatencySuccessors =
1644       TryCand.Block->getNumHighLatencySuccessors();
1645     TryCand.LastPosHighLatParentScheduled =
1646       (unsigned int) std::max<int> (0,
1647          LastPosHighLatencyParentScheduled[TryCand.Block->getID()] -
1648            LastPosWaitedHighLatency);
1649     TryCand.Height = TryCand.Block->Height;
1650     // Try not to increase VGPR usage too much, else we may spill.
1651     if (VregCurrentUsage > 120 ||
1652         Variant != SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage) {
1653       if (!tryCandidateRegUsage(Cand, TryCand) &&
1654           Variant != SISchedulerBlockSchedulerVariant::BlockRegUsage)
1655         tryCandidateLatency(Cand, TryCand);
1656     } else {
1657       if (!tryCandidateLatency(Cand, TryCand))
1658         tryCandidateRegUsage(Cand, TryCand);
1659     }
1660     if (TryCand.Reason != NoCand) {
1661       Cand.setBest(TryCand);
1662       Best = I;
1663       LLVM_DEBUG(dbgs() << "Best Current Choice: " << Cand.Block->getID() << ' '
1664                         << getReasonStr(Cand.Reason) << '\n');
1665     }
1666   }
1667 
1668   LLVM_DEBUG(dbgs() << "Picking: " << Cand.Block->getID() << '\n';
1669              dbgs() << "Is a block with high latency instruction: "
1670                     << (Cand.IsHighLatency ? "yes\n" : "no\n");
1671              dbgs() << "Position of last high latency dependency: "
1672                     << Cand.LastPosHighLatParentScheduled << '\n';
1673              dbgs() << "VGPRUsageDiff: " << Cand.VGPRUsageDiff << '\n';
1674              dbgs() << '\n';);
1675 
1676   Block = Cand.Block;
1677   ReadyBlocks.erase(Best);
1678   return Block;
1679 }
1680 
1681 // Tracking of currently alive registers to determine VGPR Usage.
1682 
1683 void SIScheduleBlockScheduler::addLiveRegs(std::set<unsigned> &Regs) {
1684   for (Register Reg : Regs) {
1685     // For now only track virtual registers.
1686     if (!Reg.isVirtual())
1687       continue;
1688     // If not already in the live set, then add it.
1689     (void) LiveRegs.insert(Reg);
1690   }
1691 }
1692 
1693 void SIScheduleBlockScheduler::decreaseLiveRegs(SIScheduleBlock *Block,
1694                                        std::set<unsigned> &Regs) {
1695   for (unsigned Reg : Regs) {
1696     // For now only track virtual registers.
1697     std::set<unsigned>::iterator Pos = LiveRegs.find(Reg);
1698     assert (Pos != LiveRegs.end() && // Reg must be live.
1699                LiveRegsConsumers.find(Reg) != LiveRegsConsumers.end() &&
1700                LiveRegsConsumers[Reg] >= 1);
1701     --LiveRegsConsumers[Reg];
1702     if (LiveRegsConsumers[Reg] == 0)
1703       LiveRegs.erase(Pos);
1704   }
1705 }
1706 
1707 void SIScheduleBlockScheduler::releaseBlockSuccs(SIScheduleBlock *Parent) {
1708   for (const auto &Block : Parent->getSuccs()) {
1709     if (--BlockNumPredsLeft[Block.first->getID()] == 0)
1710       ReadyBlocks.push_back(Block.first);
1711 
1712     if (Parent->isHighLatencyBlock() &&
1713         Block.second == SIScheduleBlockLinkKind::Data)
1714       LastPosHighLatencyParentScheduled[Block.first->getID()] = NumBlockScheduled;
1715   }
1716 }
1717 
1718 void SIScheduleBlockScheduler::blockScheduled(SIScheduleBlock *Block) {
1719   decreaseLiveRegs(Block, Block->getInRegs());
1720   addLiveRegs(Block->getOutRegs());
1721   releaseBlockSuccs(Block);
1722   for (std::map<unsigned, unsigned>::iterator RegI =
1723        LiveOutRegsNumUsages[Block->getID()].begin(),
1724        E = LiveOutRegsNumUsages[Block->getID()].end(); RegI != E; ++RegI) {
1725     std::pair<unsigned, unsigned> RegP = *RegI;
1726     // We produce this register, thus it must not be previously alive.
1727     assert(LiveRegsConsumers.find(RegP.first) == LiveRegsConsumers.end() ||
1728            LiveRegsConsumers[RegP.first] == 0);
1729     LiveRegsConsumers[RegP.first] += RegP.second;
1730   }
1731   if (LastPosHighLatencyParentScheduled[Block->getID()] >
1732         (unsigned)LastPosWaitedHighLatency)
1733     LastPosWaitedHighLatency =
1734       LastPosHighLatencyParentScheduled[Block->getID()];
1735   ++NumBlockScheduled;
1736 }
1737 
1738 std::vector<int>
1739 SIScheduleBlockScheduler::checkRegUsageImpact(std::set<unsigned> &InRegs,
1740                                      std::set<unsigned> &OutRegs) {
1741   std::vector<int> DiffSetPressure;
1742   DiffSetPressure.assign(DAG->getTRI()->getNumRegPressureSets(), 0);
1743 
1744   for (Register Reg : InRegs) {
1745     // For now only track virtual registers.
1746     if (!Reg.isVirtual())
1747       continue;
1748     if (LiveRegsConsumers[Reg] > 1)
1749       continue;
1750     PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1751     for (; PSetI.isValid(); ++PSetI) {
1752       DiffSetPressure[*PSetI] -= PSetI.getWeight();
1753     }
1754   }
1755 
1756   for (Register Reg : OutRegs) {
1757     // For now only track virtual registers.
1758     if (!Reg.isVirtual())
1759       continue;
1760     PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1761     for (; PSetI.isValid(); ++PSetI) {
1762       DiffSetPressure[*PSetI] += PSetI.getWeight();
1763     }
1764   }
1765 
1766   return DiffSetPressure;
1767 }
1768 
1769 // SIScheduler //
1770 
1771 struct SIScheduleBlockResult
1772 SIScheduler::scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant,
1773                              SISchedulerBlockSchedulerVariant ScheduleVariant) {
1774   SIScheduleBlocks Blocks = BlockCreator.getBlocks(BlockVariant);
1775   SIScheduleBlockScheduler Scheduler(DAG, ScheduleVariant, Blocks);
1776   std::vector<SIScheduleBlock*> ScheduledBlocks;
1777   struct SIScheduleBlockResult Res;
1778 
1779   ScheduledBlocks = Scheduler.getBlocks();
1780 
1781   for (unsigned b = 0; b < ScheduledBlocks.size(); ++b) {
1782     SIScheduleBlock *Block = ScheduledBlocks[b];
1783     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1784 
1785     for (SUnit* SU : SUs)
1786       Res.SUs.push_back(SU->NodeNum);
1787   }
1788 
1789   Res.MaxSGPRUsage = Scheduler.getSGPRUsage();
1790   Res.MaxVGPRUsage = Scheduler.getVGPRUsage();
1791   return Res;
1792 }
1793 
1794 // SIScheduleDAGMI //
1795 
1796 SIScheduleDAGMI::SIScheduleDAGMI(MachineSchedContext *C) :
1797   ScheduleDAGMILive(C, std::make_unique<GenericScheduler>(C)) {
1798   SITII = static_cast<const SIInstrInfo*>(TII);
1799   SITRI = static_cast<const SIRegisterInfo*>(TRI);
1800 }
1801 
1802 SIScheduleDAGMI::~SIScheduleDAGMI() = default;
1803 
1804 // Code adapted from scheduleDAG.cpp
1805 // Does a topological sort over the SUs.
1806 // Both TopDown and BottomUp
1807 void SIScheduleDAGMI::topologicalSort() {
1808   Topo.InitDAGTopologicalSorting();
1809 
1810   TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());
1811   BottomUpIndex2SU = std::vector<int>(Topo.rbegin(), Topo.rend());
1812 }
1813 
1814 // Move low latencies further from their user without
1815 // increasing SGPR usage (in general)
1816 // This is to be replaced by a better pass that would
1817 // take into account SGPR usage (based on VGPR Usage
1818 // and the corresponding wavefront count), that would
1819 // try to merge groups of loads if it make sense, etc
1820 void SIScheduleDAGMI::moveLowLatencies() {
1821    unsigned DAGSize = SUnits.size();
1822    int LastLowLatencyUser = -1;
1823    int LastLowLatencyPos = -1;
1824 
1825    for (unsigned i = 0, e = ScheduledSUnits.size(); i != e; ++i) {
1826     SUnit *SU = &SUnits[ScheduledSUnits[i]];
1827     bool IsLowLatencyUser = false;
1828     unsigned MinPos = 0;
1829 
1830     for (SDep& PredDep : SU->Preds) {
1831       SUnit *Pred = PredDep.getSUnit();
1832       if (SITII->isLowLatencyInstruction(*Pred->getInstr())) {
1833         IsLowLatencyUser = true;
1834       }
1835       if (Pred->NodeNum >= DAGSize)
1836         continue;
1837       unsigned PredPos = ScheduledSUnitsInv[Pred->NodeNum];
1838       if (PredPos >= MinPos)
1839         MinPos = PredPos + 1;
1840     }
1841 
1842     if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
1843       unsigned BestPos = LastLowLatencyUser + 1;
1844       if ((int)BestPos <= LastLowLatencyPos)
1845         BestPos = LastLowLatencyPos + 1;
1846       if (BestPos < MinPos)
1847         BestPos = MinPos;
1848       if (BestPos < i) {
1849         for (unsigned u = i; u > BestPos; --u) {
1850           ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1851           ScheduledSUnits[u] = ScheduledSUnits[u-1];
1852         }
1853         ScheduledSUnits[BestPos] = SU->NodeNum;
1854         ScheduledSUnitsInv[SU->NodeNum] = BestPos;
1855       }
1856       LastLowLatencyPos = BestPos;
1857       if (IsLowLatencyUser)
1858         LastLowLatencyUser = BestPos;
1859     } else if (IsLowLatencyUser) {
1860       LastLowLatencyUser = i;
1861     // Moves COPY instructions on which depends
1862     // the low latency instructions too.
1863     } else if (SU->getInstr()->getOpcode() == AMDGPU::COPY) {
1864       bool CopyForLowLat = false;
1865       for (SDep& SuccDep : SU->Succs) {
1866         SUnit *Succ = SuccDep.getSUnit();
1867         if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1868           continue;
1869         if (SITII->isLowLatencyInstruction(*Succ->getInstr())) {
1870           CopyForLowLat = true;
1871         }
1872       }
1873       if (!CopyForLowLat)
1874         continue;
1875       if (MinPos < i) {
1876         for (unsigned u = i; u > MinPos; --u) {
1877           ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1878           ScheduledSUnits[u] = ScheduledSUnits[u-1];
1879         }
1880         ScheduledSUnits[MinPos] = SU->NodeNum;
1881         ScheduledSUnitsInv[SU->NodeNum] = MinPos;
1882       }
1883     }
1884   }
1885 }
1886 
1887 void SIScheduleDAGMI::restoreSULinksLeft() {
1888   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1889     SUnits[i].isScheduled = false;
1890     SUnits[i].WeakPredsLeft = SUnitsLinksBackup[i].WeakPredsLeft;
1891     SUnits[i].NumPredsLeft = SUnitsLinksBackup[i].NumPredsLeft;
1892     SUnits[i].WeakSuccsLeft = SUnitsLinksBackup[i].WeakSuccsLeft;
1893     SUnits[i].NumSuccsLeft = SUnitsLinksBackup[i].NumSuccsLeft;
1894   }
1895 }
1896 
1897 // Return the Vgpr and Sgpr usage corresponding to some virtual registers.
1898 template<typename _Iterator> void
1899 SIScheduleDAGMI::fillVgprSgprCost(_Iterator First, _Iterator End,
1900                                   unsigned &VgprUsage, unsigned &SgprUsage) {
1901   VgprUsage = 0;
1902   SgprUsage = 0;
1903   for (_Iterator RegI = First; RegI != End; ++RegI) {
1904     Register Reg = *RegI;
1905     // For now only track virtual registers
1906     if (!Reg.isVirtual())
1907       continue;
1908     PSetIterator PSetI = MRI.getPressureSets(Reg);
1909     for (; PSetI.isValid(); ++PSetI) {
1910       if (*PSetI == AMDGPU::RegisterPressureSets::VGPR_32)
1911         VgprUsage += PSetI.getWeight();
1912       else if (*PSetI == AMDGPU::RegisterPressureSets::SReg_32)
1913         SgprUsage += PSetI.getWeight();
1914     }
1915   }
1916 }
1917 
1918 void SIScheduleDAGMI::schedule()
1919 {
1920   SmallVector<SUnit*, 8> TopRoots, BotRoots;
1921   SIScheduleBlockResult Best, Temp;
1922   LLVM_DEBUG(dbgs() << "Preparing Scheduling\n");
1923 
1924   buildDAGWithRegPressure();
1925   LLVM_DEBUG(dump());
1926 
1927   topologicalSort();
1928   findRootsAndBiasEdges(TopRoots, BotRoots);
1929   // We reuse several ScheduleDAGMI and ScheduleDAGMILive
1930   // functions, but to make them happy we must initialize
1931   // the default Scheduler implementation (even if we do not
1932   // run it)
1933   SchedImpl->initialize(this);
1934   initQueues(TopRoots, BotRoots);
1935 
1936   // Fill some stats to help scheduling.
1937 
1938   SUnitsLinksBackup = SUnits;
1939   IsLowLatencySU.clear();
1940   LowLatencyOffset.clear();
1941   IsHighLatencySU.clear();
1942 
1943   IsLowLatencySU.resize(SUnits.size(), 0);
1944   LowLatencyOffset.resize(SUnits.size(), 0);
1945   IsHighLatencySU.resize(SUnits.size(), 0);
1946 
1947   for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
1948     SUnit *SU = &SUnits[i];
1949     const MachineOperand *BaseLatOp;
1950     int64_t OffLatReg;
1951     if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
1952       IsLowLatencySU[i] = 1;
1953       bool OffsetIsScalable;
1954       if (SITII->getMemOperandWithOffset(*SU->getInstr(), BaseLatOp, OffLatReg,
1955                                          OffsetIsScalable, TRI))
1956         LowLatencyOffset[i] = OffLatReg;
1957     } else if (SITII->isHighLatencyDef(SU->getInstr()->getOpcode()))
1958       IsHighLatencySU[i] = 1;
1959   }
1960 
1961   SIScheduler Scheduler(this);
1962   Best = Scheduler.scheduleVariant(SISchedulerBlockCreatorVariant::LatenciesAlone,
1963                                    SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage);
1964 
1965   // if VGPR usage is extremely high, try other good performing variants
1966   // which could lead to lower VGPR usage
1967   if (Best.MaxVGPRUsage > 180) {
1968     static const std::pair<SISchedulerBlockCreatorVariant,
1969                            SISchedulerBlockSchedulerVariant>
1970         Variants[] = {
1971       { LatenciesAlone, BlockRegUsageLatency },
1972 //      { LatenciesAlone, BlockRegUsage },
1973       { LatenciesGrouped, BlockLatencyRegUsage },
1974 //      { LatenciesGrouped, BlockRegUsageLatency },
1975 //      { LatenciesGrouped, BlockRegUsage },
1976       { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1977 //      { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1978 //      { LatenciesAlonePlusConsecutive, BlockRegUsage }
1979     };
1980     for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1981       Temp = Scheduler.scheduleVariant(v.first, v.second);
1982       if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
1983         Best = Temp;
1984     }
1985   }
1986   // if VGPR usage is still extremely high, we may spill. Try other variants
1987   // which are less performing, but that could lead to lower VGPR usage.
1988   if (Best.MaxVGPRUsage > 200) {
1989     static const std::pair<SISchedulerBlockCreatorVariant,
1990                            SISchedulerBlockSchedulerVariant>
1991         Variants[] = {
1992 //      { LatenciesAlone, BlockRegUsageLatency },
1993       { LatenciesAlone, BlockRegUsage },
1994 //      { LatenciesGrouped, BlockLatencyRegUsage },
1995       { LatenciesGrouped, BlockRegUsageLatency },
1996       { LatenciesGrouped, BlockRegUsage },
1997 //      { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1998       { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1999       { LatenciesAlonePlusConsecutive, BlockRegUsage }
2000     };
2001     for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
2002       Temp = Scheduler.scheduleVariant(v.first, v.second);
2003       if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
2004         Best = Temp;
2005     }
2006   }
2007 
2008   ScheduledSUnits = Best.SUs;
2009   ScheduledSUnitsInv.resize(SUnits.size());
2010 
2011   for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
2012     ScheduledSUnitsInv[ScheduledSUnits[i]] = i;
2013   }
2014 
2015   moveLowLatencies();
2016 
2017   // Tell the outside world about the result of the scheduling.
2018 
2019   assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
2020   TopRPTracker.setPos(CurrentTop);
2021 
2022   for (std::vector<unsigned>::iterator I = ScheduledSUnits.begin(),
2023        E = ScheduledSUnits.end(); I != E; ++I) {
2024     SUnit *SU = &SUnits[*I];
2025 
2026     scheduleMI(SU, true);
2027 
2028     LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
2029                       << *SU->getInstr());
2030   }
2031 
2032   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
2033 
2034   placeDebugValues();
2035 
2036   LLVM_DEBUG({
2037     dbgs() << "*** Final schedule for "
2038            << printMBBReference(*begin()->getParent()) << " ***\n";
2039     dumpSchedule();
2040     dbgs() << '\n';
2041   });
2042 }
2043