blob: f77905336b2678fe2aeeebb913a1beebbf49842f [file] [log] [blame]
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001//===-- SIMachineScheduler.cpp - SI Scheduler Interface -------------------===//
Nicolai Haehnle02c32912016-01-13 16:10:10 +00002//
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/// \brief SI Machine Scheduler interface
12//
13//===----------------------------------------------------------------------===//
14
Matt Arsenault43e92fe2016-06-24 06:30:11 +000015#include "AMDGPU.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000016#include "SIInstrInfo.h"
Nicolai Haehnle02c32912016-01-13 16:10:10 +000017#include "SIMachineScheduler.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000018#include "SIRegisterInfo.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
Nicolai Haehnle02c32912016-01-13 16:10:10 +000021#include "llvm/CodeGen/LiveInterval.h"
22#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000023#include "llvm/CodeGen/MachineInstr.h"
Nicolai Haehnle02c32912016-01-13 16:10:10 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/MachineScheduler.h"
26#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenko6a9226d2016-12-12 22:23:53 +000027#include "llvm/CodeGen/SlotIndexes.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Target/TargetRegisterInfo.h"
32#include <algorithm>
33#include <cassert>
34#include <map>
35#include <set>
36#include <utility>
37#include <vector>
Nicolai Haehnle02c32912016-01-13 16:10:10 +000038
39using namespace llvm;
40
41#define DEBUG_TYPE "misched"
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//
Simon Pilgrime995a8082016-11-18 11:04:02 +000096// Second the order of the instructions inside the blocks is chosen.
Nicolai Haehnle02c32912016-01-13 16:10:10 +000097// At that step we do take into account only register usage and hiding
98// low latency instructions
99//
Simon Pilgrime995a8082016-11-18 11:04:02 +0000100// Third the block order is chosen, there we try to hide high latencies
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000101// 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,
Simon Pilgrime995a8082016-11-18 11:04:02 +0000108// and the bandwidth limitations.
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000109// 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
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000139// common code //
140
141#ifndef NDEBUG
142
143static 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
157static bool tryLess(int TryVal, int CandVal,
158 SISchedulerCandidate &TryCand,
159 SISchedulerCandidate &Cand,
160 SIScheduleCandReason Reason) {
161 if (TryVal < CandVal) {
162 TryCand.Reason = Reason;
163 return true;
164 }
165 if (TryVal > CandVal) {
166 if (Cand.Reason > Reason)
167 Cand.Reason = Reason;
168 return true;
169 }
170 Cand.setRepeat(Reason);
171 return false;
172}
173
174static bool tryGreater(int TryVal, int CandVal,
175 SISchedulerCandidate &TryCand,
176 SISchedulerCandidate &Cand,
177 SIScheduleCandReason Reason) {
178 if (TryVal > CandVal) {
179 TryCand.Reason = Reason;
180 return true;
181 }
182 if (TryVal < CandVal) {
183 if (Cand.Reason > Reason)
184 Cand.Reason = Reason;
185 return true;
186 }
187 Cand.setRepeat(Reason);
188 return false;
189}
190
191// SIScheduleBlock //
192
193void SIScheduleBlock::addUnit(SUnit *SU) {
194 NodeNum2Index[SU->NodeNum] = SUnits.size();
195 SUnits.push_back(SU);
196}
197
198#ifndef NDEBUG
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000199void SIScheduleBlock::traceCandidate(const SISchedCandidate &Cand) {
200
201 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
202 dbgs() << '\n';
203}
204#endif
205
206void SIScheduleBlock::tryCandidateTopDown(SISchedCandidate &Cand,
207 SISchedCandidate &TryCand) {
208 // Initialize the candidate if needed.
209 if (!Cand.isValid()) {
210 TryCand.Reason = NodeOrder;
211 return;
212 }
213
214 if (Cand.SGPRUsage > 60 &&
215 tryLess(TryCand.SGPRUsage, Cand.SGPRUsage, TryCand, Cand, RegUsage))
216 return;
217
218 // Schedule low latency instructions as top as possible.
219 // Order of priority is:
220 // . Low latency instructions which do not depend on other low latency
221 // instructions we haven't waited for
222 // . Other instructions which do not depend on low latency instructions
223 // we haven't waited for
224 // . Low latencies
225 // . All other instructions
Simon Pilgrime995a8082016-11-18 11:04:02 +0000226 // Goal is to get: low latency instructions - independent instructions
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000227 // - (eventually some more low latency instructions)
228 // - instructions that depend on the first low latency instructions.
229 // If in the block there is a lot of constant loads, the SGPR usage
230 // could go quite high, thus above the arbitrary limit of 60 will encourage
231 // use the already loaded constants (in order to release some SGPRs) before
232 // loading more.
233 if (tryLess(TryCand.HasLowLatencyNonWaitedParent,
234 Cand.HasLowLatencyNonWaitedParent,
235 TryCand, Cand, SIScheduleCandReason::Depth))
236 return;
237
238 if (tryGreater(TryCand.IsLowLatency, Cand.IsLowLatency,
239 TryCand, Cand, SIScheduleCandReason::Depth))
240 return;
241
242 if (TryCand.IsLowLatency &&
243 tryLess(TryCand.LowLatencyOffset, Cand.LowLatencyOffset,
244 TryCand, Cand, SIScheduleCandReason::Depth))
245 return;
246
247 if (tryLess(TryCand.VGPRUsage, Cand.VGPRUsage, TryCand, Cand, RegUsage))
248 return;
249
250 // Fall through to original instruction order.
251 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) {
252 TryCand.Reason = NodeOrder;
253 }
254}
255
256SUnit* SIScheduleBlock::pickNode() {
257 SISchedCandidate TopCand;
258
259 for (SUnit* SU : TopReadySUs) {
260 SISchedCandidate TryCand;
261 std::vector<unsigned> pressure;
262 std::vector<unsigned> MaxPressure;
263 // Predict register usage after this instruction.
264 TryCand.SU = SU;
265 TopRPTracker.getDownwardPressure(SU->getInstr(), pressure, MaxPressure);
266 TryCand.SGPRUsage = pressure[DAG->getSGPRSetID()];
267 TryCand.VGPRUsage = pressure[DAG->getVGPRSetID()];
268 TryCand.IsLowLatency = DAG->IsLowLatencySU[SU->NodeNum];
269 TryCand.LowLatencyOffset = DAG->LowLatencyOffset[SU->NodeNum];
270 TryCand.HasLowLatencyNonWaitedParent =
271 HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]];
272 tryCandidateTopDown(TopCand, TryCand);
273 if (TryCand.Reason != NoCand)
274 TopCand.setBest(TryCand);
275 }
276
277 return TopCand.SU;
278}
279
280
281// Schedule something valid.
282void SIScheduleBlock::fastSchedule() {
283 TopReadySUs.clear();
284 if (Scheduled)
285 undoSchedule();
286
287 for (SUnit* SU : SUnits) {
288 if (!SU->NumPredsLeft)
289 TopReadySUs.push_back(SU);
290 }
291
292 while (!TopReadySUs.empty()) {
293 SUnit *SU = TopReadySUs[0];
294 ScheduledSUnits.push_back(SU);
295 nodeScheduled(SU);
296 }
297
298 Scheduled = true;
299}
300
301// Returns if the register was set between first and last.
302static bool isDefBetween(unsigned Reg,
303 SlotIndex First, SlotIndex Last,
304 const MachineRegisterInfo *MRI,
305 const LiveIntervals *LIS) {
306 for (MachineRegisterInfo::def_instr_iterator
307 UI = MRI->def_instr_begin(Reg),
308 UE = MRI->def_instr_end(); UI != UE; ++UI) {
309 const MachineInstr* MI = &*UI;
310 if (MI->isDebugValue())
311 continue;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000312 SlotIndex InstSlot = LIS->getInstructionIndex(*MI).getRegSlot();
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000313 if (InstSlot >= First && InstSlot <= Last)
314 return true;
315 }
316 return false;
317}
318
319void SIScheduleBlock::initRegPressure(MachineBasicBlock::iterator BeginBlock,
320 MachineBasicBlock::iterator EndBlock) {
321 IntervalPressure Pressure, BotPressure;
322 RegPressureTracker RPTracker(Pressure), BotRPTracker(BotPressure);
323 LiveIntervals *LIS = DAG->getLIS();
324 MachineRegisterInfo *MRI = DAG->getMRI();
325 DAG->initRPTracker(TopRPTracker);
326 DAG->initRPTracker(BotRPTracker);
327 DAG->initRPTracker(RPTracker);
328
329 // Goes though all SU. RPTracker captures what had to be alive for the SUs
330 // to execute, and what is still alive at the end.
331 for (SUnit* SU : ScheduledSUnits) {
332 RPTracker.setPos(SU->getInstr());
333 RPTracker.advance();
334 }
335
336 // Close the RPTracker to finalize live ins/outs.
337 RPTracker.closeRegion();
338
339 // Initialize the live ins and live outs.
340 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
341 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
342
343 // Do not Track Physical Registers, because it messes up.
Matthias Braun5d458612016-01-20 00:23:26 +0000344 for (const auto &RegMaskPair : RPTracker.getPressure().LiveInRegs) {
345 if (TargetRegisterInfo::isVirtualRegister(RegMaskPair.RegUnit))
346 LiveInRegs.insert(RegMaskPair.RegUnit);
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000347 }
348 LiveOutRegs.clear();
349 // There is several possibilities to distinguish:
350 // 1) Reg is not input to any instruction in the block, but is output of one
351 // 2) 1) + read in the block and not needed after it
352 // 3) 1) + read in the block but needed in another block
353 // 4) Reg is input of an instruction but another block will read it too
354 // 5) Reg is input of an instruction and then rewritten in the block.
355 // result is not read in the block (implies used in another block)
356 // 6) Reg is input of an instruction and then rewritten in the block.
357 // result is read in the block and not needed in another block
358 // 7) Reg is input of an instruction and then rewritten in the block.
359 // result is read in the block but also needed in another block
360 // LiveInRegs will contains all the regs in situation 4, 5, 6, 7
361 // We want LiveOutRegs to contain only Regs whose content will be read after
362 // in another block, and whose content was written in the current block,
363 // that is we want it to get 1, 3, 5, 7
364 // Since we made the MIs of a block to be packed all together before
365 // scheduling, then the LiveIntervals were correct, and the RPTracker was
366 // able to correctly handle 5 vs 6, 2 vs 3.
367 // (Note: This is not sufficient for RPTracker to not do mistakes for case 4)
368 // The RPTracker's LiveOutRegs has 1, 3, (some correct or incorrect)4, 5, 7
369 // Comparing to LiveInRegs is not sufficient to differenciate 4 vs 5, 7
370 // The use of findDefBetween removes the case 4.
Matthias Braun5d458612016-01-20 00:23:26 +0000371 for (const auto &RegMaskPair : RPTracker.getPressure().LiveOutRegs) {
372 unsigned Reg = RegMaskPair.RegUnit;
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000373 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000374 isDefBetween(Reg, LIS->getInstructionIndex(*BeginBlock).getRegSlot(),
375 LIS->getInstructionIndex(*EndBlock).getRegSlot(), MRI,
376 LIS)) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000377 LiveOutRegs.insert(Reg);
378 }
379 }
380
381 // Pressure = sum_alive_registers register size
382 // Internally llvm will represent some registers as big 128 bits registers
383 // for example, but they actually correspond to 4 actual 32 bits registers.
384 // Thus Pressure is not equal to num_alive_registers * constant.
385 LiveInPressure = TopPressure.MaxSetPressure;
386 LiveOutPressure = BotPressure.MaxSetPressure;
387
388 // Prepares TopRPTracker for top down scheduling.
389 TopRPTracker.closeTop();
390}
391
392void SIScheduleBlock::schedule(MachineBasicBlock::iterator BeginBlock,
393 MachineBasicBlock::iterator EndBlock) {
394 if (!Scheduled)
395 fastSchedule();
396
397 // PreScheduling phase to set LiveIn and LiveOut.
398 initRegPressure(BeginBlock, EndBlock);
399 undoSchedule();
400
401 // Schedule for real now.
402
403 TopReadySUs.clear();
404
405 for (SUnit* SU : SUnits) {
406 if (!SU->NumPredsLeft)
407 TopReadySUs.push_back(SU);
408 }
409
410 while (!TopReadySUs.empty()) {
411 SUnit *SU = pickNode();
412 ScheduledSUnits.push_back(SU);
413 TopRPTracker.setPos(SU->getInstr());
414 TopRPTracker.advance();
415 nodeScheduled(SU);
416 }
417
418 // TODO: compute InternalAdditionnalPressure.
419 InternalAdditionnalPressure.resize(TopPressure.MaxSetPressure.size());
420
421 // Check everything is right.
422#ifndef NDEBUG
423 assert(SUnits.size() == ScheduledSUnits.size() &&
424 TopReadySUs.empty());
425 for (SUnit* SU : SUnits) {
426 assert(SU->isScheduled &&
427 SU->NumPredsLeft == 0);
428 }
429#endif
430
431 Scheduled = true;
432}
433
434void SIScheduleBlock::undoSchedule() {
435 for (SUnit* SU : SUnits) {
436 SU->isScheduled = false;
437 for (SDep& Succ : SU->Succs) {
438 if (BC->isSUInBlock(Succ.getSUnit(), ID))
439 undoReleaseSucc(SU, &Succ);
440 }
441 }
442 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
443 ScheduledSUnits.clear();
444 Scheduled = false;
445}
446
447void SIScheduleBlock::undoReleaseSucc(SUnit *SU, SDep *SuccEdge) {
448 SUnit *SuccSU = SuccEdge->getSUnit();
449
450 if (SuccEdge->isWeak()) {
451 ++SuccSU->WeakPredsLeft;
452 return;
453 }
454 ++SuccSU->NumPredsLeft;
455}
456
457void SIScheduleBlock::releaseSucc(SUnit *SU, SDep *SuccEdge) {
458 SUnit *SuccSU = SuccEdge->getSUnit();
459
460 if (SuccEdge->isWeak()) {
461 --SuccSU->WeakPredsLeft;
462 return;
463 }
464#ifndef NDEBUG
465 if (SuccSU->NumPredsLeft == 0) {
466 dbgs() << "*** Scheduling failed! ***\n";
467 SuccSU->dump(DAG);
468 dbgs() << " has been released too many times!\n";
469 llvm_unreachable(nullptr);
470 }
471#endif
472
473 --SuccSU->NumPredsLeft;
474}
475
476/// Release Successors of the SU that are in the block or not.
477void SIScheduleBlock::releaseSuccessors(SUnit *SU, bool InOrOutBlock) {
478 for (SDep& Succ : SU->Succs) {
479 SUnit *SuccSU = Succ.getSUnit();
480
Matt Arsenaultfe358062016-07-19 00:35:22 +0000481 if (SuccSU->NodeNum >= DAG->SUnits.size())
482 continue;
483
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000484 if (BC->isSUInBlock(SuccSU, ID) != InOrOutBlock)
485 continue;
486
487 releaseSucc(SU, &Succ);
488 if (SuccSU->NumPredsLeft == 0 && InOrOutBlock)
489 TopReadySUs.push_back(SuccSU);
490 }
491}
492
493void SIScheduleBlock::nodeScheduled(SUnit *SU) {
494 // Is in TopReadySUs
495 assert (!SU->NumPredsLeft);
Eugene Zelenko6a9226d2016-12-12 22:23:53 +0000496 std::vector<SUnit *>::iterator I = llvm::find(TopReadySUs, SU);
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000497 if (I == TopReadySUs.end()) {
498 dbgs() << "Data Structure Bug in SI Scheduler\n";
499 llvm_unreachable(nullptr);
500 }
501 TopReadySUs.erase(I);
502
503 releaseSuccessors(SU, true);
504 // Scheduling this node will trigger a wait,
505 // thus propagate to other instructions that they do not need to wait either.
506 if (HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]])
507 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
508
509 if (DAG->IsLowLatencySU[SU->NodeNum]) {
510 for (SDep& Succ : SU->Succs) {
511 std::map<unsigned, unsigned>::iterator I =
512 NodeNum2Index.find(Succ.getSUnit()->NodeNum);
513 if (I != NodeNum2Index.end())
514 HasLowLatencyNonWaitedParent[I->second] = 1;
515 }
516 }
517 SU->isScheduled = true;
518}
519
520void SIScheduleBlock::finalizeUnits() {
521 // We remove links from outside blocks to enable scheduling inside the block.
522 for (SUnit* SU : SUnits) {
523 releaseSuccessors(SU, false);
524 if (DAG->IsHighLatencySU[SU->NodeNum])
525 HighLatencyBlock = true;
526 }
527 HasLowLatencyNonWaitedParent.resize(SUnits.size(), 0);
528}
529
530// we maintain ascending order of IDs
531void SIScheduleBlock::addPred(SIScheduleBlock *Pred) {
532 unsigned PredID = Pred->getID();
533
534 // Check if not already predecessor.
535 for (SIScheduleBlock* P : Preds) {
536 if (PredID == P->getID())
537 return;
538 }
539 Preds.push_back(Pred);
540
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000541 assert(none_of(Succs,
542 [=](SIScheduleBlock *S) { return PredID == S->getID(); }) &&
543 "Loop in the Block Graph!");
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000544}
545
546void SIScheduleBlock::addSucc(SIScheduleBlock *Succ) {
547 unsigned SuccID = Succ->getID();
548
549 // Check if not already predecessor.
550 for (SIScheduleBlock* S : Succs) {
551 if (SuccID == S->getID())
552 return;
553 }
554 if (Succ->isHighLatencyBlock())
555 ++NumHighLatencySuccessors;
556 Succs.push_back(Succ);
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000557 assert(none_of(Preds,
558 [=](SIScheduleBlock *P) { return SuccID == P->getID(); }) &&
559 "Loop in the Block Graph!");
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000560}
561
562#ifndef NDEBUG
563void SIScheduleBlock::printDebug(bool full) {
564 dbgs() << "Block (" << ID << ")\n";
565 if (!full)
566 return;
567
568 dbgs() << "\nContains High Latency Instruction: "
569 << HighLatencyBlock << '\n';
570 dbgs() << "\nDepends On:\n";
571 for (SIScheduleBlock* P : Preds) {
572 P->printDebug(false);
573 }
574
575 dbgs() << "\nSuccessors:\n";
576 for (SIScheduleBlock* S : Succs) {
577 S->printDebug(false);
578 }
579
580 if (Scheduled) {
581 dbgs() << "LiveInPressure " << LiveInPressure[DAG->getSGPRSetID()] << ' '
582 << LiveInPressure[DAG->getVGPRSetID()] << '\n';
583 dbgs() << "LiveOutPressure " << LiveOutPressure[DAG->getSGPRSetID()] << ' '
584 << LiveOutPressure[DAG->getVGPRSetID()] << "\n\n";
585 dbgs() << "LiveIns:\n";
586 for (unsigned Reg : LiveInRegs)
587 dbgs() << PrintVRegOrUnit(Reg, DAG->getTRI()) << ' ';
588
589 dbgs() << "\nLiveOuts:\n";
590 for (unsigned Reg : LiveOutRegs)
591 dbgs() << PrintVRegOrUnit(Reg, DAG->getTRI()) << ' ';
592 }
593
594 dbgs() << "\nInstructions:\n";
595 if (!Scheduled) {
596 for (SUnit* SU : SUnits) {
597 SU->dump(DAG);
598 }
599 } else {
600 for (SUnit* SU : SUnits) {
601 SU->dump(DAG);
602 }
603 }
604
Eugene Zelenko6a9226d2016-12-12 22:23:53 +0000605 dbgs() << "///////////////////////\n";
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000606}
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000607#endif
608
609// SIScheduleBlockCreator //
610
611SIScheduleBlockCreator::SIScheduleBlockCreator(SIScheduleDAGMI *DAG) :
612DAG(DAG) {
613}
614
Eugene Zelenko6a9226d2016-12-12 22:23:53 +0000615SIScheduleBlockCreator::~SIScheduleBlockCreator() = default;
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000616
617SIScheduleBlocks
618SIScheduleBlockCreator::getBlocks(SISchedulerBlockCreatorVariant BlockVariant) {
619 std::map<SISchedulerBlockCreatorVariant, SIScheduleBlocks>::iterator B =
620 Blocks.find(BlockVariant);
621 if (B == Blocks.end()) {
622 SIScheduleBlocks Res;
623 createBlocksForVariant(BlockVariant);
624 topologicalSort();
625 scheduleInsideBlocks();
626 fillStats();
627 Res.Blocks = CurrentBlocks;
628 Res.TopDownIndex2Block = TopDownIndex2Block;
629 Res.TopDownBlock2Index = TopDownBlock2Index;
630 Blocks[BlockVariant] = Res;
631 return Res;
632 } else {
633 return B->second;
634 }
635}
636
637bool SIScheduleBlockCreator::isSUInBlock(SUnit *SU, unsigned ID) {
638 if (SU->NodeNum >= DAG->SUnits.size())
639 return false;
640 return CurrentBlocks[Node2CurrentBlock[SU->NodeNum]]->getID() == ID;
641}
642
643void SIScheduleBlockCreator::colorHighLatenciesAlone() {
644 unsigned DAGSize = DAG->SUnits.size();
645
646 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
647 SUnit *SU = &DAG->SUnits[i];
648 if (DAG->IsHighLatencySU[SU->NodeNum]) {
649 CurrentColoring[SU->NodeNum] = NextReservedID++;
650 }
651 }
652}
653
654void SIScheduleBlockCreator::colorHighLatenciesGroups() {
655 unsigned DAGSize = DAG->SUnits.size();
656 unsigned NumHighLatencies = 0;
657 unsigned GroupSize;
658 unsigned Color = NextReservedID;
659 unsigned Count = 0;
660 std::set<unsigned> FormingGroup;
661
662 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
663 SUnit *SU = &DAG->SUnits[i];
664 if (DAG->IsHighLatencySU[SU->NodeNum])
665 ++NumHighLatencies;
666 }
667
668 if (NumHighLatencies == 0)
669 return;
670
671 if (NumHighLatencies <= 6)
672 GroupSize = 2;
673 else if (NumHighLatencies <= 12)
674 GroupSize = 3;
675 else
676 GroupSize = 4;
677
678 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
679 SUnit *SU = &DAG->SUnits[i];
680 if (DAG->IsHighLatencySU[SU->NodeNum]) {
681 unsigned CompatibleGroup = true;
682 unsigned ProposedColor = Color;
683 for (unsigned j : FormingGroup) {
684 // TODO: Currently CompatibleGroup will always be false,
685 // because the graph enforces the load order. This
686 // can be fixed, but as keeping the load order is often
687 // good for performance that causes a performance hit (both
688 // the default scheduler and this scheduler).
689 // When this scheduler determines a good load order,
690 // this can be fixed.
691 if (!DAG->canAddEdge(SU, &DAG->SUnits[j]) ||
692 !DAG->canAddEdge(&DAG->SUnits[j], SU))
693 CompatibleGroup = false;
694 }
695 if (!CompatibleGroup || ++Count == GroupSize) {
696 FormingGroup.clear();
697 Color = ++NextReservedID;
698 if (!CompatibleGroup) {
699 ProposedColor = Color;
700 FormingGroup.insert(SU->NodeNum);
701 }
702 Count = 0;
703 } else {
704 FormingGroup.insert(SU->NodeNum);
705 }
706 CurrentColoring[SU->NodeNum] = ProposedColor;
707 }
708 }
709}
710
711void SIScheduleBlockCreator::colorComputeReservedDependencies() {
712 unsigned DAGSize = DAG->SUnits.size();
713 std::map<std::set<unsigned>, unsigned> ColorCombinations;
714
715 CurrentTopDownReservedDependencyColoring.clear();
716 CurrentBottomUpReservedDependencyColoring.clear();
717
718 CurrentTopDownReservedDependencyColoring.resize(DAGSize, 0);
719 CurrentBottomUpReservedDependencyColoring.resize(DAGSize, 0);
720
721 // Traverse TopDown, and give different colors to SUs depending
722 // on which combination of High Latencies they depend on.
723
Tom Stellard4a304b32016-05-03 16:30:56 +0000724 for (unsigned SUNum : DAG->TopDownIndex2SU) {
725 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000726 std::set<unsigned> SUColors;
727
728 // Already given.
729 if (CurrentColoring[SU->NodeNum]) {
730 CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
731 CurrentColoring[SU->NodeNum];
732 continue;
733 }
734
735 for (SDep& PredDep : SU->Preds) {
736 SUnit *Pred = PredDep.getSUnit();
737 if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
738 continue;
739 if (CurrentTopDownReservedDependencyColoring[Pred->NodeNum] > 0)
740 SUColors.insert(CurrentTopDownReservedDependencyColoring[Pred->NodeNum]);
741 }
742 // Color 0 by default.
743 if (SUColors.empty())
744 continue;
745 // Same color than parents.
746 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
747 CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
748 *SUColors.begin();
749 else {
750 std::map<std::set<unsigned>, unsigned>::iterator Pos =
751 ColorCombinations.find(SUColors);
752 if (Pos != ColorCombinations.end()) {
753 CurrentTopDownReservedDependencyColoring[SU->NodeNum] = Pos->second;
754 } else {
755 CurrentTopDownReservedDependencyColoring[SU->NodeNum] =
756 NextNonReservedID;
757 ColorCombinations[SUColors] = NextNonReservedID++;
758 }
759 }
760 }
761
762 ColorCombinations.clear();
763
764 // Same as before, but BottomUp.
765
Tom Stellard4a304b32016-05-03 16:30:56 +0000766 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
767 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000768 std::set<unsigned> SUColors;
769
770 // Already given.
771 if (CurrentColoring[SU->NodeNum]) {
772 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
773 CurrentColoring[SU->NodeNum];
774 continue;
775 }
776
777 for (SDep& SuccDep : SU->Succs) {
778 SUnit *Succ = SuccDep.getSUnit();
779 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
780 continue;
781 if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0)
782 SUColors.insert(CurrentBottomUpReservedDependencyColoring[Succ->NodeNum]);
783 }
784 // Keep color 0.
785 if (SUColors.empty())
786 continue;
787 // Same color than parents.
788 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
789 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
790 *SUColors.begin();
791 else {
792 std::map<std::set<unsigned>, unsigned>::iterator Pos =
793 ColorCombinations.find(SUColors);
794 if (Pos != ColorCombinations.end()) {
795 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = Pos->second;
796 } else {
797 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] =
798 NextNonReservedID;
799 ColorCombinations[SUColors] = NextNonReservedID++;
800 }
801 }
802 }
803}
804
805void SIScheduleBlockCreator::colorAccordingToReservedDependencies() {
806 unsigned DAGSize = DAG->SUnits.size();
807 std::map<std::pair<unsigned, unsigned>, unsigned> ColorCombinations;
808
809 // Every combination of colors given by the top down
810 // and bottom up Reserved node dependency
811
812 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
813 SUnit *SU = &DAG->SUnits[i];
814 std::pair<unsigned, unsigned> SUColors;
815
816 // High latency instructions: already given.
817 if (CurrentColoring[SU->NodeNum])
818 continue;
819
820 SUColors.first = CurrentTopDownReservedDependencyColoring[SU->NodeNum];
821 SUColors.second = CurrentBottomUpReservedDependencyColoring[SU->NodeNum];
822
823 std::map<std::pair<unsigned, unsigned>, unsigned>::iterator Pos =
824 ColorCombinations.find(SUColors);
825 if (Pos != ColorCombinations.end()) {
826 CurrentColoring[SU->NodeNum] = Pos->second;
827 } else {
828 CurrentColoring[SU->NodeNum] = NextNonReservedID;
829 ColorCombinations[SUColors] = NextNonReservedID++;
830 }
831 }
832}
833
834void SIScheduleBlockCreator::colorEndsAccordingToDependencies() {
835 unsigned DAGSize = DAG->SUnits.size();
836 std::vector<int> PendingColoring = CurrentColoring;
837
Valery Pykhtinba3a4de2017-03-27 17:26:40 +0000838 assert(DAGSize >= 1 &&
839 CurrentBottomUpReservedDependencyColoring.size() == DAGSize &&
840 CurrentTopDownReservedDependencyColoring.size() == DAGSize);
841 // If there is no reserved block at all, do nothing. We don't want
842 // everything in one block.
843 if (*std::max_element(CurrentBottomUpReservedDependencyColoring.begin(),
844 CurrentBottomUpReservedDependencyColoring.end()) == 0 &&
845 *std::max_element(CurrentTopDownReservedDependencyColoring.begin(),
846 CurrentTopDownReservedDependencyColoring.end()) == 0)
847 return;
848
Tom Stellard4a304b32016-05-03 16:30:56 +0000849 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
850 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000851 std::set<unsigned> SUColors;
852 std::set<unsigned> SUColorsPending;
853
854 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
855 continue;
856
857 if (CurrentBottomUpReservedDependencyColoring[SU->NodeNum] > 0 ||
858 CurrentTopDownReservedDependencyColoring[SU->NodeNum] > 0)
859 continue;
860
861 for (SDep& SuccDep : SU->Succs) {
862 SUnit *Succ = SuccDep.getSUnit();
863 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
864 continue;
865 if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0 ||
866 CurrentTopDownReservedDependencyColoring[Succ->NodeNum] > 0)
867 SUColors.insert(CurrentColoring[Succ->NodeNum]);
868 SUColorsPending.insert(PendingColoring[Succ->NodeNum]);
869 }
Valery Pykhtinba3a4de2017-03-27 17:26:40 +0000870 // If there is only one child/parent block, and that block
871 // is not among the ones we are removing in this path, then
872 // merge the instruction to that block
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000873 if (SUColors.size() == 1 && SUColorsPending.size() == 1)
874 PendingColoring[SU->NodeNum] = *SUColors.begin();
875 else // TODO: Attribute new colors depending on color
876 // combination of children.
877 PendingColoring[SU->NodeNum] = NextNonReservedID++;
878 }
879 CurrentColoring = PendingColoring;
880}
881
882
883void SIScheduleBlockCreator::colorForceConsecutiveOrderInGroup() {
884 unsigned DAGSize = DAG->SUnits.size();
885 unsigned PreviousColor;
886 std::set<unsigned> SeenColors;
887
888 if (DAGSize <= 1)
889 return;
890
891 PreviousColor = CurrentColoring[0];
892
893 for (unsigned i = 1, e = DAGSize; i != e; ++i) {
894 SUnit *SU = &DAG->SUnits[i];
895 unsigned CurrentColor = CurrentColoring[i];
896 unsigned PreviousColorSave = PreviousColor;
897 assert(i == SU->NodeNum);
898
899 if (CurrentColor != PreviousColor)
900 SeenColors.insert(PreviousColor);
901 PreviousColor = CurrentColor;
902
903 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
904 continue;
905
906 if (SeenColors.find(CurrentColor) == SeenColors.end())
907 continue;
908
909 if (PreviousColorSave != CurrentColor)
910 CurrentColoring[i] = NextNonReservedID++;
911 else
912 CurrentColoring[i] = CurrentColoring[i-1];
913 }
914}
915
916void SIScheduleBlockCreator::colorMergeConstantLoadsNextGroup() {
917 unsigned DAGSize = DAG->SUnits.size();
918
Tom Stellard4a304b32016-05-03 16:30:56 +0000919 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
920 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000921 std::set<unsigned> SUColors;
922
923 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
924 continue;
925
926 // No predecessor: Vgpr constant loading.
927 // Low latency instructions usually have a predecessor (the address)
928 if (SU->Preds.size() > 0 && !DAG->IsLowLatencySU[SU->NodeNum])
929 continue;
930
931 for (SDep& SuccDep : SU->Succs) {
932 SUnit *Succ = SuccDep.getSUnit();
933 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
934 continue;
935 SUColors.insert(CurrentColoring[Succ->NodeNum]);
936 }
937 if (SUColors.size() == 1)
938 CurrentColoring[SU->NodeNum] = *SUColors.begin();
939 }
940}
941
942void SIScheduleBlockCreator::colorMergeIfPossibleNextGroup() {
943 unsigned DAGSize = DAG->SUnits.size();
944
Tom Stellard4a304b32016-05-03 16:30:56 +0000945 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
946 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000947 std::set<unsigned> SUColors;
948
949 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
950 continue;
951
952 for (SDep& SuccDep : SU->Succs) {
953 SUnit *Succ = SuccDep.getSUnit();
954 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
955 continue;
956 SUColors.insert(CurrentColoring[Succ->NodeNum]);
957 }
958 if (SUColors.size() == 1)
959 CurrentColoring[SU->NodeNum] = *SUColors.begin();
960 }
961}
962
963void SIScheduleBlockCreator::colorMergeIfPossibleNextGroupOnlyForReserved() {
964 unsigned DAGSize = DAG->SUnits.size();
965
Tom Stellard4a304b32016-05-03 16:30:56 +0000966 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
967 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000968 std::set<unsigned> SUColors;
969
970 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
971 continue;
972
973 for (SDep& SuccDep : SU->Succs) {
974 SUnit *Succ = SuccDep.getSUnit();
975 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
976 continue;
977 SUColors.insert(CurrentColoring[Succ->NodeNum]);
978 }
979 if (SUColors.size() == 1 && *SUColors.begin() <= DAGSize)
980 CurrentColoring[SU->NodeNum] = *SUColors.begin();
981 }
982}
983
984void SIScheduleBlockCreator::colorMergeIfPossibleSmallGroupsToNextGroup() {
985 unsigned DAGSize = DAG->SUnits.size();
986 std::map<unsigned, unsigned> ColorCount;
987
Tom Stellard4a304b32016-05-03 16:30:56 +0000988 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
989 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000990 unsigned color = CurrentColoring[SU->NodeNum];
Valery Pykhtine2419dc2017-03-24 17:49:05 +0000991 ++ColorCount[color];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000992 }
993
Tom Stellard4a304b32016-05-03 16:30:56 +0000994 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
995 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +0000996 unsigned color = CurrentColoring[SU->NodeNum];
997 std::set<unsigned> SUColors;
998
999 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1000 continue;
1001
1002 if (ColorCount[color] > 1)
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 && *SUColors.begin() != color) {
1012 --ColorCount[color];
1013 CurrentColoring[SU->NodeNum] = *SUColors.begin();
1014 ++ColorCount[*SUColors.begin()];
1015 }
1016 }
1017}
1018
1019void SIScheduleBlockCreator::cutHugeBlocks() {
1020 // TODO
1021}
1022
1023void SIScheduleBlockCreator::regroupNoUserInstructions() {
1024 unsigned DAGSize = DAG->SUnits.size();
1025 int GroupID = NextNonReservedID++;
1026
Tom Stellard4a304b32016-05-03 16:30:56 +00001027 for (unsigned SUNum : DAG->BottomUpIndex2SU) {
1028 SUnit *SU = &DAG->SUnits[SUNum];
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001029 bool hasSuccessor = false;
1030
1031 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize)
1032 continue;
1033
1034 for (SDep& SuccDep : SU->Succs) {
1035 SUnit *Succ = SuccDep.getSUnit();
1036 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1037 continue;
1038 hasSuccessor = true;
1039 }
1040 if (!hasSuccessor)
1041 CurrentColoring[SU->NodeNum] = GroupID;
1042 }
1043}
1044
1045void SIScheduleBlockCreator::createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant) {
1046 unsigned DAGSize = DAG->SUnits.size();
1047 std::map<unsigned,unsigned> RealID;
1048
1049 CurrentBlocks.clear();
1050 CurrentColoring.clear();
1051 CurrentColoring.resize(DAGSize, 0);
1052 Node2CurrentBlock.clear();
1053
1054 // Restore links previous scheduling variant has overridden.
1055 DAG->restoreSULinksLeft();
1056
1057 NextReservedID = 1;
1058 NextNonReservedID = DAGSize + 1;
1059
1060 DEBUG(dbgs() << "Coloring the graph\n");
1061
1062 if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesGrouped)
1063 colorHighLatenciesGroups();
1064 else
1065 colorHighLatenciesAlone();
1066 colorComputeReservedDependencies();
1067 colorAccordingToReservedDependencies();
1068 colorEndsAccordingToDependencies();
1069 if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesAlonePlusConsecutive)
1070 colorForceConsecutiveOrderInGroup();
1071 regroupNoUserInstructions();
1072 colorMergeConstantLoadsNextGroup();
1073 colorMergeIfPossibleNextGroupOnlyForReserved();
1074
1075 // Put SUs of same color into same block
1076 Node2CurrentBlock.resize(DAGSize, -1);
1077 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1078 SUnit *SU = &DAG->SUnits[i];
1079 unsigned Color = CurrentColoring[SU->NodeNum];
1080 if (RealID.find(Color) == RealID.end()) {
1081 int ID = CurrentBlocks.size();
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001082 BlockPtrs.push_back(llvm::make_unique<SIScheduleBlock>(DAG, this, ID));
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001083 CurrentBlocks.push_back(BlockPtrs.rbegin()->get());
1084 RealID[Color] = ID;
1085 }
1086 CurrentBlocks[RealID[Color]]->addUnit(SU);
1087 Node2CurrentBlock[SU->NodeNum] = RealID[Color];
1088 }
1089
1090 // Build dependencies between blocks.
1091 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1092 SUnit *SU = &DAG->SUnits[i];
1093 int SUID = Node2CurrentBlock[i];
1094 for (SDep& SuccDep : SU->Succs) {
1095 SUnit *Succ = SuccDep.getSUnit();
1096 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize)
1097 continue;
1098 if (Node2CurrentBlock[Succ->NodeNum] != SUID)
1099 CurrentBlocks[SUID]->addSucc(CurrentBlocks[Node2CurrentBlock[Succ->NodeNum]]);
1100 }
1101 for (SDep& PredDep : SU->Preds) {
1102 SUnit *Pred = PredDep.getSUnit();
1103 if (PredDep.isWeak() || Pred->NodeNum >= DAGSize)
1104 continue;
1105 if (Node2CurrentBlock[Pred->NodeNum] != SUID)
1106 CurrentBlocks[SUID]->addPred(CurrentBlocks[Node2CurrentBlock[Pred->NodeNum]]);
1107 }
1108 }
1109
1110 // Free root and leafs of all blocks to enable scheduling inside them.
1111 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1112 SIScheduleBlock *Block = CurrentBlocks[i];
1113 Block->finalizeUnits();
1114 }
1115 DEBUG(
1116 dbgs() << "Blocks created:\n\n";
1117 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1118 SIScheduleBlock *Block = CurrentBlocks[i];
1119 Block->printDebug(true);
1120 }
1121 );
1122}
1123
1124// Two functions taken from Codegen/MachineScheduler.cpp
1125
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001126/// Non-const version.
1127static MachineBasicBlock::iterator
1128nextIfDebug(MachineBasicBlock::iterator I,
1129 MachineBasicBlock::const_iterator End) {
Matt Arsenaultfef7beb2016-12-22 16:06:32 +00001130 for (; I != End; ++I) {
1131 if (!I->isDebugValue())
1132 break;
1133 }
1134 return I;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001135}
1136
1137void SIScheduleBlockCreator::topologicalSort() {
1138 unsigned DAGSize = CurrentBlocks.size();
1139 std::vector<int> WorkList;
1140
1141 DEBUG(dbgs() << "Topological Sort\n");
1142
1143 WorkList.reserve(DAGSize);
1144 TopDownIndex2Block.resize(DAGSize);
1145 TopDownBlock2Index.resize(DAGSize);
1146 BottomUpIndex2Block.resize(DAGSize);
1147
1148 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1149 SIScheduleBlock *Block = CurrentBlocks[i];
1150 unsigned Degree = Block->getSuccs().size();
1151 TopDownBlock2Index[i] = Degree;
1152 if (Degree == 0) {
1153 WorkList.push_back(i);
1154 }
1155 }
1156
1157 int Id = DAGSize;
1158 while (!WorkList.empty()) {
1159 int i = WorkList.back();
1160 SIScheduleBlock *Block = CurrentBlocks[i];
1161 WorkList.pop_back();
1162 TopDownBlock2Index[i] = --Id;
1163 TopDownIndex2Block[Id] = i;
1164 for (SIScheduleBlock* Pred : Block->getPreds()) {
1165 if (!--TopDownBlock2Index[Pred->getID()])
1166 WorkList.push_back(Pred->getID());
1167 }
1168 }
1169
1170#ifndef NDEBUG
1171 // Check correctness of the ordering.
1172 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1173 SIScheduleBlock *Block = CurrentBlocks[i];
1174 for (SIScheduleBlock* Pred : Block->getPreds()) {
1175 assert(TopDownBlock2Index[i] > TopDownBlock2Index[Pred->getID()] &&
1176 "Wrong Top Down topological sorting");
1177 }
1178 }
1179#endif
1180
1181 BottomUpIndex2Block = std::vector<int>(TopDownIndex2Block.rbegin(),
1182 TopDownIndex2Block.rend());
1183}
1184
1185void SIScheduleBlockCreator::scheduleInsideBlocks() {
1186 unsigned DAGSize = CurrentBlocks.size();
1187
1188 DEBUG(dbgs() << "\nScheduling Blocks\n\n");
1189
1190 // We do schedule a valid scheduling such that a Block corresponds
1191 // to a range of instructions.
1192 DEBUG(dbgs() << "First phase: Fast scheduling for Reg Liveness\n");
1193 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1194 SIScheduleBlock *Block = CurrentBlocks[i];
1195 Block->fastSchedule();
1196 }
1197
1198 // Note: the following code, and the part restoring previous position
1199 // is by far the most expensive operation of the Scheduler.
1200
1201 // Do not update CurrentTop.
1202 MachineBasicBlock::iterator CurrentTopFastSched = DAG->getCurrentTop();
1203 std::vector<MachineBasicBlock::iterator> PosOld;
1204 std::vector<MachineBasicBlock::iterator> PosNew;
1205 PosOld.reserve(DAG->SUnits.size());
1206 PosNew.reserve(DAG->SUnits.size());
1207
1208 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1209 int BlockIndice = TopDownIndex2Block[i];
1210 SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
1211 std::vector<SUnit*> SUs = Block->getScheduledUnits();
1212
1213 for (SUnit* SU : SUs) {
1214 MachineInstr *MI = SU->getInstr();
1215 MachineBasicBlock::iterator Pos = MI;
1216 PosOld.push_back(Pos);
1217 if (&*CurrentTopFastSched == MI) {
1218 PosNew.push_back(Pos);
1219 CurrentTopFastSched = nextIfDebug(++CurrentTopFastSched,
1220 DAG->getCurrentBottom());
1221 } else {
1222 // Update the instruction stream.
1223 DAG->getBB()->splice(CurrentTopFastSched, DAG->getBB(), MI);
1224
1225 // Update LiveIntervals.
Simon Pilgrime995a8082016-11-18 11:04:02 +00001226 // Note: Moving all instructions and calling handleMove every time
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001227 // is the most cpu intensive operation of the scheduler.
1228 // It would gain a lot if there was a way to recompute the
1229 // LiveIntervals for the entire scheduling region.
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +00001230 DAG->getLIS()->handleMove(*MI, /*UpdateFlags=*/true);
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001231 PosNew.push_back(CurrentTopFastSched);
1232 }
1233 }
1234 }
1235
1236 // Now we have Block of SUs == Block of MI.
1237 // We do the final schedule for the instructions inside the block.
1238 // The property that all the SUs of the Block are grouped together as MI
1239 // is used for correct reg usage tracking.
1240 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1241 SIScheduleBlock *Block = CurrentBlocks[i];
1242 std::vector<SUnit*> SUs = Block->getScheduledUnits();
1243 Block->schedule((*SUs.begin())->getInstr(), (*SUs.rbegin())->getInstr());
1244 }
1245
1246 DEBUG(dbgs() << "Restoring MI Pos\n");
1247 // Restore old ordering (which prevents a LIS->handleMove bug).
1248 for (unsigned i = PosOld.size(), e = 0; i != e; --i) {
1249 MachineBasicBlock::iterator POld = PosOld[i-1];
1250 MachineBasicBlock::iterator PNew = PosNew[i-1];
1251 if (PNew != POld) {
1252 // Update the instruction stream.
1253 DAG->getBB()->splice(POld, DAG->getBB(), PNew);
1254
1255 // Update LiveIntervals.
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +00001256 DAG->getLIS()->handleMove(*POld, /*UpdateFlags=*/true);
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001257 }
1258 }
1259
1260 DEBUG(
1261 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1262 SIScheduleBlock *Block = CurrentBlocks[i];
1263 Block->printDebug(true);
1264 }
1265 );
1266}
1267
1268void SIScheduleBlockCreator::fillStats() {
1269 unsigned DAGSize = CurrentBlocks.size();
1270
1271 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1272 int BlockIndice = TopDownIndex2Block[i];
1273 SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001274 if (Block->getPreds().empty())
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001275 Block->Depth = 0;
1276 else {
1277 unsigned Depth = 0;
1278 for (SIScheduleBlock *Pred : Block->getPreds()) {
1279 if (Depth < Pred->Depth + 1)
1280 Depth = Pred->Depth + 1;
1281 }
1282 Block->Depth = Depth;
1283 }
1284 }
1285
1286 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
1287 int BlockIndice = BottomUpIndex2Block[i];
1288 SIScheduleBlock *Block = CurrentBlocks[BlockIndice];
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001289 if (Block->getSuccs().empty())
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001290 Block->Height = 0;
1291 else {
1292 unsigned Height = 0;
1293 for (SIScheduleBlock *Succ : Block->getSuccs()) {
1294 if (Height < Succ->Height + 1)
1295 Height = Succ->Height + 1;
1296 }
1297 Block->Height = Height;
1298 }
1299 }
1300}
1301
1302// SIScheduleBlockScheduler //
1303
1304SIScheduleBlockScheduler::SIScheduleBlockScheduler(SIScheduleDAGMI *DAG,
1305 SISchedulerBlockSchedulerVariant Variant,
1306 SIScheduleBlocks BlocksStruct) :
1307 DAG(DAG), Variant(Variant), Blocks(BlocksStruct.Blocks),
1308 LastPosWaitedHighLatency(0), NumBlockScheduled(0), VregCurrentUsage(0),
1309 SregCurrentUsage(0), maxVregUsage(0), maxSregUsage(0) {
1310
1311 // Fill the usage of every output
1312 // Warning: while by construction we always have a link between two blocks
1313 // when one needs a result from the other, the number of users of an output
1314 // is not the sum of child blocks having as input the same virtual register.
1315 // Here is an example. A produces x and y. B eats x and produces x'.
1316 // C eats x' and y. The register coalescer may have attributed the same
1317 // virtual register to x and x'.
1318 // To count accurately, we do a topological sort. In case the register is
1319 // found for several parents, we increment the usage of the one with the
1320 // highest topological index.
1321 LiveOutRegsNumUsages.resize(Blocks.size());
1322 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1323 SIScheduleBlock *Block = Blocks[i];
1324 for (unsigned Reg : Block->getInRegs()) {
1325 bool Found = false;
1326 int topoInd = -1;
1327 for (SIScheduleBlock* Pred: Block->getPreds()) {
1328 std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1329 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1330
1331 if (RegPos != PredOutRegs.end()) {
1332 Found = true;
1333 if (topoInd < BlocksStruct.TopDownBlock2Index[Pred->getID()]) {
1334 topoInd = BlocksStruct.TopDownBlock2Index[Pred->getID()];
1335 }
1336 }
1337 }
1338
1339 if (!Found)
1340 continue;
1341
1342 int PredID = BlocksStruct.TopDownIndex2Block[topoInd];
Valery Pykhtine2419dc2017-03-24 17:49:05 +00001343 ++LiveOutRegsNumUsages[PredID][Reg];
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001344 }
1345 }
1346
1347 LastPosHighLatencyParentScheduled.resize(Blocks.size(), 0);
1348 BlockNumPredsLeft.resize(Blocks.size());
1349 BlockNumSuccsLeft.resize(Blocks.size());
1350
1351 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1352 SIScheduleBlock *Block = Blocks[i];
1353 BlockNumPredsLeft[i] = Block->getPreds().size();
1354 BlockNumSuccsLeft[i] = Block->getSuccs().size();
1355 }
1356
1357#ifndef NDEBUG
1358 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1359 SIScheduleBlock *Block = Blocks[i];
1360 assert(Block->getID() == i);
1361 }
1362#endif
1363
1364 std::set<unsigned> InRegs = DAG->getInRegs();
1365 addLiveRegs(InRegs);
1366
Valery Pykhtinf70f6832017-03-27 17:06:36 +00001367 // Increase LiveOutRegsNumUsages for blocks
1368 // producing registers consumed in another
1369 // scheduling region.
1370 for (unsigned Reg : DAG->getOutRegs()) {
1371 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1372 // Do reverse traversal
1373 int ID = BlocksStruct.TopDownIndex2Block[Blocks.size()-1-i];
1374 SIScheduleBlock *Block = Blocks[ID];
1375 const std::set<unsigned> &OutRegs = Block->getOutRegs();
1376
1377 if (OutRegs.find(Reg) == OutRegs.end())
1378 continue;
1379
1380 ++LiveOutRegsNumUsages[ID][Reg];
1381 break;
1382 }
1383 }
1384
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001385 // Fill LiveRegsConsumers for regs that were already
1386 // defined before scheduling.
1387 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1388 SIScheduleBlock *Block = Blocks[i];
1389 for (unsigned Reg : Block->getInRegs()) {
1390 bool Found = false;
1391 for (SIScheduleBlock* Pred: Block->getPreds()) {
1392 std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1393 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1394
1395 if (RegPos != PredOutRegs.end()) {
1396 Found = true;
1397 break;
1398 }
1399 }
1400
Valery Pykhtine2419dc2017-03-24 17:49:05 +00001401 if (!Found)
1402 ++LiveRegsConsumers[Reg];
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001403 }
1404 }
1405
1406 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1407 SIScheduleBlock *Block = Blocks[i];
1408 if (BlockNumPredsLeft[i] == 0) {
1409 ReadyBlocks.push_back(Block);
1410 }
1411 }
1412
1413 while (SIScheduleBlock *Block = pickBlock()) {
1414 BlocksScheduled.push_back(Block);
1415 blockScheduled(Block);
1416 }
1417
1418 DEBUG(
1419 dbgs() << "Block Order:";
1420 for (SIScheduleBlock* Block : BlocksScheduled) {
1421 dbgs() << ' ' << Block->getID();
1422 }
Valery Pykhtin57ab6992017-03-24 16:37:48 +00001423 dbgs() << '\n';
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001424 );
1425}
1426
1427bool SIScheduleBlockScheduler::tryCandidateLatency(SIBlockSchedCandidate &Cand,
1428 SIBlockSchedCandidate &TryCand) {
1429 if (!Cand.isValid()) {
1430 TryCand.Reason = NodeOrder;
1431 return true;
1432 }
1433
1434 // Try to hide high latencies.
1435 if (tryLess(TryCand.LastPosHighLatParentScheduled,
1436 Cand.LastPosHighLatParentScheduled, TryCand, Cand, Latency))
1437 return true;
1438 // Schedule high latencies early so you can hide them better.
1439 if (tryGreater(TryCand.IsHighLatency, Cand.IsHighLatency,
1440 TryCand, Cand, Latency))
1441 return true;
1442 if (TryCand.IsHighLatency && tryGreater(TryCand.Height, Cand.Height,
1443 TryCand, Cand, Depth))
1444 return true;
1445 if (tryGreater(TryCand.NumHighLatencySuccessors,
1446 Cand.NumHighLatencySuccessors,
1447 TryCand, Cand, Successor))
1448 return true;
1449 return false;
1450}
1451
1452bool SIScheduleBlockScheduler::tryCandidateRegUsage(SIBlockSchedCandidate &Cand,
1453 SIBlockSchedCandidate &TryCand) {
1454 if (!Cand.isValid()) {
1455 TryCand.Reason = NodeOrder;
1456 return true;
1457 }
1458
1459 if (tryLess(TryCand.VGPRUsageDiff > 0, Cand.VGPRUsageDiff > 0,
1460 TryCand, Cand, RegUsage))
1461 return true;
1462 if (tryGreater(TryCand.NumSuccessors > 0,
1463 Cand.NumSuccessors > 0,
1464 TryCand, Cand, Successor))
1465 return true;
1466 if (tryGreater(TryCand.Height, Cand.Height, TryCand, Cand, Depth))
1467 return true;
1468 if (tryLess(TryCand.VGPRUsageDiff, Cand.VGPRUsageDiff,
1469 TryCand, Cand, RegUsage))
1470 return true;
1471 return false;
1472}
1473
1474SIScheduleBlock *SIScheduleBlockScheduler::pickBlock() {
1475 SIBlockSchedCandidate Cand;
1476 std::vector<SIScheduleBlock*>::iterator Best;
1477 SIScheduleBlock *Block;
1478 if (ReadyBlocks.empty())
1479 return nullptr;
1480
1481 DAG->fillVgprSgprCost(LiveRegs.begin(), LiveRegs.end(),
1482 VregCurrentUsage, SregCurrentUsage);
1483 if (VregCurrentUsage > maxVregUsage)
1484 maxVregUsage = VregCurrentUsage;
Valery Pykhtinf7d10232017-03-24 16:45:50 +00001485 if (SregCurrentUsage > maxSregUsage)
1486 maxSregUsage = SregCurrentUsage;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001487 DEBUG(
1488 dbgs() << "Picking New Blocks\n";
1489 dbgs() << "Available: ";
1490 for (SIScheduleBlock* Block : ReadyBlocks)
1491 dbgs() << Block->getID() << ' ';
1492 dbgs() << "\nCurrent Live:\n";
1493 for (unsigned Reg : LiveRegs)
1494 dbgs() << PrintVRegOrUnit(Reg, DAG->getTRI()) << ' ';
1495 dbgs() << '\n';
1496 dbgs() << "Current VGPRs: " << VregCurrentUsage << '\n';
1497 dbgs() << "Current SGPRs: " << SregCurrentUsage << '\n';
1498 );
1499
1500 Cand.Block = nullptr;
1501 for (std::vector<SIScheduleBlock*>::iterator I = ReadyBlocks.begin(),
1502 E = ReadyBlocks.end(); I != E; ++I) {
1503 SIBlockSchedCandidate TryCand;
1504 TryCand.Block = *I;
1505 TryCand.IsHighLatency = TryCand.Block->isHighLatencyBlock();
1506 TryCand.VGPRUsageDiff =
1507 checkRegUsageImpact(TryCand.Block->getInRegs(),
1508 TryCand.Block->getOutRegs())[DAG->getVGPRSetID()];
1509 TryCand.NumSuccessors = TryCand.Block->getSuccs().size();
1510 TryCand.NumHighLatencySuccessors =
1511 TryCand.Block->getNumHighLatencySuccessors();
1512 TryCand.LastPosHighLatParentScheduled =
1513 (unsigned int) std::max<int> (0,
1514 LastPosHighLatencyParentScheduled[TryCand.Block->getID()] -
1515 LastPosWaitedHighLatency);
1516 TryCand.Height = TryCand.Block->Height;
1517 // Try not to increase VGPR usage too much, else we may spill.
1518 if (VregCurrentUsage > 120 ||
1519 Variant != SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage) {
1520 if (!tryCandidateRegUsage(Cand, TryCand) &&
1521 Variant != SISchedulerBlockSchedulerVariant::BlockRegUsage)
1522 tryCandidateLatency(Cand, TryCand);
1523 } else {
1524 if (!tryCandidateLatency(Cand, TryCand))
1525 tryCandidateRegUsage(Cand, TryCand);
1526 }
1527 if (TryCand.Reason != NoCand) {
1528 Cand.setBest(TryCand);
1529 Best = I;
1530 DEBUG(dbgs() << "Best Current Choice: " << Cand.Block->getID() << ' '
1531 << getReasonStr(Cand.Reason) << '\n');
1532 }
1533 }
1534
1535 DEBUG(
1536 dbgs() << "Picking: " << Cand.Block->getID() << '\n';
1537 dbgs() << "Is a block with high latency instruction: "
1538 << (Cand.IsHighLatency ? "yes\n" : "no\n");
1539 dbgs() << "Position of last high latency dependency: "
1540 << Cand.LastPosHighLatParentScheduled << '\n';
1541 dbgs() << "VGPRUsageDiff: " << Cand.VGPRUsageDiff << '\n';
1542 dbgs() << '\n';
1543 );
1544
1545 Block = Cand.Block;
1546 ReadyBlocks.erase(Best);
1547 return Block;
1548}
1549
1550// Tracking of currently alive registers to determine VGPR Usage.
1551
1552void SIScheduleBlockScheduler::addLiveRegs(std::set<unsigned> &Regs) {
1553 for (unsigned Reg : Regs) {
1554 // For now only track virtual registers.
1555 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1556 continue;
1557 // If not already in the live set, then add it.
1558 (void) LiveRegs.insert(Reg);
1559 }
1560}
1561
1562void SIScheduleBlockScheduler::decreaseLiveRegs(SIScheduleBlock *Block,
1563 std::set<unsigned> &Regs) {
1564 for (unsigned Reg : Regs) {
1565 // For now only track virtual registers.
1566 std::set<unsigned>::iterator Pos = LiveRegs.find(Reg);
1567 assert (Pos != LiveRegs.end() && // Reg must be live.
1568 LiveRegsConsumers.find(Reg) != LiveRegsConsumers.end() &&
1569 LiveRegsConsumers[Reg] >= 1);
1570 --LiveRegsConsumers[Reg];
1571 if (LiveRegsConsumers[Reg] == 0)
1572 LiveRegs.erase(Pos);
1573 }
1574}
1575
1576void SIScheduleBlockScheduler::releaseBlockSuccs(SIScheduleBlock *Parent) {
1577 for (SIScheduleBlock* Block : Parent->getSuccs()) {
1578 --BlockNumPredsLeft[Block->getID()];
1579 if (BlockNumPredsLeft[Block->getID()] == 0) {
1580 ReadyBlocks.push_back(Block);
1581 }
1582 // TODO: Improve check. When the dependency between the high latency
1583 // instructions and the instructions of the other blocks are WAR or WAW
1584 // there will be no wait triggered. We would like these cases to not
1585 // update LastPosHighLatencyParentScheduled.
1586 if (Parent->isHighLatencyBlock())
1587 LastPosHighLatencyParentScheduled[Block->getID()] = NumBlockScheduled;
1588 }
1589}
1590
1591void SIScheduleBlockScheduler::blockScheduled(SIScheduleBlock *Block) {
1592 decreaseLiveRegs(Block, Block->getInRegs());
1593 addLiveRegs(Block->getOutRegs());
1594 releaseBlockSuccs(Block);
1595 for (std::map<unsigned, unsigned>::iterator RegI =
1596 LiveOutRegsNumUsages[Block->getID()].begin(),
1597 E = LiveOutRegsNumUsages[Block->getID()].end(); RegI != E; ++RegI) {
1598 std::pair<unsigned, unsigned> RegP = *RegI;
Valery Pykhtine2419dc2017-03-24 17:49:05 +00001599 // We produce this register, thus it must not be previously alive.
1600 assert(LiveRegsConsumers.find(RegP.first) == LiveRegsConsumers.end() ||
1601 LiveRegsConsumers[RegP.first] == 0);
1602 LiveRegsConsumers[RegP.first] += RegP.second;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001603 }
1604 if (LastPosHighLatencyParentScheduled[Block->getID()] >
1605 (unsigned)LastPosWaitedHighLatency)
1606 LastPosWaitedHighLatency =
1607 LastPosHighLatencyParentScheduled[Block->getID()];
1608 ++NumBlockScheduled;
1609}
1610
1611std::vector<int>
1612SIScheduleBlockScheduler::checkRegUsageImpact(std::set<unsigned> &InRegs,
1613 std::set<unsigned> &OutRegs) {
1614 std::vector<int> DiffSetPressure;
1615 DiffSetPressure.assign(DAG->getTRI()->getNumRegPressureSets(), 0);
1616
1617 for (unsigned Reg : InRegs) {
1618 // For now only track virtual registers.
1619 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1620 continue;
1621 if (LiveRegsConsumers[Reg] > 1)
1622 continue;
1623 PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1624 for (; PSetI.isValid(); ++PSetI) {
1625 DiffSetPressure[*PSetI] -= PSetI.getWeight();
1626 }
1627 }
1628
1629 for (unsigned Reg : OutRegs) {
1630 // For now only track virtual registers.
1631 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1632 continue;
1633 PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg);
1634 for (; PSetI.isValid(); ++PSetI) {
1635 DiffSetPressure[*PSetI] += PSetI.getWeight();
1636 }
1637 }
1638
1639 return DiffSetPressure;
1640}
1641
1642// SIScheduler //
1643
1644struct SIScheduleBlockResult
1645SIScheduler::scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant,
1646 SISchedulerBlockSchedulerVariant ScheduleVariant) {
1647 SIScheduleBlocks Blocks = BlockCreator.getBlocks(BlockVariant);
1648 SIScheduleBlockScheduler Scheduler(DAG, ScheduleVariant, Blocks);
1649 std::vector<SIScheduleBlock*> ScheduledBlocks;
1650 struct SIScheduleBlockResult Res;
1651
1652 ScheduledBlocks = Scheduler.getBlocks();
1653
1654 for (unsigned b = 0; b < ScheduledBlocks.size(); ++b) {
1655 SIScheduleBlock *Block = ScheduledBlocks[b];
1656 std::vector<SUnit*> SUs = Block->getScheduledUnits();
1657
1658 for (SUnit* SU : SUs)
1659 Res.SUs.push_back(SU->NodeNum);
1660 }
1661
1662 Res.MaxSGPRUsage = Scheduler.getSGPRUsage();
1663 Res.MaxVGPRUsage = Scheduler.getVGPRUsage();
1664 return Res;
1665}
1666
1667// SIScheduleDAGMI //
1668
1669SIScheduleDAGMI::SIScheduleDAGMI(MachineSchedContext *C) :
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001670 ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C)) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001671 SITII = static_cast<const SIInstrInfo*>(TII);
1672 SITRI = static_cast<const SIRegisterInfo*>(TRI);
1673
Tom Stellard7c463c92016-08-26 21:16:37 +00001674 VGPRSetID = SITRI->getVGPRPressureSet();
1675 SGPRSetID = SITRI->getSGPRPressureSet();
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001676}
1677
Eugene Zelenko6a9226d2016-12-12 22:23:53 +00001678SIScheduleDAGMI::~SIScheduleDAGMI() = default;
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001679
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001680// Code adapted from scheduleDAG.cpp
1681// Does a topological sort over the SUs.
1682// Both TopDown and BottomUp
1683void SIScheduleDAGMI::topologicalSort() {
Tom Stellard1d3940e2016-06-09 23:48:02 +00001684 Topo.InitDAGTopologicalSorting();
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001685
Tom Stellard1d3940e2016-06-09 23:48:02 +00001686 TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());
1687 BottomUpIndex2SU = std::vector<int>(Topo.rbegin(), Topo.rend());
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001688}
1689
1690// Move low latencies further from their user without
1691// increasing SGPR usage (in general)
1692// This is to be replaced by a better pass that would
1693// take into account SGPR usage (based on VGPR Usage
1694// and the corresponding wavefront count), that would
1695// try to merge groups of loads if it make sense, etc
1696void SIScheduleDAGMI::moveLowLatencies() {
1697 unsigned DAGSize = SUnits.size();
1698 int LastLowLatencyUser = -1;
1699 int LastLowLatencyPos = -1;
1700
1701 for (unsigned i = 0, e = ScheduledSUnits.size(); i != e; ++i) {
1702 SUnit *SU = &SUnits[ScheduledSUnits[i]];
1703 bool IsLowLatencyUser = false;
1704 unsigned MinPos = 0;
1705
1706 for (SDep& PredDep : SU->Preds) {
1707 SUnit *Pred = PredDep.getSUnit();
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001708 if (SITII->isLowLatencyInstruction(*Pred->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001709 IsLowLatencyUser = true;
1710 }
1711 if (Pred->NodeNum >= DAGSize)
1712 continue;
1713 unsigned PredPos = ScheduledSUnitsInv[Pred->NodeNum];
1714 if (PredPos >= MinPos)
1715 MinPos = PredPos + 1;
1716 }
1717
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001718 if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001719 unsigned BestPos = LastLowLatencyUser + 1;
1720 if ((int)BestPos <= LastLowLatencyPos)
1721 BestPos = LastLowLatencyPos + 1;
1722 if (BestPos < MinPos)
1723 BestPos = MinPos;
1724 if (BestPos < i) {
1725 for (unsigned u = i; u > BestPos; --u) {
1726 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1727 ScheduledSUnits[u] = ScheduledSUnits[u-1];
1728 }
1729 ScheduledSUnits[BestPos] = SU->NodeNum;
1730 ScheduledSUnitsInv[SU->NodeNum] = BestPos;
1731 }
1732 LastLowLatencyPos = BestPos;
1733 if (IsLowLatencyUser)
1734 LastLowLatencyUser = BestPos;
1735 } else if (IsLowLatencyUser) {
1736 LastLowLatencyUser = i;
1737 // Moves COPY instructions on which depends
1738 // the low latency instructions too.
1739 } else if (SU->getInstr()->getOpcode() == AMDGPU::COPY) {
1740 bool CopyForLowLat = false;
1741 for (SDep& SuccDep : SU->Succs) {
1742 SUnit *Succ = SuccDep.getSUnit();
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001743 if (SITII->isLowLatencyInstruction(*Succ->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001744 CopyForLowLat = true;
1745 }
1746 }
1747 if (!CopyForLowLat)
1748 continue;
1749 if (MinPos < i) {
1750 for (unsigned u = i; u > MinPos; --u) {
1751 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1752 ScheduledSUnits[u] = ScheduledSUnits[u-1];
1753 }
1754 ScheduledSUnits[MinPos] = SU->NodeNum;
1755 ScheduledSUnitsInv[SU->NodeNum] = MinPos;
1756 }
1757 }
1758 }
1759}
1760
1761void SIScheduleDAGMI::restoreSULinksLeft() {
1762 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1763 SUnits[i].isScheduled = false;
1764 SUnits[i].WeakPredsLeft = SUnitsLinksBackup[i].WeakPredsLeft;
1765 SUnits[i].NumPredsLeft = SUnitsLinksBackup[i].NumPredsLeft;
1766 SUnits[i].WeakSuccsLeft = SUnitsLinksBackup[i].WeakSuccsLeft;
1767 SUnits[i].NumSuccsLeft = SUnitsLinksBackup[i].NumSuccsLeft;
1768 }
1769}
1770
1771// Return the Vgpr and Sgpr usage corresponding to some virtual registers.
1772template<typename _Iterator> void
1773SIScheduleDAGMI::fillVgprSgprCost(_Iterator First, _Iterator End,
1774 unsigned &VgprUsage, unsigned &SgprUsage) {
1775 VgprUsage = 0;
1776 SgprUsage = 0;
1777 for (_Iterator RegI = First; RegI != End; ++RegI) {
1778 unsigned Reg = *RegI;
1779 // For now only track virtual registers
1780 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1781 continue;
1782 PSetIterator PSetI = MRI.getPressureSets(Reg);
1783 for (; PSetI.isValid(); ++PSetI) {
1784 if (*PSetI == VGPRSetID)
1785 VgprUsage += PSetI.getWeight();
1786 else if (*PSetI == SGPRSetID)
1787 SgprUsage += PSetI.getWeight();
1788 }
1789 }
1790}
1791
1792void SIScheduleDAGMI::schedule()
1793{
1794 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1795 SIScheduleBlockResult Best, Temp;
1796 DEBUG(dbgs() << "Preparing Scheduling\n");
1797
1798 buildDAGWithRegPressure();
1799 DEBUG(
1800 for(SUnit& SU : SUnits)
1801 SU.dumpAll(this)
1802 );
1803
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001804 topologicalSort();
1805 findRootsAndBiasEdges(TopRoots, BotRoots);
1806 // We reuse several ScheduleDAGMI and ScheduleDAGMILive
1807 // functions, but to make them happy we must initialize
1808 // the default Scheduler implementation (even if we do not
1809 // run it)
1810 SchedImpl->initialize(this);
1811 initQueues(TopRoots, BotRoots);
1812
1813 // Fill some stats to help scheduling.
1814
1815 SUnitsLinksBackup = SUnits;
1816 IsLowLatencySU.clear();
1817 LowLatencyOffset.clear();
1818 IsHighLatencySU.clear();
1819
1820 IsLowLatencySU.resize(SUnits.size(), 0);
1821 LowLatencyOffset.resize(SUnits.size(), 0);
1822 IsHighLatencySU.resize(SUnits.size(), 0);
1823
1824 for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
1825 SUnit *SU = &SUnits[i];
Chad Rosierc27a18f2016-03-09 16:00:35 +00001826 unsigned BaseLatReg;
1827 int64_t OffLatReg;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001828 if (SITII->isLowLatencyInstruction(*SU->getInstr())) {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001829 IsLowLatencySU[i] = 1;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001830 if (SITII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseLatReg, OffLatReg,
1831 TRI))
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001832 LowLatencyOffset[i] = OffLatReg;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001833 } else if (SITII->isHighLatencyInstruction(*SU->getInstr()))
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001834 IsHighLatencySU[i] = 1;
1835 }
1836
1837 SIScheduler Scheduler(this);
1838 Best = Scheduler.scheduleVariant(SISchedulerBlockCreatorVariant::LatenciesAlone,
1839 SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage);
Matt Arsenault105c2a22016-07-01 18:03:46 +00001840
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001841 // if VGPR usage is extremely high, try other good performing variants
1842 // which could lead to lower VGPR usage
1843 if (Best.MaxVGPRUsage > 180) {
Benjamin Kramer80e3d5b2017-03-24 17:53:06 +00001844 static const std::pair<SISchedulerBlockCreatorVariant,
1845 SISchedulerBlockSchedulerVariant>
Benjamin Kramerc06d6722017-03-24 14:11:47 +00001846 Variants[] = {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001847 { LatenciesAlone, BlockRegUsageLatency },
1848// { LatenciesAlone, BlockRegUsage },
1849 { LatenciesGrouped, BlockLatencyRegUsage },
1850// { LatenciesGrouped, BlockRegUsageLatency },
1851// { LatenciesGrouped, BlockRegUsage },
1852 { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1853// { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1854// { LatenciesAlonePlusConsecutive, BlockRegUsage }
1855 };
1856 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1857 Temp = Scheduler.scheduleVariant(v.first, v.second);
1858 if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
1859 Best = Temp;
1860 }
1861 }
1862 // if VGPR usage is still extremely high, we may spill. Try other variants
1863 // which are less performing, but that could lead to lower VGPR usage.
1864 if (Best.MaxVGPRUsage > 200) {
Benjamin Kramer80e3d5b2017-03-24 17:53:06 +00001865 static const std::pair<SISchedulerBlockCreatorVariant,
1866 SISchedulerBlockSchedulerVariant>
Benjamin Kramerc06d6722017-03-24 14:11:47 +00001867 Variants[] = {
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001868// { LatenciesAlone, BlockRegUsageLatency },
1869 { LatenciesAlone, BlockRegUsage },
1870// { LatenciesGrouped, BlockLatencyRegUsage },
1871 { LatenciesGrouped, BlockRegUsageLatency },
1872 { LatenciesGrouped, BlockRegUsage },
1873// { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage },
1874 { LatenciesAlonePlusConsecutive, BlockRegUsageLatency },
1875 { LatenciesAlonePlusConsecutive, BlockRegUsage }
1876 };
1877 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1878 Temp = Scheduler.scheduleVariant(v.first, v.second);
1879 if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage)
1880 Best = Temp;
1881 }
1882 }
Matt Arsenault105c2a22016-07-01 18:03:46 +00001883
Nicolai Haehnle02c32912016-01-13 16:10:10 +00001884 ScheduledSUnits = Best.SUs;
1885 ScheduledSUnitsInv.resize(SUnits.size());
1886
1887 for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) {
1888 ScheduledSUnitsInv[ScheduledSUnits[i]] = i;
1889 }
1890
1891 moveLowLatencies();
1892
1893 // Tell the outside world about the result of the scheduling.
1894
1895 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1896 TopRPTracker.setPos(CurrentTop);
1897
1898 for (std::vector<unsigned>::iterator I = ScheduledSUnits.begin(),
1899 E = ScheduledSUnits.end(); I != E; ++I) {
1900 SUnit *SU = &SUnits[*I];
1901
1902 scheduleMI(SU, true);
1903
1904 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
1905 << *SU->getInstr());
1906 }
1907
1908 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1909
1910 placeDebugValues();
1911
1912 DEBUG({
1913 unsigned BBNum = begin()->getParent()->getNumber();
1914 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1915 dumpSchedule();
1916 dbgs() << '\n';
1917 });
1918}