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