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[DAG->getSGPRSetID()];
273     TryCand.VGPRUsage = pressure[DAG->getVGPRSetID()];
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     unsigned Reg = RegMaskPair.RegUnit;
379     if (Register::isVirtualRegister(Reg) &&
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 " << LiveInPressure[DAG->getSGPRSetID()] << ' '
599            << LiveInPressure[DAG->getVGPRSetID()] << '\n';
600     dbgs() << "LiveOutPressure " << LiveOutPressure[DAG->getSGPRSetID()] << ' '
601            << LiveOutPressure[DAG->getVGPRSetID()] << "\n\n";
602     dbgs() << "LiveIns:\n";
603     for (unsigned Reg : LiveInRegs)
604       dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
605 
606     dbgs() << "\nLiveOuts:\n";
607     for (unsigned Reg : LiveOutRegs)
608       dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
609   }
610 
611   dbgs() << "\nInstructions:\n";
612   for (const SUnit* SU : SUnits)
613       DAG->dumpNode(*SU);
614 
615   dbgs() << "///////////////////////\n";
616 }
617 #endif
618 
619 // SIScheduleBlockCreator //
620 
621 SIScheduleBlockCreator::SIScheduleBlockCreator(SIScheduleDAGMI *DAG) :
622 DAG(DAG) {
623 }
624 
625 SIScheduleBlockCreator::~SIScheduleBlockCreator() = default;
626 
627 SIScheduleBlocks
628 SIScheduleBlockCreator::getBlocks(SISchedulerBlockCreatorVariant BlockVariant) {
629   std::map<SISchedulerBlockCreatorVariant, SIScheduleBlocks>::iterator B =
630     Blocks.find(BlockVariant);
631   if (B == Blocks.end()) {
632     SIScheduleBlocks Res;
633     createBlocksForVariant(BlockVariant);
634     topologicalSort();
635     scheduleInsideBlocks();
636     fillStats();
637     Res.Blocks = CurrentBlocks;
638     Res.TopDownIndex2Block = TopDownIndex2Block;
639     Res.TopDownBlock2Index = TopDownBlock2Index;
640     Blocks[BlockVariant] = Res;
641     return Res;
642   } else {
643     return B->second;
644   }
645 }
646 
647 bool SIScheduleBlockCreator::isSUInBlock(SUnit *SU, unsigned ID) {
648   if (SU->NodeNum >= DAG->SUnits.size())
649     return false;
650   return CurrentBlocks[Node2CurrentBlock[SU->NodeNum]]->getID() == ID;
651 }
652 
653 void SIScheduleBlockCreator::colorHighLatenciesAlone() {
654   unsigned DAGSize = DAG->SUnits.size();
655 
656   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
657     SUnit *SU = &DAG->SUnits[i];
658     if (DAG->IsHighLatencySU[SU->NodeNum]) {
659       CurrentColoring[SU->NodeNum] = NextReservedID++;
660     }
661   }
662 }
663 
664 static bool
665 hasDataDependencyPred(const SUnit &SU, const SUnit &FromSU) {
666   for (const auto &PredDep : SU.Preds) {
667     if (PredDep.getSUnit() == &FromSU &&
668         PredDep.getKind() == llvm::SDep::Data)
669       return true;
670   }
671   return false;
672 }
673 
674 void SIScheduleBlockCreator::colorHighLatenciesGroups() {
675   unsigned DAGSize = DAG->SUnits.size();
676   unsigned NumHighLatencies = 0;
677   unsigned GroupSize;
678   int Color = NextReservedID;
679   unsigned Count = 0;
680   std::set<unsigned> FormingGroup;
681 
682   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
683     SUnit *SU = &DAG->SUnits[i];
684     if (DAG->IsHighLatencySU[SU->NodeNum])
685       ++NumHighLatencies;
686   }
687 
688   if (NumHighLatencies == 0)
689     return;
690 
691   if (NumHighLatencies <= 6)
692     GroupSize = 2;
693   else if (NumHighLatencies <= 12)
694     GroupSize = 3;
695   else
696     GroupSize = 4;
697 
698   for (unsigned SUNum : DAG->TopDownIndex2SU) {
699     const SUnit &SU = DAG->SUnits[SUNum];
700     if (DAG->IsHighLatencySU[SU.NodeNum]) {
701       unsigned CompatibleGroup = true;
702       int ProposedColor = Color;
703       std::vector<int> AdditionalElements;
704 
705       // We don't want to put in the same block
706       // two high latency instructions that depend
707       // on each other.
708       // One way would be to check canAddEdge
709       // in both directions, but that currently is not
710       // enough because there the high latency order is
711       // enforced (via links).
712       // Instead, look at the dependencies between the
713       // high latency instructions and deduce if it is
714       // a data dependency or not.
715       for (unsigned j : FormingGroup) {
716         bool HasSubGraph;
717         std::vector<int> SubGraph;
718         // By construction (topological order), if SU and
719         // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary
720         // in the parent graph of SU.
721 #ifndef NDEBUG
722         SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j],
723                                                HasSubGraph);
724         assert(!HasSubGraph);
725 #endif
726         SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU,
727                                                HasSubGraph);
728         if (!HasSubGraph)
729           continue; // No dependencies between each other
730         else if (SubGraph.size() > 5) {
731           // Too many elements would be required to be added to the block.
732           CompatibleGroup = false;
733           break;
734         }
735         else {
736           // Check the type of dependency
737           for (unsigned k : SubGraph) {
738             // If in the path to join the two instructions,
739             // there is another high latency instruction,
740             // or instructions colored for another block
741             // abort the merge.
742             if (DAG->IsHighLatencySU[k] ||
743                 (CurrentColoring[k] != ProposedColor &&
744                  CurrentColoring[k] != 0)) {
745               CompatibleGroup = false;
746               break;
747             }
748             // If one of the SU in the subgraph depends on the result of SU j,
749             // there'll be a data dependency.
750             if (hasDataDependencyPred(DAG->SUnits[k], DAG->SUnits[j])) {
751               CompatibleGroup = false;
752               break;
753             }
754           }
755           if (!CompatibleGroup)
756             break;
757           // Same check for the SU
758           if (hasDataDependencyPred(SU, DAG->SUnits[j])) {
759             CompatibleGroup = false;
760             break;
761           }
762           // Add all the required instructions to the block
763           // These cannot live in another block (because they
764           // depend (order dependency) on one of the
765           // instruction in the block, and are required for the
766           // high latency instruction we add.
767           AdditionalElements.insert(AdditionalElements.end(),
768                                     SubGraph.begin(), SubGraph.end());
769         }
770       }
771       if (CompatibleGroup) {
772         FormingGroup.insert(SU.NodeNum);
773         for (unsigned j : AdditionalElements)
774           CurrentColoring[j] = ProposedColor;
775         CurrentColoring[SU.NodeNum] = ProposedColor;
776         ++Count;
777       }
778       // Found one incompatible instruction,
779       // or has filled a big enough group.
780       // -> start a new one.
781       if (!CompatibleGroup) {
782         FormingGroup.clear();
783         Color = ++NextReservedID;
784         ProposedColor = Color;
785         FormingGroup.insert(SU.NodeNum);
786         CurrentColoring[SU.NodeNum] = ProposedColor;
787         Count = 0;
788       } else if (Count == GroupSize) {
789         FormingGroup.clear();
790         Color = ++NextReservedID;
791         ProposedColor = Color;
792         Count = 0;
793       }
794     }
795   }
796 }
797 
798 void SIScheduleBlockCreator::colorComputeReservedDependencies() {
799   unsigned DAGSize = DAG->SUnits.size();
800   std::map<std::set<unsigned>, unsigned> ColorCombinations;
801 
802   CurrentTopDownReservedDependencyColoring.clear();
803   CurrentBottomUpReservedDependencyColoring.clear();
804 
805   CurrentTopDownReservedDependencyColoring.resize(DAGSize, 0);
806   CurrentBottomUpReservedDependencyColoring.resize(DAGSize, 0);
807 
808   // Traverse TopDown, and give different colors to SUs depending
809   // on which combination of High Latencies they depend on.
810 
811   for (unsigned SUNum : DAG->TopDownIndex2SU) {
812     SUnit *SU = &DAG->SUnits[SUNum];
813     std::set<unsigned> SUColors;
814 
815     // Already given.
816     if (CurrentColoring[SU->NodeNum]) {
817       CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
818         CurrentColoring[SU->NodeNum];
819       continue;
820     }
821 
822    for (SDep& PredDep : SU->Preds) {
823       SUnit *Pred = PredDep.getSUnit();
824       if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
825         continue;
826       if (CurrentTopDownReservedDependencyColoring[Pred->NodeNum] > 0)
827         SUColors.insert(CurrentTopDownReservedDependencyColoring[Pred->NodeNum]);
828     }
829     // Color 0 by default.
830     if (SUColors.empty())
831       continue;
832     // Same color than parents.
833     if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
834       CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
835         *SUColors.begin();
836     else {
837       std::map<std::set<unsigned>, unsigned>::iterator Pos =
838         ColorCombinations.find(SUColors);
839       if (Pos != ColorCombinations.end()) {
840           CurrentTopDownReservedDependencyColoring[SU->NodeNum] = Pos->second;
841       } else {
842         CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
843           NextNonReservedID;
844         ColorCombinations[SUColors] = NextNonReservedID++;
845       }
846     }
847   }
848 
849   ColorCombinations.clear();
850 
851   // Same as before, but BottomUp.
852 
853   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
854     SUnit *SU = &DAG->SUnits[SUNum];
855     std::set<unsigned> SUColors;
856 
857     // Already given.
858     if (CurrentColoring[SU->NodeNum]) {
859       CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
860         CurrentColoring[SU->NodeNum];
861       continue;
862     }
863 
864     for (SDep& SuccDep : SU->Succs) {
865       SUnit *Succ = SuccDep.getSUnit();
866       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
867         continue;
868       if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0)
869         SUColors.insert(CurrentBottomUpReservedDependencyColoring[Succ->NodeNum]);
870     }
871     // Keep color 0.
872     if (SUColors.empty())
873       continue;
874     // Same color than parents.
875     if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
876       CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
877         *SUColors.begin();
878     else {
879       std::map<std::set<unsigned>, unsigned>::iterator Pos =
880         ColorCombinations.find(SUColors);
881       if (Pos != ColorCombinations.end()) {
882         CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = Pos->second;
883       } else {
884         CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
885           NextNonReservedID;
886         ColorCombinations[SUColors] = NextNonReservedID++;
887       }
888     }
889   }
890 }
891 
892 void SIScheduleBlockCreator::colorAccordingToReservedDependencies() {
893   unsigned DAGSize = DAG->SUnits.size();
894   std::map<std::pair<unsigned, unsigned>, unsigned> ColorCombinations;
895 
896   // Every combination of colors given by the top down
897   // and bottom up Reserved node dependency
898 
899   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
900     SUnit *SU = &DAG->SUnits[i];
901     std::pair<unsigned, unsigned> SUColors;
902 
903     // High latency instructions: already given.
904     if (CurrentColoring[SU->NodeNum])
905       continue;
906 
907     SUColors.first = CurrentTopDownReservedDependencyColoring[SU->NodeNum];
908     SUColors.second = CurrentBottomUpReservedDependencyColoring[SU->NodeNum];
909 
910     std::map<std::pair<unsigned, unsigned>, unsigned>::iterator Pos =
911       ColorCombinations.find(SUColors);
912     if (Pos != ColorCombinations.end()) {
913       CurrentColoring[SU->NodeNum] = Pos->second;
914     } else {
915       CurrentColoring[SU->NodeNum] = NextNonReservedID;
916       ColorCombinations[SUColors] = NextNonReservedID++;
917     }
918   }
919 }
920 
921 void SIScheduleBlockCreator::colorEndsAccordingToDependencies() {
922   unsigned DAGSize = DAG->SUnits.size();
923   std::vector<int> PendingColoring = CurrentColoring;
924 
925   assert(DAGSize >= 1 &&
926          CurrentBottomUpReservedDependencyColoring.size() == DAGSize &&
927          CurrentTopDownReservedDependencyColoring.size() == DAGSize);
928   // If there is no reserved block at all, do nothing. We don't want
929   // everything in one block.
930   if (*std::max_element(CurrentBottomUpReservedDependencyColoring.begin(),
931                         CurrentBottomUpReservedDependencyColoring.end()) == 0 &&
932       *std::max_element(CurrentTopDownReservedDependencyColoring.begin(),
933                         CurrentTopDownReservedDependencyColoring.end()) == 0)
934     return;
935 
936   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
937     SUnit *SU = &DAG->SUnits[SUNum];
938     std::set<unsigned> SUColors;
939     std::set<unsigned> SUColorsPending;
940 
941     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
942       continue;
943 
944     if (CurrentBottomUpReservedDependencyColoring[SU->NodeNum] > 0 ||
945         CurrentTopDownReservedDependencyColoring[SU->NodeNum] > 0)
946       continue;
947 
948     for (SDep& SuccDep : SU->Succs) {
949       SUnit *Succ = SuccDep.getSUnit();
950       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
951         continue;
952       if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0 ||
953           CurrentTopDownReservedDependencyColoring[Succ->NodeNum] > 0)
954         SUColors.insert(CurrentColoring[Succ->NodeNum]);
955       SUColorsPending.insert(PendingColoring[Succ->NodeNum]);
956     }
957     // If there is only one child/parent block, and that block
958     // is not among the ones we are removing in this path, then
959     // merge the instruction to that block
960     if (SUColors.size() == 1 && SUColorsPending.size() == 1)
961       PendingColoring[SU->NodeNum] = *SUColors.begin();
962     else // TODO: Attribute new colors depending on color
963          // combination of children.
964       PendingColoring[SU->NodeNum] = NextNonReservedID++;
965   }
966   CurrentColoring = PendingColoring;
967 }
968 
969 
970 void SIScheduleBlockCreator::colorForceConsecutiveOrderInGroup() {
971   unsigned DAGSize = DAG->SUnits.size();
972   unsigned PreviousColor;
973   std::set<unsigned> SeenColors;
974 
975   if (DAGSize <= 1)
976     return;
977 
978   PreviousColor = CurrentColoring[0];
979 
980   for (unsigned i = 1, e = DAGSize; i != e; ++i) {
981     SUnit *SU = &DAG->SUnits[i];
982     unsigned CurrentColor = CurrentColoring[i];
983     unsigned PreviousColorSave = PreviousColor;
984     assert(i == SU->NodeNum);
985 
986     if (CurrentColor != PreviousColor)
987       SeenColors.insert(PreviousColor);
988     PreviousColor = CurrentColor;
989 
990     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
991       continue;
992 
993     if (SeenColors.find(CurrentColor) == SeenColors.end())
994       continue;
995 
996     if (PreviousColorSave != CurrentColor)
997       CurrentColoring[i] = NextNonReservedID++;
998     else
999       CurrentColoring[i] = CurrentColoring[i-1];
1000   }
1001 }
1002 
1003 void SIScheduleBlockCreator::colorMergeConstantLoadsNextGroup() {
1004   unsigned DAGSize = DAG->SUnits.size();
1005 
1006   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1007     SUnit *SU = &DAG->SUnits[SUNum];
1008     std::set<unsigned> SUColors;
1009 
1010     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1011       continue;
1012 
1013     // No predecessor: Vgpr constant loading.
1014     // Low latency instructions usually have a predecessor (the address)
1015     if (SU->Preds.size() > 0 && !DAG->IsLowLatencySU[SU->NodeNum])
1016       continue;
1017 
1018     for (SDep& SuccDep : SU->Succs) {
1019       SUnit *Succ = SuccDep.getSUnit();
1020       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1021         continue;
1022       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1023     }
1024     if (SUColors.size() == 1)
1025       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1026   }
1027 }
1028 
1029 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroup() {
1030   unsigned DAGSize = DAG->SUnits.size();
1031 
1032   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1033     SUnit *SU = &DAG->SUnits[SUNum];
1034     std::set<unsigned> SUColors;
1035 
1036     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1037       continue;
1038 
1039     for (SDep& SuccDep : SU->Succs) {
1040        SUnit *Succ = SuccDep.getSUnit();
1041       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1042         continue;
1043       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1044     }
1045     if (SUColors.size() == 1)
1046       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1047   }
1048 }
1049 
1050 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroupOnlyForReserved() {
1051   unsigned DAGSize = DAG->SUnits.size();
1052 
1053   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1054     SUnit *SU = &DAG->SUnits[SUNum];
1055     std::set<unsigned> SUColors;
1056 
1057     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1058       continue;
1059 
1060     for (SDep& SuccDep : SU->Succs) {
1061        SUnit *Succ = SuccDep.getSUnit();
1062       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1063         continue;
1064       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1065     }
1066     if (SUColors.size() == 1 && *SUColors.begin() <= DAGSize)
1067       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1068   }
1069 }
1070 
1071 void SIScheduleBlockCreator::colorMergeIfPossibleSmallGroupsToNextGroup() {
1072   unsigned DAGSize = DAG->SUnits.size();
1073   std::map<unsigned, unsigned> ColorCount;
1074 
1075   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1076     SUnit *SU = &DAG->SUnits[SUNum];
1077     unsigned color = CurrentColoring[SU->NodeNum];
1078      ++ColorCount[color];
1079   }
1080 
1081   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1082     SUnit *SU = &DAG->SUnits[SUNum];
1083     unsigned color = CurrentColoring[SU->NodeNum];
1084     std::set<unsigned> SUColors;
1085 
1086     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1087       continue;
1088 
1089     if (ColorCount[color] > 1)
1090       continue;
1091 
1092     for (SDep& SuccDep : SU->Succs) {
1093        SUnit *Succ = SuccDep.getSUnit();
1094       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1095         continue;
1096       SUColors.insert(CurrentColoring[Succ->NodeNum]);
1097     }
1098     if (SUColors.size() == 1 && *SUColors.begin() != color) {
1099       --ColorCount[color];
1100       CurrentColoring[SU->NodeNum] = *SUColors.begin();
1101       ++ColorCount[*SUColors.begin()];
1102     }
1103   }
1104 }
1105 
1106 void SIScheduleBlockCreator::cutHugeBlocks() {
1107   // TODO
1108 }
1109 
1110 void SIScheduleBlockCreator::regroupNoUserInstructions() {
1111   unsigned DAGSize = DAG->SUnits.size();
1112   int GroupID = NextNonReservedID++;
1113 
1114   for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1115     SUnit *SU = &DAG->SUnits[SUNum];
1116     bool hasSuccessor = false;
1117 
1118     if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1119       continue;
1120 
1121     for (SDep& SuccDep : SU->Succs) {
1122        SUnit *Succ = SuccDep.getSUnit();
1123       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1124         continue;
1125       hasSuccessor = true;
1126     }
1127     if (!hasSuccessor)
1128       CurrentColoring[SU->NodeNum] = GroupID;
1129   }
1130 }
1131 
1132 void SIScheduleBlockCreator::colorExports() {
1133   unsigned ExportColor = NextNonReservedID++;
1134   SmallVector<unsigned, 8> ExpGroup;
1135 
1136   // Put all exports together in a block.
1137   // The block will naturally end up being scheduled last,
1138   // thus putting exports at the end of the schedule, which
1139   // is better for performance.
1140   // However we must ensure, for safety, the exports can be put
1141   // together in the same block without any other instruction.
1142   // This could happen, for example, when scheduling after regalloc
1143   // if reloading a spilled register from memory using the same
1144   // register than used in a previous export.
1145   // If that happens, do not regroup the exports.
1146   for (unsigned SUNum : DAG->TopDownIndex2SU) {
1147     const SUnit &SU = DAG->SUnits[SUNum];
1148     if (SIInstrInfo::isEXP(*SU.getInstr())) {
1149       // Check the EXP can be added to the group safely,
1150       // ie without needing any other instruction.
1151       // The EXP is allowed to depend on other EXP
1152       // (they will be in the same group).
1153       for (unsigned j : ExpGroup) {
1154         bool HasSubGraph;
1155         std::vector<int> SubGraph;
1156         // By construction (topological order), if SU and
1157         // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary
1158         // in the parent graph of SU.
1159 #ifndef NDEBUG
1160         SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j],
1161                                                HasSubGraph);
1162         assert(!HasSubGraph);
1163 #endif
1164         SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU,
1165                                                HasSubGraph);
1166         if (!HasSubGraph)
1167           continue; // No dependencies between each other
1168 
1169         // SubGraph contains all the instructions required
1170         // between EXP SUnits[j] and EXP SU.
1171         for (unsigned k : SubGraph) {
1172           if (!SIInstrInfo::isEXP(*DAG->SUnits[k].getInstr()))
1173             // Other instructions than EXP would be required in the group.
1174             // Abort the groupping.
1175             return;
1176         }
1177       }
1178 
1179       ExpGroup.push_back(SUNum);
1180     }
1181   }
1182 
1183   // The group can be formed. Give the color.
1184   for (unsigned j : ExpGroup)
1185     CurrentColoring[j] = ExportColor;
1186 }
1187 
1188 void SIScheduleBlockCreator::createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant) {
1189   unsigned DAGSize = DAG->SUnits.size();
1190   std::map<unsigned,unsigned> RealID;
1191 
1192   CurrentBlocks.clear();
1193   CurrentColoring.clear();
1194   CurrentColoring.resize(DAGSize, 0);
1195   Node2CurrentBlock.clear();
1196 
1197   // Restore links previous scheduling variant has overridden.
1198   DAG->restoreSULinksLeft();
1199 
1200   NextReservedID = 1;
1201   NextNonReservedID = DAGSize + 1;
1202 
1203   LLVM_DEBUG(dbgs() << "Coloring the graph\n");
1204 
1205   if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesGrouped)
1206     colorHighLatenciesGroups();
1207   else
1208     colorHighLatenciesAlone();
1209   colorComputeReservedDependencies();
1210   colorAccordingToReservedDependencies();
1211   colorEndsAccordingToDependencies();
1212   if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesAlonePlusConsecutive)
1213     colorForceConsecutiveOrderInGroup();
1214   regroupNoUserInstructions();
1215   colorMergeConstantLoadsNextGroup();
1216   colorMergeIfPossibleNextGroupOnlyForReserved();
1217   colorExports();
1218 
1219   // Put SUs of same color into same block
1220   Node2CurrentBlock.resize(DAGSize, -1);
1221   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1222     SUnit *SU = &DAG->SUnits[i];
1223     unsigned Color = CurrentColoring[SU->NodeNum];
1224     if (RealID.find(Color) == RealID.end()) {
1225       int ID = CurrentBlocks.size();
1226       BlockPtrs.push_back(std::make_unique<SIScheduleBlock>(DAG, this, ID));
1227       CurrentBlocks.push_back(BlockPtrs.rbegin()->get());
1228       RealID[Color] = ID;
1229     }
1230     CurrentBlocks[RealID[Color]]->addUnit(SU);
1231     Node2CurrentBlock[SU->NodeNum] = RealID[Color];
1232   }
1233 
1234   // Build dependencies between blocks.
1235   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1236     SUnit *SU = &DAG->SUnits[i];
1237     int SUID = Node2CurrentBlock[i];
1238      for (SDep& SuccDep : SU->Succs) {
1239        SUnit *Succ = SuccDep.getSUnit();
1240       if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1241         continue;
1242       if (Node2CurrentBlock[Succ->NodeNum] != SUID)
1243         CurrentBlocks[SUID]->addSucc(CurrentBlocks[Node2CurrentBlock[Succ->NodeNum]],
1244                                      SuccDep.isCtrl() ? NoData : Data);
1245     }
1246     for (SDep& PredDep : SU->Preds) {
1247       SUnit *Pred = PredDep.getSUnit();
1248       if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
1249         continue;
1250       if (Node2CurrentBlock[Pred->NodeNum] != SUID)
1251         CurrentBlocks[SUID]->addPred(CurrentBlocks[Node2CurrentBlock[Pred->NodeNum]]);
1252     }
1253   }
1254 
1255   // Free root and leafs of all blocks to enable scheduling inside them.
1256   for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1257     SIScheduleBlock *Block = CurrentBlocks[i];
1258     Block->finalizeUnits();
1259   }
1260   LLVM_DEBUG(dbgs() << "Blocks created:\n\n";
1261              for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1262                SIScheduleBlock *Block = CurrentBlocks[i];
1263                Block->printDebug(true);
1264              });
1265 }
1266 
1267 // Two functions taken from Codegen/MachineScheduler.cpp
1268 
1269 /// Non-const version.
1270 static MachineBasicBlock::iterator
1271 nextIfDebug(MachineBasicBlock::iterator I,
1272             MachineBasicBlock::const_iterator End) {
1273   for (; I != End; ++I) {
1274     if (!I->isDebugInstr())
1275       break;
1276   }
1277   return I;
1278 }
1279 
1280 void SIScheduleBlockCreator::topologicalSort() {
1281   unsigned DAGSize = CurrentBlocks.size();
1282   std::vector<int> WorkList;
1283 
1284   LLVM_DEBUG(dbgs() << "Topological Sort\n");
1285 
1286   WorkList.reserve(DAGSize);
1287   TopDownIndex2Block.resize(DAGSize);
1288   TopDownBlock2Index.resize(DAGSize);
1289   BottomUpIndex2Block.resize(DAGSize);
1290 
1291   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1292     SIScheduleBlock *Block = CurrentBlocks[i];
1293     unsigned Degree = Block->getSuccs().size();
1294     TopDownBlock2Index[i] = Degree;
1295     if (Degree == 0) {
1296       WorkList.push_back(i);
1297     }
1298   }
1299 
1300   int Id = DAGSize;
1301   while (!WorkList.empty()) {
1302     int i = WorkList.back();
1303     SIScheduleBlock *Block = CurrentBlocks[i];
1304     WorkList.pop_back();
1305     TopDownBlock2Index[i] = --Id;
1306     TopDownIndex2Block[Id] = i;
1307     for (SIScheduleBlock* Pred : Block->getPreds()) {
1308       if (!--TopDownBlock2Index[Pred->getID()])
1309         WorkList.push_back(Pred->getID());
1310     }
1311   }
1312 
1313 #ifndef NDEBUG
1314   // Check correctness of the ordering.
1315   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1316     SIScheduleBlock *Block = CurrentBlocks[i];
1317     for (SIScheduleBlock* Pred : Block->getPreds()) {
1318       assert(TopDownBlock2Index[i] > TopDownBlock2Index[Pred->getID()] &&
1319       "Wrong Top Down topological sorting");
1320     }
1321   }
1322 #endif
1323 
1324   BottomUpIndex2Block = std::vector<int>(TopDownIndex2Block.rbegin(),
1325                                          TopDownIndex2Block.rend());
1326 }
1327 
1328 void SIScheduleBlockCreator::scheduleInsideBlocks() {
1329   unsigned DAGSize = CurrentBlocks.size();
1330 
1331   LLVM_DEBUG(dbgs() << "\nScheduling Blocks\n\n");
1332 
1333   // We do schedule a valid scheduling such that a Block corresponds
1334   // to a range of instructions.
1335   LLVM_DEBUG(dbgs() << "First phase: Fast scheduling for Reg Liveness\n");
1336   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1337     SIScheduleBlock *Block = CurrentBlocks[i];
1338     Block->fastSchedule();
1339   }
1340 
1341   // Note: the following code, and the part restoring previous position
1342   // is by far the most expensive operation of the Scheduler.
1343 
1344   // Do not update CurrentTop.
1345   MachineBasicBlock::iterator CurrentTopFastSched = DAG->getCurrentTop();
1346   std::vector<MachineBasicBlock::iterator> PosOld;
1347   std::vector<MachineBasicBlock::iterator> PosNew;
1348   PosOld.reserve(DAG->SUnits.size());
1349   PosNew.reserve(DAG->SUnits.size());
1350 
1351   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1352     int BlockIndice = TopDownIndex2Block[i];
1353     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1354     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1355 
1356     for (SUnit* SU : SUs) {
1357       MachineInstr *MI = SU->getInstr();
1358       MachineBasicBlock::iterator Pos = MI;
1359       PosOld.push_back(Pos);
1360       if (&*CurrentTopFastSched == MI) {
1361         PosNew.push_back(Pos);
1362         CurrentTopFastSched = nextIfDebug(++CurrentTopFastSched,
1363                                           DAG->getCurrentBottom());
1364       } else {
1365         // Update the instruction stream.
1366         DAG->getBB()->splice(CurrentTopFastSched, DAG->getBB(), MI);
1367 
1368         // Update LiveIntervals.
1369         // Note: Moving all instructions and calling handleMove every time
1370         // is the most cpu intensive operation of the scheduler.
1371         // It would gain a lot if there was a way to recompute the
1372         // LiveIntervals for the entire scheduling region.
1373         DAG->getLIS()->handleMove(*MI, /*UpdateFlags=*/true);
1374         PosNew.push_back(CurrentTopFastSched);
1375       }
1376     }
1377   }
1378 
1379   // Now we have Block of SUs == Block of MI.
1380   // We do the final schedule for the instructions inside the block.
1381   // The property that all the SUs of the Block are grouped together as MI
1382   // is used for correct reg usage tracking.
1383   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1384     SIScheduleBlock *Block = CurrentBlocks[i];
1385     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1386     Block->schedule((*SUs.begin())->getInstr(), (*SUs.rbegin())->getInstr());
1387   }
1388 
1389   LLVM_DEBUG(dbgs() << "Restoring MI Pos\n");
1390   // Restore old ordering (which prevents a LIS->handleMove bug).
1391   for (unsigned i = PosOld.size(), e = 0; i != e; --i) {
1392     MachineBasicBlock::iterator POld = PosOld[i-1];
1393     MachineBasicBlock::iterator PNew = PosNew[i-1];
1394     if (PNew != POld) {
1395       // Update the instruction stream.
1396       DAG->getBB()->splice(POld, DAG->getBB(), PNew);
1397 
1398       // Update LiveIntervals.
1399       DAG->getLIS()->handleMove(*POld, /*UpdateFlags=*/true);
1400     }
1401   }
1402 
1403   LLVM_DEBUG(for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1404     SIScheduleBlock *Block = CurrentBlocks[i];
1405     Block->printDebug(true);
1406   });
1407 }
1408 
1409 void SIScheduleBlockCreator::fillStats() {
1410   unsigned DAGSize = CurrentBlocks.size();
1411 
1412   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1413     int BlockIndice = TopDownIndex2Block[i];
1414     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1415     if (Block->getPreds().empty())
1416       Block->Depth = 0;
1417     else {
1418       unsigned Depth = 0;
1419       for (SIScheduleBlock *Pred : Block->getPreds()) {
1420         if (Depth < Pred->Depth + Pred->getCost())
1421           Depth = Pred->Depth + Pred->getCost();
1422       }
1423       Block->Depth = Depth;
1424     }
1425   }
1426 
1427   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1428     int BlockIndice = BottomUpIndex2Block[i];
1429     SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1430     if (Block->getSuccs().empty())
1431       Block->Height = 0;
1432     else {
1433       unsigned Height = 0;
1434       for (const auto &Succ : Block->getSuccs())
1435         Height = std::max(Height, Succ.first->Height + Succ.first->getCost());
1436       Block->Height = Height;
1437     }
1438   }
1439 }
1440 
1441 // SIScheduleBlockScheduler //
1442 
1443 SIScheduleBlockScheduler::SIScheduleBlockScheduler(SIScheduleDAGMI *DAG,
1444                                                    SISchedulerBlockSchedulerVariant Variant,
1445                                                    SIScheduleBlocks  BlocksStruct) :
1446   DAG(DAG), Variant(Variant), Blocks(BlocksStruct.Blocks),
1447   LastPosWaitedHighLatency(0), NumBlockScheduled(0), VregCurrentUsage(0),
1448   SregCurrentUsage(0), maxVregUsage(0), maxSregUsage(0) {
1449 
1450   // Fill the usage of every output
1451   // Warning: while by construction we always have a link between two blocks
1452   // when one needs a result from the other, the number of users of an output
1453   // is not the sum of child blocks having as input the same virtual register.
1454   // Here is an example. A produces x and y. B eats x and produces x'.
1455   // C eats x' and y. The register coalescer may have attributed the same
1456   // virtual register to x and x'.
1457   // To count accurately, we do a topological sort. In case the register is
1458   // found for several parents, we increment the usage of the one with the
1459   // highest topological index.
1460   LiveOutRegsNumUsages.resize(Blocks.size());
1461   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1462     SIScheduleBlock *Block = Blocks[i];
1463     for (unsigned Reg : Block->getInRegs()) {
1464       bool Found = false;
1465       int topoInd = -1;
1466       for (SIScheduleBlock* Pred: Block->getPreds()) {
1467         std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1468         std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1469 
1470         if (RegPos != PredOutRegs.end()) {
1471           Found = true;
1472           if (topoInd < BlocksStruct.TopDownBlock2Index[Pred->getID()]) {
1473             topoInd = BlocksStruct.TopDownBlock2Index[Pred->getID()];
1474           }
1475         }
1476       }
1477 
1478       if (!Found)
1479         continue;
1480 
1481       int PredID = BlocksStruct.TopDownIndex2Block[topoInd];
1482       ++LiveOutRegsNumUsages[PredID][Reg];
1483     }
1484   }
1485 
1486   LastPosHighLatencyParentScheduled.resize(Blocks.size(), 0);
1487   BlockNumPredsLeft.resize(Blocks.size());
1488   BlockNumSuccsLeft.resize(Blocks.size());
1489 
1490   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1491     SIScheduleBlock *Block = Blocks[i];
1492     BlockNumPredsLeft[i] = Block->getPreds().size();
1493     BlockNumSuccsLeft[i] = Block->getSuccs().size();
1494   }
1495 
1496 #ifndef NDEBUG
1497   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1498     SIScheduleBlock *Block = Blocks[i];
1499     assert(Block->getID() == i);
1500   }
1501 #endif
1502 
1503   std::set<unsigned> InRegs = DAG->getInRegs();
1504   addLiveRegs(InRegs);
1505 
1506   // Increase LiveOutRegsNumUsages for blocks
1507   // producing registers consumed in another
1508   // scheduling region.
1509   for (unsigned Reg : DAG->getOutRegs()) {
1510     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1511       // Do reverse traversal
1512       int ID = BlocksStruct.TopDownIndex2Block[Blocks.size()-1-i];
1513       SIScheduleBlock *Block = Blocks[ID];
1514       const std::set<unsigned> &OutRegs = Block->getOutRegs();
1515 
1516       if (OutRegs.find(Reg) == OutRegs.end())
1517         continue;
1518 
1519       ++LiveOutRegsNumUsages[ID][Reg];
1520       break;
1521     }
1522   }
1523 
1524   // Fill LiveRegsConsumers for regs that were already
1525   // defined before scheduling.
1526   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1527     SIScheduleBlock *Block = Blocks[i];
1528     for (unsigned Reg : Block->getInRegs()) {
1529       bool Found = false;
1530       for (SIScheduleBlock* Pred: Block->getPreds()) {
1531         std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1532         std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1533 
1534         if (RegPos != PredOutRegs.end()) {
1535           Found = true;
1536           break;
1537         }
1538       }
1539 
1540       if (!Found)
1541         ++LiveRegsConsumers[Reg];
1542     }
1543   }
1544 
1545   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1546     SIScheduleBlock *Block = Blocks[i];
1547     if (BlockNumPredsLeft[i] == 0) {
1548       ReadyBlocks.push_back(Block);
1549     }
1550   }
1551 
1552   while (SIScheduleBlock *Block = pickBlock()) {
1553     BlocksScheduled.push_back(Block);
1554     blockScheduled(Block);
1555   }
1556 
1557   LLVM_DEBUG(dbgs() << "Block Order:"; for (SIScheduleBlock *Block
1558                                             : BlocksScheduled) {
1559     dbgs() << ' ' << Block->getID();
1560   } dbgs() << '\n';);
1561 }
1562 
1563 bool SIScheduleBlockScheduler::tryCandidateLatency(SIBlockSchedCandidate &Cand,
1564                                                    SIBlockSchedCandidate &TryCand) {
1565   if (!Cand.isValid()) {
1566     TryCand.Reason = NodeOrder;
1567     return true;
1568   }
1569 
1570   // Try to hide high latencies.
1571   if (SISched::tryLess(TryCand.LastPosHighLatParentScheduled,
1572                  Cand.LastPosHighLatParentScheduled, TryCand, Cand, Latency))
1573     return true;
1574   // Schedule high latencies early so you can hide them better.
1575   if (SISched::tryGreater(TryCand.IsHighLatency, Cand.IsHighLatency,
1576                           TryCand, Cand, Latency))
1577     return true;
1578   if (TryCand.IsHighLatency && SISched::tryGreater(TryCand.Height, Cand.Height,
1579                                                    TryCand, Cand, Depth))
1580     return true;
1581   if (SISched::tryGreater(TryCand.NumHighLatencySuccessors,
1582                           Cand.NumHighLatencySuccessors,
1583                           TryCand, Cand, Successor))
1584     return true;
1585   return false;
1586 }
1587 
1588 bool SIScheduleBlockScheduler::tryCandidateRegUsage(SIBlockSchedCandidate &Cand,
1589                                                     SIBlockSchedCandidate &TryCand) {
1590   if (!Cand.isValid()) {
1591     TryCand.Reason = NodeOrder;
1592     return true;
1593   }
1594 
1595   if (SISched::tryLess(TryCand.VGPRUsageDiff > 0, Cand.VGPRUsageDiff > 0,
1596                        TryCand, Cand, RegUsage))
1597     return true;
1598   if (SISched::tryGreater(TryCand.NumSuccessors > 0,
1599                           Cand.NumSuccessors > 0,
1600                           TryCand, Cand, Successor))
1601     return true;
1602   if (SISched::tryGreater(TryCand.Height, Cand.Height, TryCand, Cand, Depth))
1603     return true;
1604   if (SISched::tryLess(TryCand.VGPRUsageDiff, Cand.VGPRUsageDiff,
1605                        TryCand, Cand, RegUsage))
1606     return true;
1607   return false;
1608 }
1609 
1610 SIScheduleBlock *SIScheduleBlockScheduler::pickBlock() {
1611   SIBlockSchedCandidate Cand;
1612   std::vector<SIScheduleBlock*>::iterator Best;
1613   SIScheduleBlock *Block;
1614   if (ReadyBlocks.empty())
1615     return nullptr;
1616 
1617   DAG->fillVgprSgprCost(LiveRegs.begin(), LiveRegs.end(),
1618                         VregCurrentUsage, SregCurrentUsage);
1619   if (VregCurrentUsage > maxVregUsage)
1620     maxVregUsage = VregCurrentUsage;
1621   if (SregCurrentUsage > maxSregUsage)
1622     maxSregUsage = SregCurrentUsage;
1623   LLVM_DEBUG(dbgs() << "Picking New Blocks\n"; dbgs() << "Available: ";
1624              for (SIScheduleBlock *Block
1625                   : ReadyBlocks) dbgs()
1626              << Block->getID() << ' ';
1627              dbgs() << "\nCurrent Live:\n";
1628              for (unsigned Reg
1629                   : LiveRegs) dbgs()
1630              << printVRegOrUnit(Reg, DAG->getTRI()) << ' ';
1631              dbgs() << '\n';
1632              dbgs() << "Current VGPRs: " << VregCurrentUsage << '\n';
1633              dbgs() << "Current SGPRs: " << SregCurrentUsage << '\n';);
1634 
1635   Cand.Block = nullptr;
1636   for (std::vector<SIScheduleBlock*>::iterator I = ReadyBlocks.begin(),
1637        E = ReadyBlocks.end(); I != E; ++I) {
1638     SIBlockSchedCandidate TryCand;
1639     TryCand.Block = *I;
1640     TryCand.IsHighLatency = TryCand.Block->isHighLatencyBlock();
1641     TryCand.VGPRUsageDiff =
1642       checkRegUsageImpact(TryCand.Block->getInRegs(),
1643                           TryCand.Block->getOutRegs())[DAG->getVGPRSetID()];
1644     TryCand.NumSuccessors = TryCand.Block->getSuccs().size();
1645     TryCand.NumHighLatencySuccessors =
1646       TryCand.Block->getNumHighLatencySuccessors();
1647     TryCand.LastPosHighLatParentScheduled =
1648       (unsigned int) std::max<int> (0,
1649          LastPosHighLatencyParentScheduled[TryCand.Block->getID()] -
1650            LastPosWaitedHighLatency);
1651     TryCand.Height = TryCand.Block->Height;
1652     // Try not to increase VGPR usage too much, else we may spill.
1653     if (VregCurrentUsage > 120 ||
1654         Variant != SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage) {
1655       if (!tryCandidateRegUsage(Cand, TryCand) &&
1656           Variant != SISchedulerBlockSchedulerVariant::BlockRegUsage)
1657         tryCandidateLatency(Cand, TryCand);
1658     } else {
1659       if (!tryCandidateLatency(Cand, TryCand))
1660         tryCandidateRegUsage(Cand, TryCand);
1661     }
1662     if (TryCand.Reason != NoCand) {
1663       Cand.setBest(TryCand);
1664       Best = I;
1665       LLVM_DEBUG(dbgs() << "Best Current Choice: " << Cand.Block->getID() << ' '
1666                         << getReasonStr(Cand.Reason) << '\n');
1667     }
1668   }
1669 
1670   LLVM_DEBUG(dbgs() << "Picking: " << Cand.Block->getID() << '\n';
1671              dbgs() << "Is a block with high latency instruction: "
1672                     << (Cand.IsHighLatency ? "yes\n" : "no\n");
1673              dbgs() << "Position of last high latency dependency: "
1674                     << Cand.LastPosHighLatParentScheduled << '\n';
1675              dbgs() << "VGPRUsageDiff: " << Cand.VGPRUsageDiff << '\n';
1676              dbgs() << '\n';);
1677 
1678   Block = Cand.Block;
1679   ReadyBlocks.erase(Best);
1680   return Block;
1681 }
1682 
1683 // Tracking of currently alive registers to determine VGPR Usage.
1684 
1685 void SIScheduleBlockScheduler::addLiveRegs(std::set<unsigned> &Regs) {
1686   for (unsigned Reg : Regs) {
1687     // For now only track virtual registers.
1688     if (!Register::isVirtualRegister(Reg))
1689       continue;
1690     // If not already in the live set, then add it.
1691     (void) LiveRegs.insert(Reg);
1692   }
1693 }
1694 
1695 void SIScheduleBlockScheduler::decreaseLiveRegs(SIScheduleBlock *Block,
1696                                        std::set<unsigned> &Regs) {
1697   for (unsigned Reg : Regs) {
1698     // For now only track virtual registers.
1699     std::set<unsigned>::iterator Pos = LiveRegs.find(Reg);
1700     assert (Pos != LiveRegs.end() && // Reg must be live.
1701                LiveRegsConsumers.find(Reg) != LiveRegsConsumers.end() &&
1702                LiveRegsConsumers[Reg] >= 1);
1703     --LiveRegsConsumers[Reg];
1704     if (LiveRegsConsumers[Reg] == 0)
1705       LiveRegs.erase(Pos);
1706   }
1707 }
1708 
1709 void SIScheduleBlockScheduler::releaseBlockSuccs(SIScheduleBlock *Parent) {
1710   for (const auto &Block : Parent->getSuccs()) {
1711     if (--BlockNumPredsLeft[Block.first->getID()] == 0)
1712       ReadyBlocks.push_back(Block.first);
1713 
1714     if (Parent->isHighLatencyBlock() &&
1715         Block.second == SIScheduleBlockLinkKind::Data)
1716       LastPosHighLatencyParentScheduled[Block.first->getID()] = NumBlockScheduled;
1717   }
1718 }
1719 
1720 void SIScheduleBlockScheduler::blockScheduled(SIScheduleBlock *Block) {
1721   decreaseLiveRegs(Block, Block->getInRegs());
1722   addLiveRegs(Block->getOutRegs());
1723   releaseBlockSuccs(Block);
1724   for (std::map<unsigned, unsigned>::iterator RegI =
1725        LiveOutRegsNumUsages[Block->getID()].begin(),
1726        E = LiveOutRegsNumUsages[Block->getID()].end(); RegI != E; ++RegI) {
1727     std::pair<unsigned, unsigned> RegP = *RegI;
1728     // We produce this register, thus it must not be previously alive.
1729     assert(LiveRegsConsumers.find(RegP.first) == LiveRegsConsumers.end() ||
1730            LiveRegsConsumers[RegP.first] == 0);
1731     LiveRegsConsumers[RegP.first] += RegP.second;
1732   }
1733   if (LastPosHighLatencyParentScheduled[Block->getID()] >
1734         (unsigned)LastPosWaitedHighLatency)
1735     LastPosWaitedHighLatency =
1736       LastPosHighLatencyParentScheduled[Block->getID()];
1737   ++NumBlockScheduled;
1738 }
1739 
1740 std::vector<int>
1741 SIScheduleBlockScheduler::checkRegUsageImpact(std::set<unsigned> &InRegs,
1742                                      std::set<unsigned> &OutRegs) {
1743   std::vector<int> DiffSetPressure;
1744   DiffSetPressure.assign(DAG->getTRI()->getNumRegPressureSets(), 0);
1745 
1746   for (unsigned Reg : InRegs) {
1747     // For now only track virtual registers.
1748     if (!Register::isVirtualRegister(Reg))
1749       continue;
1750     if (LiveRegsConsumers[Reg] > 1)
1751       continue;
1752     PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1753     for (; PSetI.isValid(); ++PSetI) {
1754       DiffSetPressure[*PSetI] -= PSetI.getWeight();
1755     }
1756   }
1757 
1758   for (unsigned Reg : OutRegs) {
1759     // For now only track virtual registers.
1760     if (!Register::isVirtualRegister(Reg))
1761       continue;
1762     PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1763     for (; PSetI.isValid(); ++PSetI) {
1764       DiffSetPressure[*PSetI] += PSetI.getWeight();
1765     }
1766   }
1767 
1768   return DiffSetPressure;
1769 }
1770 
1771 // SIScheduler //
1772 
1773 struct SIScheduleBlockResult
1774 SIScheduler::scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant,
1775                              SISchedulerBlockSchedulerVariant ScheduleVariant) {
1776   SIScheduleBlocks Blocks = BlockCreator.getBlocks(BlockVariant);
1777   SIScheduleBlockScheduler Scheduler(DAG, ScheduleVariant, Blocks);
1778   std::vector<SIScheduleBlock*> ScheduledBlocks;
1779   struct SIScheduleBlockResult Res;
1780 
1781   ScheduledBlocks = Scheduler.getBlocks();
1782 
1783   for (unsigned b = 0; b < ScheduledBlocks.size(); ++b) {
1784     SIScheduleBlock *Block = ScheduledBlocks[b];
1785     std::vector<SUnit*> SUs = Block->getScheduledUnits();
1786 
1787     for (SUnit* SU : SUs)
1788       Res.SUs.push_back(SU->NodeNum);
1789   }
1790 
1791   Res.MaxSGPRUsage = Scheduler.getSGPRUsage();
1792   Res.MaxVGPRUsage = Scheduler.getVGPRUsage();
1793   return Res;
1794 }
1795 
1796 // SIScheduleDAGMI //
1797 
1798 SIScheduleDAGMI::SIScheduleDAGMI(MachineSchedContext *C) :
1799   ScheduleDAGMILive(C, std::make_unique<GenericScheduler>(C)) {
1800   SITII = static_cast<const SIInstrInfo*>(TII);
1801   SITRI = static_cast<const SIRegisterInfo*>(TRI);
1802 
1803   VGPRSetID = SITRI->getVGPRPressureSet();
1804   SGPRSetID = SITRI->getSGPRPressureSet();
1805 }
1806 
1807 SIScheduleDAGMI::~SIScheduleDAGMI() = default;
1808 
1809 // Code adapted from scheduleDAG.cpp
1810 // Does a topological sort over the SUs.
1811 // Both TopDown and BottomUp
1812 void SIScheduleDAGMI::topologicalSort() {
1813   Topo.InitDAGTopologicalSorting();
1814 
1815   TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());
1816   BottomUpIndex2SU = std::vector<int>(Topo.rbegin(), Topo.rend());
1817 }
1818 
1819 // Move low latencies further from their user without
1820 // increasing SGPR usage (in general)
1821 // This is to be replaced by a better pass that would
1822 // take into account SGPR usage (based on VGPR Usage
1823 // and the corresponding wavefront count), that would
1824 // try to merge groups of loads if it make sense, etc
1825 void SIScheduleDAGMI::moveLowLatencies() {
1826    unsigned DAGSize = SUnits.size();
1827    int LastLowLatencyUser = -1;
1828    int LastLowLatencyPos = -1;
1829 
1830    for (unsigned i = 0, e = ScheduledSUnits.size(); i != e; ++i) {
1831     SUnit *SU = &SUnits[ScheduledSUnits[i]];
1832     bool IsLowLatencyUser = false;
1833     unsigned MinPos = 0;
1834 
1835     for (SDep& PredDep : SU->Preds) {
1836       SUnit *Pred = PredDep.getSUnit();
1837       if (SITII->isLowLatencyInstruction(*Pred->getInstr())) {
1838         IsLowLatencyUser = true;
1839       }
1840       if (Pred->NodeNum >= DAGSize)
1841         continue;
1842       unsigned PredPos = ScheduledSUnitsInv[Pred->NodeNum];
1843       if (PredPos >= MinPos)
1844         MinPos = PredPos + 1;
1845     }
1846 
1847     if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
1848       unsigned BestPos = LastLowLatencyUser + 1;
1849       if ((int)BestPos <= LastLowLatencyPos)
1850         BestPos = LastLowLatencyPos + 1;
1851       if (BestPos < MinPos)
1852         BestPos = MinPos;
1853       if (BestPos < i) {
1854         for (unsigned u = i; u > BestPos; --u) {
1855           ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1856           ScheduledSUnits[u] = ScheduledSUnits[u-1];
1857         }
1858         ScheduledSUnits[BestPos] = SU->NodeNum;
1859         ScheduledSUnitsInv[SU->NodeNum] = BestPos;
1860       }
1861       LastLowLatencyPos = BestPos;
1862       if (IsLowLatencyUser)
1863         LastLowLatencyUser = BestPos;
1864     } else if (IsLowLatencyUser) {
1865       LastLowLatencyUser = i;
1866     // Moves COPY instructions on which depends
1867     // the low latency instructions too.
1868     } else if (SU->getInstr()->getOpcode() == AMDGPU::COPY) {
1869       bool CopyForLowLat = false;
1870       for (SDep& SuccDep : SU->Succs) {
1871         SUnit *Succ = SuccDep.getSUnit();
1872         if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1873           continue;
1874         if (SITII->isLowLatencyInstruction(*Succ->getInstr())) {
1875           CopyForLowLat = true;
1876         }
1877       }
1878       if (!CopyForLowLat)
1879         continue;
1880       if (MinPos < i) {
1881         for (unsigned u = i; u > MinPos; --u) {
1882           ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1883           ScheduledSUnits[u] = ScheduledSUnits[u-1];
1884         }
1885         ScheduledSUnits[MinPos] = SU->NodeNum;
1886         ScheduledSUnitsInv[SU->NodeNum] = MinPos;
1887       }
1888     }
1889   }
1890 }
1891 
1892 void SIScheduleDAGMI::restoreSULinksLeft() {
1893   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1894     SUnits[i].isScheduled = false;
1895     SUnits[i].WeakPredsLeft = SUnitsLinksBackup[i].WeakPredsLeft;
1896     SUnits[i].NumPredsLeft = SUnitsLinksBackup[i].NumPredsLeft;
1897     SUnits[i].WeakSuccsLeft = SUnitsLinksBackup[i].WeakSuccsLeft;
1898     SUnits[i].NumSuccsLeft = SUnitsLinksBackup[i].NumSuccsLeft;
1899   }
1900 }
1901 
1902 // Return the Vgpr and Sgpr usage corresponding to some virtual registers.
1903 template<typename _Iterator> void
1904 SIScheduleDAGMI::fillVgprSgprCost(_Iterator First, _Iterator End,
1905                                   unsigned &VgprUsage, unsigned &SgprUsage) {
1906   VgprUsage = 0;
1907   SgprUsage = 0;
1908   for (_Iterator RegI = First; RegI != End; ++RegI) {
1909     unsigned Reg = *RegI;
1910     // For now only track virtual registers
1911     if (!Register::isVirtualRegister(Reg))
1912       continue;
1913     PSetIterator PSetI = MRI.getPressureSets(Reg);
1914     for (; PSetI.isValid(); ++PSetI) {
1915       if (*PSetI == VGPRSetID)
1916         VgprUsage += PSetI.getWeight();
1917       else if (*PSetI == SGPRSetID)
1918         SgprUsage += PSetI.getWeight();
1919     }
1920   }
1921 }
1922 
1923 void SIScheduleDAGMI::schedule()
1924 {
1925   SmallVector<SUnit*, 8> TopRoots, BotRoots;
1926   SIScheduleBlockResult Best, Temp;
1927   LLVM_DEBUG(dbgs() << "Preparing Scheduling\n");
1928 
1929   buildDAGWithRegPressure();
1930   LLVM_DEBUG(dump());
1931 
1932   topologicalSort();
1933   findRootsAndBiasEdges(TopRoots, BotRoots);
1934   // We reuse several ScheduleDAGMI and ScheduleDAGMILive
1935   // functions, but to make them happy we must initialize
1936   // the default Scheduler implementation (even if we do not
1937   // run it)
1938   SchedImpl->initialize(this);
1939   initQueues(TopRoots, BotRoots);
1940 
1941   // Fill some stats to help scheduling.
1942 
1943   SUnitsLinksBackup = SUnits;
1944   IsLowLatencySU.clear();
1945   LowLatencyOffset.clear();
1946   IsHighLatencySU.clear();
1947 
1948   IsLowLatencySU.resize(SUnits.size(), 0);
1949   LowLatencyOffset.resize(SUnits.size(), 0);
1950   IsHighLatencySU.resize(SUnits.size(), 0);
1951 
1952   for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
1953     SUnit *SU = &SUnits[i];
1954     const MachineOperand *BaseLatOp;
1955     int64_t OffLatReg;
1956     if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
1957       IsLowLatencySU[i] = 1;
1958       if (SITII->getMemOperandWithOffset(*SU->getInstr(), BaseLatOp, OffLatReg,
1959                                          TRI))
1960         LowLatencyOffset[i] = OffLatReg;
1961     } else if (SITII->isHighLatencyInstruction(*SU->getInstr()))
1962       IsHighLatencySU[i] = 1;
1963   }
1964 
1965   SIScheduler Scheduler(this);
1966   Best = Scheduler.scheduleVariant(SISchedulerBlockCreatorVariant::LatenciesAlone,
1967                                    SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage);
1968 
1969   // if VGPR usage is extremely high, try other good performing variants
1970   // which could lead to lower VGPR usage
1971   if (Best.MaxVGPRUsage > 180) {
1972     static const std::pair<SISchedulerBlockCreatorVariant,
1973                            SISchedulerBlockSchedulerVariant>
1974         Variants[] = {
1975       { LatenciesAlone, BlockRegUsageLatency },
1976 //      { LatenciesAlone, BlockRegUsage },
1977       { LatenciesGrouped, BlockLatencyRegUsage },
1978 //      { LatenciesGrouped, BlockRegUsageLatency },
1979 //      { LatenciesGrouped, BlockRegUsage },
1980       { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1981 //      { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1982 //      { LatenciesAlonePlusConsecutive, BlockRegUsage }
1983     };
1984     for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1985       Temp = Scheduler.scheduleVariant(v.first, v.second);
1986       if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
1987         Best = Temp;
1988     }
1989   }
1990   // if VGPR usage is still extremely high, we may spill. Try other variants
1991   // which are less performing, but that could lead to lower VGPR usage.
1992   if (Best.MaxVGPRUsage > 200) {
1993     static const std::pair<SISchedulerBlockCreatorVariant,
1994                            SISchedulerBlockSchedulerVariant>
1995         Variants[] = {
1996 //      { LatenciesAlone, BlockRegUsageLatency },
1997       { LatenciesAlone, BlockRegUsage },
1998 //      { LatenciesGrouped, BlockLatencyRegUsage },
1999       { LatenciesGrouped, BlockRegUsageLatency },
2000       { LatenciesGrouped, BlockRegUsage },
2001 //      { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
2002       { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
2003       { LatenciesAlonePlusConsecutive, BlockRegUsage }
2004     };
2005     for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
2006       Temp = Scheduler.scheduleVariant(v.first, v.second);
2007       if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
2008         Best = Temp;
2009     }
2010   }
2011 
2012   ScheduledSUnits = Best.SUs;
2013   ScheduledSUnitsInv.resize(SUnits.size());
2014 
2015   for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
2016     ScheduledSUnitsInv[ScheduledSUnits[i]] = i;
2017   }
2018 
2019   moveLowLatencies();
2020 
2021   // Tell the outside world about the result of the scheduling.
2022 
2023   assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
2024   TopRPTracker.setPos(CurrentTop);
2025 
2026   for (std::vector<unsigned>::iterator I = ScheduledSUnits.begin(),
2027        E = ScheduledSUnits.end(); I != E; ++I) {
2028     SUnit *SU = &SUnits[*I];
2029 
2030     scheduleMI(SU, true);
2031 
2032     LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
2033                       << *SU->getInstr());
2034   }
2035 
2036   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
2037 
2038   placeDebugValues();
2039 
2040   LLVM_DEBUG({
2041     dbgs() << "*** Final schedule for "
2042            << printMBBReference(*begin()->getParent()) << " ***\n";
2043     dumpSchedule();
2044     dbgs() << '\n';
2045   });
2046 }
2047