LLVM 24.0.0git
SIMachineScheduler.h
Go to the documentation of this file.
1//===-- SIMachineScheduler.h - SI Scheduler Interface -----------*- C++ -*-===//
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#ifndef LLVM_LIB_TARGET_AMDGPU_SIMACHINESCHEDULER_H
15#define LLVM_LIB_TARGET_AMDGPU_SIMACHINESCHEDULER_H
16
20#include <cstdint>
21#include <set>
22#include <vector>
23
24namespace llvm {
25
26class SIInstrInfo;
27class SIScheduleDAGMI;
29
38
40 // The reason for this candidate.
42
43 // Set of reasons that apply to multiple candidates.
45
47
49};
50
55
57 SIScheduleDAGMI *DAG;
59
60 std::vector<SUnit*> SUnits;
61 std::map<unsigned, unsigned> NodeNum2Index;
62 std::vector<SUnit*> TopReadySUs;
63 std::vector<SUnit*> ScheduledSUnits;
64
65 /// The top of the unscheduled zone.
66 IntervalPressure TopPressure;
67 RegPressureTracker TopRPTracker;
68
69 // Pressure: number of said class of registers needed to
70 // store the live virtual and real registers.
71 // We do care only of SGPR32 and VGPR32 and do track only virtual registers.
72 // Pressure of additional registers required inside the block.
73 std::vector<unsigned> InternalAdditionalPressure;
74 // Pressure of input and output registers
75 std::vector<unsigned> LiveInPressure;
76 std::vector<unsigned> LiveOutPressure;
77 // Registers required by the block, and outputs.
78 // We do track only virtual registers.
79 // Note that some registers are not 32 bits,
80 // and thus the pressure is not equal
81 // to the number of live registers.
82 std::set<Register> LiveInRegs;
83 std::set<Register> LiveOutRegs;
84
85 bool Scheduled = false;
86 bool HighLatencyBlock = false;
87
88 std::vector<unsigned> HasLowLatencyNonWaitedParent;
89
90 // Unique ID, the index of the Block in the SIScheduleDAGMI Blocks table.
91 unsigned ID;
92
93 std::vector<SIScheduleBlock*> Preds; // All blocks predecessors.
94 // All blocks successors, and the kind of link
95 std::vector<std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind>> Succs;
96 unsigned NumHighLatencySuccessors = 0;
97
98public:
100 unsigned ID):
101 DAG(DAG), BC(BC), TopRPTracker(TopPressure), ID(ID) {}
102
103 ~SIScheduleBlock() = default;
104
105 unsigned getID() const { return ID; }
106
107 /// Functions for Block construction.
108 void addUnit(SUnit *SU);
109
110 // When all SUs have been added.
111 void finalizeUnits();
112
113 // Add block pred, which has instruction predecessor of SU.
116
117 const std::vector<SIScheduleBlock*>& getPreds() const { return Preds; }
119 getSuccs() const { return Succs; }
120
121 unsigned Height = 0; // Maximum topdown path length to block without outputs
122 unsigned Depth = 0; // Maximum bottomup path length to block without inputs
123
125 return NumHighLatencySuccessors;
126 }
127
128 bool isHighLatencyBlock() { return HighLatencyBlock; }
129
130 // This is approximative.
131 // Ideally should take into accounts some instructions (rcp, etc)
132 // are 4 times slower.
133 int getCost() { return static_cast<int>(SUnits.size()); }
134
135 // The block Predecessors and Successors must be all registered
136 // before fastSchedule().
137 // Fast schedule with no particular requirement.
138 void fastSchedule();
139
140 std::vector<SUnit*> getScheduledUnits() { return ScheduledSUnits; }
141
142 // Complete schedule that will try to minimize reg pressure and
143 // low latencies, and will fill liveins and liveouts.
144 // Needs all MIs to be grouped between BeginBlock and EndBlock.
145 // The MIs can be moved after the scheduling,
146 // it is just used to allow correct track of live registers.
149
150 bool isScheduled() { return Scheduled; }
151
152 std::set<Register> &getInRegs() { return LiveInRegs; }
153 std::set<Register> &getOutRegs() { return LiveOutRegs; }
154
155 void printDebug(bool Full);
156
157private:
158 struct SISchedCandidate : SISchedulerCandidate {
159 // The best SUnit candidate.
160 SUnit *SU = nullptr;
161
162 unsigned SGPRUsage;
163 unsigned VGPRUsage;
164 bool IsLowLatency;
165 unsigned LowLatencyOffset;
166 bool HasLowLatencyNonWaitedParent;
167
168 SISchedCandidate() = default;
169
170 bool isValid() const { return SU; }
171
172 // Copy the status of another candidate without changing policy.
173 void setBest(SISchedCandidate &Best) {
174 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
175 SU = Best.SU;
176 Reason = Best.Reason;
177 SGPRUsage = Best.SGPRUsage;
178 VGPRUsage = Best.VGPRUsage;
179 IsLowLatency = Best.IsLowLatency;
180 LowLatencyOffset = Best.LowLatencyOffset;
181 HasLowLatencyNonWaitedParent = Best.HasLowLatencyNonWaitedParent;
182 }
183 };
184
185 void undoSchedule();
186
187 void undoReleaseSucc(SUnit *SU, SDep *SuccEdge);
188 void releaseSucc(SUnit *SU, SDep *SuccEdge);
189 // InOrOutBlock: restrict to links pointing inside the block (true),
190 // or restrict to links pointing outside the block (false).
191 void releaseSuccessors(SUnit *SU, bool InOrOutBlock);
192
193 void nodeScheduled(SUnit *SU);
194 void tryCandidateTopDown(SISchedCandidate &Cand, SISchedCandidate &TryCand);
195 SUnit* pickNode();
196 void traceCandidate(const SISchedCandidate &Cand);
197 void initRegPressure(MachineBasicBlock::iterator BeginBlock,
199};
200
202 std::vector<SIScheduleBlock*> Blocks;
203 std::vector<int> TopDownIndex2Block;
204 std::vector<int> TopDownBlock2Index;
205};
206
212
214 SIScheduleDAGMI *DAG;
215 // unique_ptr handles freeing memory for us.
216 std::vector<std::unique_ptr<SIScheduleBlock>> BlockPtrs;
218 SIScheduleBlocks> Blocks;
219 std::vector<SIScheduleBlock*> CurrentBlocks;
220 std::vector<int> Node2CurrentBlock;
221
222 // Topological sort
223 // Maps topological index to the node number.
224 std::vector<int> TopDownIndex2Block;
225 std::vector<int> TopDownBlock2Index;
226 std::vector<int> BottomUpIndex2Block;
227
228 // 0 -> Color not given.
229 // 1 to SUnits.size() -> Reserved group (you should only add elements to them).
230 // Above -> Other groups.
231 int NextReservedID;
232 int NextNonReservedID;
233 std::vector<int> CurrentColoring;
234 std::vector<int> CurrentTopDownReservedDependencyColoring;
235 std::vector<int> CurrentBottomUpReservedDependencyColoring;
236
237public:
239
242
243 bool isSUInBlock(SUnit *SU, unsigned ID);
244
245private:
246 // Give a Reserved color to every high latency.
247 void colorHighLatenciesAlone();
248
249 // Create groups of high latencies with a Reserved color.
250 void colorHighLatenciesGroups();
251
252 // Compute coloring for topdown and bottom traversals with
253 // different colors depending on dependencies on Reserved colors.
254 void colorComputeReservedDependencies();
255
256 // Give color to all non-colored SUs according to Reserved groups dependencies.
257 void colorAccordingToReservedDependencies();
258
259 // Divides Blocks having no bottom up or top down dependencies on Reserved groups.
260 // The new colors are computed according to the dependencies on the other blocks
261 // formed with colorAccordingToReservedDependencies.
262 void colorEndsAccordingToDependencies();
263
264 // Cut groups into groups with SUs in consecutive order (except for Reserved groups).
265 void colorForceConsecutiveOrderInGroup();
266
267 // Merge Constant loads that have all their users into another group to the group.
268 // (TODO: else if all their users depend on the same group, put them there)
269 void colorMergeConstantLoadsNextGroup();
270
271 // Merge SUs that have all their users into another group to the group,
272 // but only for Reserved groups.
273 void colorMergeIfPossibleNextGroupOnlyForReserved();
274
275 // Put in one group all instructions with no users in this scheduling region
276 // (we'd want these groups be at the end).
277 void regroupNoUserInstructions();
278
279 // Give Reserved color to export instructions
280 void colorExports();
281
282 void createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant);
283
284 void topologicalSort();
285
286 void scheduleInsideBlocks();
287
288 void fillStats();
289};
290
296
298 SIScheduleDAGMI *DAG;
300 std::vector<SIScheduleBlock*> Blocks;
301
302 std::vector<std::map<Register, unsigned>> LiveOutRegsNumUsages;
303 std::set<Register> LiveRegs;
304 // Num of schedulable unscheduled blocks reading the register.
305 std::map<Register, unsigned> LiveRegsConsumers;
306
307 std::vector<unsigned> LastPosHighLatencyParentScheduled;
308 int LastPosWaitedHighLatency;
309
310 std::vector<SIScheduleBlock*> BlocksScheduled;
311 unsigned NumBlockScheduled;
312 std::vector<SIScheduleBlock*> ReadyBlocks;
313
314 unsigned VregCurrentUsage;
315 unsigned SregCurrentUsage;
316
317 // Currently is only approximation.
318 unsigned maxVregUsage;
319 unsigned maxSregUsage;
320
321 std::vector<unsigned> BlockNumPredsLeft;
322 std::vector<unsigned> BlockNumSuccsLeft;
323
324public:
327 SIScheduleBlocks BlocksStruct);
329
330 std::vector<SIScheduleBlock*> getBlocks() { return BlocksScheduled; }
331
332 unsigned getVGPRUsage() { return maxVregUsage; }
333 unsigned getSGPRUsage() { return maxSregUsage; }
334
335private:
336 struct SIBlockSchedCandidate : SISchedulerCandidate {
337 // The best Block candidate.
338 SIScheduleBlock *Block = nullptr;
339
340 bool IsHighLatency;
341 int VGPRUsageDiff;
342 size_t NumSuccessors;
343 unsigned NumHighLatencySuccessors;
344 unsigned LastPosHighLatParentScheduled;
345 unsigned Height;
346
347 SIBlockSchedCandidate() = default;
348
349 bool isValid() const { return Block; }
350
351 // Copy the status of another candidate without changing policy.
352 void setBest(SIBlockSchedCandidate &Best) {
353 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
354 Block = Best.Block;
355 Reason = Best.Reason;
356 IsHighLatency = Best.IsHighLatency;
357 VGPRUsageDiff = Best.VGPRUsageDiff;
358 NumSuccessors = Best.NumSuccessors;
359 NumHighLatencySuccessors = Best.NumHighLatencySuccessors;
360 LastPosHighLatParentScheduled = Best.LastPosHighLatParentScheduled;
361 Height = Best.Height;
362 }
363 };
364
365 bool tryCandidateLatency(SIBlockSchedCandidate &Cand,
366 SIBlockSchedCandidate &TryCand);
367 bool tryCandidateRegUsage(SIBlockSchedCandidate &Cand,
368 SIBlockSchedCandidate &TryCand);
369 SIScheduleBlock *pickBlock();
370
371 void addLiveRegs(std::set<VirtRegOrUnit> &Regs);
372 void decreaseLiveRegs(SIScheduleBlock *Block, std::set<Register> &Regs);
373 void releaseBlockSuccs(SIScheduleBlock *Parent);
374 void blockScheduled(SIScheduleBlock *Block);
375
376 // Check register pressure change
377 // by scheduling a block with these LiveIn and LiveOut.
378 std::vector<int> checkRegUsageImpact(std::set<Register> &InRegs,
379 std::set<Register> &OutRegs);
380};
381
383 std::vector<unsigned> SUs;
384 unsigned MaxSGPRUsage;
385 unsigned MaxVGPRUsage;
386};
387
389 SIScheduleDAGMI *DAG;
390 SIScheduleBlockCreator BlockCreator;
391
392public:
393 SIScheduler(SIScheduleDAGMI *DAG) : DAG(DAG), BlockCreator(DAG) {}
394
395 ~SIScheduler() = default;
396
399 SISchedulerBlockSchedulerVariant ScheduleVariant);
400};
401
402class SIScheduleDAGMI final : public ScheduleDAGMILive {
403 const SIInstrInfo *SITII;
404
405 std::vector<SUnit> SUnitsLinksBackup;
406
407 // For moveLowLatencies. After all Scheduling variants are tested.
408 std::vector<unsigned> ScheduledSUnits;
409 std::vector<unsigned> ScheduledSUnitsInv;
410
411public:
413
415
416 // Entry point for the schedule.
417 void schedule() override;
418
419 // To init Block's RPTracker.
423
427 LiveIntervals *getLIS() { return LIS; }
429 const TargetRegisterInfo *getTRI() { return TRI; }
431
432 void restoreSULinksLeft();
433
434 template<typename _Iterator> void fillVgprSgprCost(_Iterator First,
435 _Iterator End,
436 unsigned &VgprUsage,
437 unsigned &SgprUsage);
438
439 std::set<VirtRegOrUnit> getInRegs() {
440 std::set<VirtRegOrUnit> InRegs;
441 for (const auto &RegMaskPair : RPTracker.getPressure().LiveInRegs) {
442 InRegs.insert(RegMaskPair.VRegOrUnit);
443 }
444 return InRegs;
445 }
446
447 std::set<VirtRegOrUnit> getOutRegs() {
448 std::set<VirtRegOrUnit> OutRegs;
449 for (const auto &RegMaskPair : RPTracker.getPressure().LiveOutRegs) {
450 OutRegs.insert(RegMaskPair.VRegOrUnit);
451 }
452 return OutRegs;
453 };
454
455private:
456 void topologicalSort();
457 // After scheduling is done, improve low latency placements.
458 void moveLowLatencies();
459
460public:
461 // Some stats for scheduling inside blocks.
462 std::vector<unsigned> IsLowLatencySU;
463 std::vector<unsigned> LowLatencyOffset;
464 std::vector<unsigned> IsHighLatencySU;
465 // Topological sort
466 // Maps topological index to the node number.
467 std::vector<int> TopDownIndex2SU;
468 std::vector<int> BottomUpIndex2SU;
469};
470
471} // end namespace llvm
472
473#endif // LLVM_LIB_TARGET_AMDGPU_SIMACHINESCHEDULER_H
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
MachineInstrBundleIterator< MachineInstr > iterator
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Track the current register pressure at some position in the instruction stream, and remember the high...
bool isSUInBlock(SUnit *SU, unsigned ID)
SIScheduleBlockCreator(SIScheduleDAGMI *DAG)
SIScheduleBlocks getBlocks(SISchedulerBlockCreatorVariant BlockVariant)
SIScheduleBlockScheduler(SIScheduleDAGMI *DAG, SISchedulerBlockSchedulerVariant Variant, SIScheduleBlocks BlocksStruct)
std::vector< SIScheduleBlock * > getBlocks()
unsigned getNumHighLatencySuccessors() const
SIScheduleBlock(SIScheduleDAGMI *DAG, SIScheduleBlockCreator *BC, unsigned ID)
ArrayRef< std::pair< SIScheduleBlock *, SIScheduleBlockLinkKind > > getSuccs() const
~SIScheduleBlock()=default
const std::vector< SIScheduleBlock * > & getPreds() const
void addPred(SIScheduleBlock *Pred)
std::set< Register > & getOutRegs()
std::vector< SUnit * > getScheduledUnits()
void addSucc(SIScheduleBlock *Succ, SIScheduleBlockLinkKind Kind)
void schedule(MachineBasicBlock::iterator BeginBlock, MachineBasicBlock::iterator EndBlock)
void addUnit(SUnit *SU)
Functions for Block construction.
std::set< Register > & getInRegs()
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.
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()
MachineBasicBlock * getBB()
void initRPTracker(RegPressureTracker &RPTracker)
std::set< VirtRegOrUnit > getOutRegs()
~SIScheduleDAGMI() override
const TargetRegisterInfo * getTRI()
std::set< VirtRegOrUnit > getInRegs()
struct SIScheduleBlockResult scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant, SISchedulerBlockSchedulerVariant ScheduleVariant)
~SIScheduler()=default
SIScheduler(SIScheduleDAGMI *DAG)
Scheduling unit. This is a node in the scheduling DAG.
MachineBasicBlock * BB
The block in which to insert instructions.
ScheduleDAGTopologicalSort Topo
Topo - A topological ordering for SUnits which permits fast IsReachable and similar queries.
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
ScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S)
RegisterClassInfo * RegClassInfo
RegPressureTracker RPTracker
MachineBasicBlock::iterator CurrentBottom
The bottom of the unscheduled zone.
MachineBasicBlock::iterator CurrentTop
The top of the unscheduled zone.
This class can compute a topological ordering for SUnits and provides methods for dynamically updatin...
MachineRegisterInfo & MRI
Virtual/real register map.
const TargetRegisterInfo * TRI
Target processor register info.
MachineFunction & MF
Machine function.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
This is an optimization pass for GlobalISel generic memory operations.
SISchedulerBlockSchedulerVariant
SISchedulerBlockCreatorVariant
@ LatenciesAlonePlusConsecutive
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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 > SUs
std::vector< int > TopDownIndex2Block
std::vector< SIScheduleBlock * > Blocks
std::vector< int > TopDownBlock2Index
SIScheduleCandReason Reason
void setRepeat(SIScheduleCandReason R)