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