LLVM 20.0.0git
AMDGPUIGroupLP.cpp
Go to the documentation of this file.
1//===--- AMDGPUIGroupLP.cpp - AMDGPU IGroupLP ------------===//
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 This file defines a set of schedule DAG mutations that can be used to
10// override default scheduler behavior to enforce specific scheduling patterns.
11// They should be used in cases where runtime performance considerations such as
12// inter-wavefront interactions, mean that compile-time heuristics cannot
13// predict the optimal instruction ordering, or in kernels where optimum
14// instruction scheduling is important enough to warrant manual intervention.
15//
16//===----------------------------------------------------------------------===//
17
18#include "AMDGPUIGroupLP.h"
19#include "AMDGPUTargetMachine.h"
21#include "SIInstrInfo.h"
24#include "llvm/ADT/DenseMap.h"
27
28using namespace llvm;
29
30#define DEBUG_TYPE "igrouplp"
31
32namespace {
33
34static cl::opt<bool> EnableExactSolver(
35 "amdgpu-igrouplp-exact-solver", cl::Hidden,
36 cl::desc("Whether to use the exponential time solver to fit "
37 "the instructions to the pipeline as closely as "
38 "possible."),
39 cl::init(false));
40
41static cl::opt<unsigned> CutoffForExact(
42 "amdgpu-igrouplp-exact-solver-cutoff", cl::init(0), cl::Hidden,
43 cl::desc("The maximum number of scheduling group conflicts "
44 "which we attempt to solve with the exponential time "
45 "exact solver. Problem sizes greater than this will"
46 "be solved by the less accurate greedy algorithm. Selecting "
47 "solver by size is superseded by manually selecting "
48 "the solver (e.g. by amdgpu-igrouplp-exact-solver"));
49
50static cl::opt<uint64_t> MaxBranchesExplored(
51 "amdgpu-igrouplp-exact-solver-max-branches", cl::init(0), cl::Hidden,
52 cl::desc("The amount of branches that we are willing to explore with"
53 "the exact algorithm before giving up."));
54
55static cl::opt<bool> UseCostHeur(
56 "amdgpu-igrouplp-exact-solver-cost-heur", cl::init(true), cl::Hidden,
57 cl::desc("Whether to use the cost heuristic to make choices as we "
58 "traverse the search space using the exact solver. Defaulted "
59 "to on, and if turned off, we will use the node order -- "
60 "attempting to put the later nodes in the later sched groups. "
61 "Experimentally, results are mixed, so this should be set on a "
62 "case-by-case basis."));
63
64// Components of the mask that determines which instruction types may be may be
65// classified into a SchedGroup.
66enum class SchedGroupMask {
67 NONE = 0u,
68 ALU = 1u << 0,
69 VALU = 1u << 1,
70 SALU = 1u << 2,
71 MFMA = 1u << 3,
72 VMEM = 1u << 4,
73 VMEM_READ = 1u << 5,
74 VMEM_WRITE = 1u << 6,
75 DS = 1u << 7,
76 DS_READ = 1u << 8,
77 DS_WRITE = 1u << 9,
78 TRANS = 1u << 10,
79 ALL = ALU | VALU | SALU | MFMA | VMEM | VMEM_READ | VMEM_WRITE | DS |
80 DS_READ | DS_WRITE | TRANS,
81 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ ALL)
82};
83
84class SchedGroup;
85
86// InstructionRule class is used to enact a filter which determines whether or
87// not an SU maps to a given SchedGroup. It contains complementary data
88// structures (e.g Cache) to help those filters.
89class InstructionRule {
90protected:
91 const SIInstrInfo *TII;
92 unsigned SGID;
93 // A cache made available to the Filter to store SUnits for subsequent
94 // invocations of the Filter
95 std::optional<SmallVector<SUnit *, 4>> Cache;
96
97public:
98 virtual bool
99 apply(const SUnit *, const ArrayRef<SUnit *>,
101 return true;
102 };
103
104 InstructionRule(const SIInstrInfo *TII, unsigned SGID,
105 bool NeedsCache = false)
106 : TII(TII), SGID(SGID) {
107 if (NeedsCache) {
108 Cache = SmallVector<SUnit *, 4>();
109 }
110 }
111
112 virtual ~InstructionRule() = default;
113};
114
115using SUnitsToCandidateSGsMap = DenseMap<SUnit *, SmallVector<int, 4>>;
116
117// Classify instructions into groups to enable fine tuned control over the
118// scheduler. These groups may be more specific than current SchedModel
119// instruction classes.
120class SchedGroup {
121private:
122 // Mask that defines which instruction types can be classified into this
123 // SchedGroup. The instruction types correspond to the mask from SCHED_BARRIER
124 // and SCHED_GROUP_BARRIER.
125 SchedGroupMask SGMask;
126
127 // Maximum number of SUnits that can be added to this group.
128 std::optional<unsigned> MaxSize;
129
130 // SchedGroups will only synchronize with other SchedGroups that have the same
131 // SyncID.
132 int SyncID = 0;
133
134 // SGID is used to map instructions to candidate SchedGroups
135 unsigned SGID;
136
137 // The different rules each instruction in this SchedGroup must conform to
139
140 // Count of the number of created SchedGroups, used to initialize SGID.
141 static unsigned NumSchedGroups;
142
143 // Try to add and edge from SU A to SU B.
144 bool tryAddEdge(SUnit *A, SUnit *B);
145
146 // Use SGMask to determine whether we can classify MI as a member of this
147 // SchedGroup object.
148 bool canAddMI(const MachineInstr &MI) const;
149
150public:
151 // Collection of SUnits that are classified as members of this group.
152 SmallVector<SUnit *, 32> Collection;
153
155 const SIInstrInfo *TII;
156
157 // Returns true if SU can be added to this SchedGroup.
158 bool canAddSU(SUnit &SU) const;
159
160 // Add DAG dependencies from all SUnits in this SchedGroup and this SU. If
161 // MakePred is true, SU will be a predecessor of the SUnits in this
162 // SchedGroup, otherwise SU will be a successor.
163 void link(SUnit &SU, bool MakePred = false);
164
165 // Add DAG dependencies and track which edges are added, and the count of
166 // missed edges
167 int link(SUnit &SU, bool MakePred,
168 std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges);
169
170 // Add DAG dependencies from all SUnits in this SchedGroup and this SU.
171 // Use the predicate to determine whether SU should be a predecessor (P =
172 // true) or a successor (P = false) of this SchedGroup.
173 void link(SUnit &SU, function_ref<bool(const SUnit *A, const SUnit *B)> P);
174
175 // Add DAG dependencies such that SUnits in this group shall be ordered
176 // before SUnits in OtherGroup.
177 void link(SchedGroup &OtherGroup);
178
179 // Returns true if no more instructions may be added to this group.
180 bool isFull() const { return MaxSize && Collection.size() >= *MaxSize; }
181
182 // Append a constraint that SUs must meet in order to fit into this
183 // SchedGroup. Since many rules involve the relationship between a SchedGroup
184 // and the SUnits in other SchedGroups, rules are checked at Pipeline Solve
185 // time (rather than SchedGroup init time.)
186 void addRule(std::shared_ptr<InstructionRule> NewRule) {
187 Rules.push_back(NewRule);
188 }
189
190 // Returns true if the SU matches all rules
191 bool allowedByRules(const SUnit *SU,
192 SmallVectorImpl<SchedGroup> &SyncPipe) const {
193 for (auto &Rule : Rules) {
194 if (!Rule.get()->apply(SU, Collection, SyncPipe))
195 return false;
196 }
197 return true;
198 }
199
200 // Add SU to the SchedGroup.
201 void add(SUnit &SU) {
202 LLVM_DEBUG(dbgs() << "For SchedGroup with mask "
203 << format_hex((int)SGMask, 10, true) << " adding "
204 << *SU.getInstr());
205 Collection.push_back(&SU);
206 }
207
208 // Remove last element in the SchedGroup
209 void pop() { Collection.pop_back(); }
210
211 // Identify and add all relevant SUs from the DAG to this SchedGroup.
212 void initSchedGroup();
213
214 // Add instructions to the SchedGroup bottom up starting from RIter.
215 // PipelineInstrs is a set of instructions that should not be added to the
216 // SchedGroup even when the other conditions for adding it are satisfied.
217 // RIter will be added to the SchedGroup as well, and dependencies will be
218 // added so that RIter will always be scheduled at the end of the group.
219 void initSchedGroup(std::vector<SUnit>::reverse_iterator RIter,
220 SUnitsToCandidateSGsMap &SyncedInstrs);
221
222 void initSchedGroup(SUnitsToCandidateSGsMap &SyncedInstrs);
223
224 int getSyncID() { return SyncID; }
225
226 int getSGID() { return SGID; }
227
228 SchedGroupMask getMask() { return SGMask; }
229
230 SchedGroup(SchedGroupMask SGMask, std::optional<unsigned> MaxSize,
231 ScheduleDAGInstrs *DAG, const SIInstrInfo *TII)
232 : SGMask(SGMask), MaxSize(MaxSize), DAG(DAG), TII(TII) {
233 SGID = NumSchedGroups++;
234 }
235
236 SchedGroup(SchedGroupMask SGMask, std::optional<unsigned> MaxSize, int SyncID,
237 ScheduleDAGInstrs *DAG, const SIInstrInfo *TII)
238 : SGMask(SGMask), MaxSize(MaxSize), SyncID(SyncID), DAG(DAG), TII(TII) {
239 SGID = NumSchedGroups++;
240 }
241};
242
243// Remove all existing edges from a SCHED_BARRIER or SCHED_GROUP_BARRIER.
244static void resetEdges(SUnit &SU, ScheduleDAGInstrs *DAG) {
245 assert(SU.getInstr()->getOpcode() == AMDGPU::SCHED_BARRIER ||
246 SU.getInstr()->getOpcode() == AMDGPU::SCHED_GROUP_BARRIER ||
247 SU.getInstr()->getOpcode() == AMDGPU::IGLP_OPT);
248
249 while (!SU.Preds.empty())
250 for (auto &P : SU.Preds)
251 SU.removePred(P);
252
253 while (!SU.Succs.empty())
254 for (auto &S : SU.Succs)
255 for (auto &SP : S.getSUnit()->Preds)
256 if (SP.getSUnit() == &SU)
257 S.getSUnit()->removePred(SP);
258}
259
260using SUToCandSGsPair = std::pair<SUnit *, SmallVector<int, 4>>;
261using SUsToCandSGsVec = SmallVector<SUToCandSGsPair, 4>;
262
263// The PipelineSolver is used to assign SUnits to SchedGroups in a pipeline
264// in non-trivial cases. For example, if the requested pipeline is
265// {VMEM_READ, VALU, MFMA, VMEM_READ} and we encounter a VMEM_READ instruction
266// in the DAG, then we will have an instruction that can not be trivially
267// assigned to a SchedGroup. The PipelineSolver class implements two algorithms
268// to find a good solution to the pipeline -- a greedy algorithm and an exact
269// algorithm. The exact algorithm has an exponential time complexity and should
270// only be used for small sized problems or medium sized problems where an exact
271// solution is highly desired.
272class PipelineSolver {
273 ScheduleDAGMI *DAG;
274
275 // Instructions that can be assigned to multiple SchedGroups
277 SmallVector<SUsToCandSGsVec, 4> PipelineInstrs;
279 // The current working pipeline
281 // The pipeline that has the best solution found so far
283
284 // Whether or not we actually have any SyncedInstrs to try to solve.
285 bool NeedsSolver = false;
286
287 // Compute an estimate of the size of search tree -- the true size is
288 // the product of each conflictedInst.Matches.size() across all SyncPipelines
289 unsigned computeProblemSize();
290
291 // The cost penalty of not assigning a SU to a SchedGroup
292 int MissPenalty = 0;
293
294 // Costs in terms of the number of edges we are unable to add
295 int BestCost = -1;
296 int CurrCost = 0;
297
298 // Index pointing to the conflicting instruction that is currently being
299 // fitted
300 int CurrConflInstNo = 0;
301 // Index to the pipeline that is currently being fitted
302 int CurrSyncGroupIdx = 0;
303 // The first non trivial pipeline
304 int BeginSyncGroupIdx = 0;
305
306 // How many branches we have explored
307 uint64_t BranchesExplored = 0;
308
309 // The direction in which we process the candidate SchedGroups per SU
310 bool IsBottomUp = true;
311
312 // Update indices to fit next conflicting instruction
313 void advancePosition();
314 // Recede indices to attempt to find better fit for previous conflicting
315 // instruction
316 void retreatPosition();
317
318 // The exponential time algorithm which finds the provably best fit
319 bool solveExact();
320 // The polynomial time algorithm which attempts to find a good fit
321 bool solveGreedy();
322 // Find the best SchedGroup for the current SU using the heuristic given all
323 // current information. One step in the greedy algorithm. Templated against
324 // the SchedGroup iterator (either reverse or forward).
325 template <typename T>
326 void greedyFind(std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges, T I,
327 T E);
328 // Whether or not the current solution is optimal
329 bool checkOptimal();
330 // Populate the ready list, prioiritizing fewest missed edges first
331 // Templated against the SchedGroup iterator (either reverse or forward).
332 template <typename T>
333 void populateReadyList(SmallVectorImpl<std::pair<int, int>> &ReadyList, T I,
334 T E);
335 // Add edges corresponding to the SchedGroups as assigned by solver
336 void makePipeline();
337 // Link the SchedGroups in the best found pipeline.
338 // Tmplated against the SchedGroup iterator (either reverse or forward).
339 template <typename T> void linkSchedGroups(T I, T E);
340 // Add the edges from the SU to the other SchedGroups in pipeline, and
341 // return the number of edges missed.
342 int addEdges(SmallVectorImpl<SchedGroup> &SyncPipeline, SUnit *SU, int SGID,
343 std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges);
344 /// Link the pipeline as if \p SU was in the SchedGroup with ID \p SGID. It
345 /// returns the cost (in terms of missed pipeline edges), and tracks the edges
346 /// added in \p AddedEdges
347 template <typename T>
348 int linkSUnit(SUnit *SU, int SGID,
349 std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges, T I, T E);
350 /// Remove the edges passed via \p AddedEdges
351 void removeEdges(const std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges);
352 // Convert the passed in maps to arrays for bidirectional iterators
353 void convertSyncMapsToArrays();
354
355 void reset();
356
357public:
358 // Invoke the solver to map instructions to instruction groups. Heuristic &&
359 // command-line-option determines to use exact or greedy algorithm.
360 void solve();
361
362 PipelineSolver(DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
364 ScheduleDAGMI *DAG, bool IsBottomUp = true)
365 : DAG(DAG), SyncedInstrs(SyncedInstrs),
366 SyncedSchedGroups(SyncedSchedGroups), IsBottomUp(IsBottomUp) {
367
368 for (auto &PipelineInstrs : SyncedInstrs) {
369 if (PipelineInstrs.second.size() > 0) {
370 NeedsSolver = true;
371 break;
372 }
373 }
374
375 if (!NeedsSolver)
376 return;
377
378 convertSyncMapsToArrays();
379
380 CurrPipeline = BestPipeline;
381
382 while (static_cast<size_t>(BeginSyncGroupIdx) < PipelineInstrs.size() &&
383 PipelineInstrs[BeginSyncGroupIdx].size() == 0)
384 ++BeginSyncGroupIdx;
385
386 if (static_cast<size_t>(BeginSyncGroupIdx) >= PipelineInstrs.size())
387 return;
388 }
389};
390
391void PipelineSolver::reset() {
392
393 for (auto &SyncPipeline : CurrPipeline) {
394 for (auto &SG : SyncPipeline) {
395 SmallVector<SUnit *, 32> TempCollection = SG.Collection;
396 SG.Collection.clear();
397 auto SchedBarr = llvm::find_if(TempCollection, [](SUnit *SU) {
398 return SU->getInstr()->getOpcode() == AMDGPU::SCHED_GROUP_BARRIER;
399 });
400 if (SchedBarr != TempCollection.end())
401 SG.Collection.push_back(*SchedBarr);
402 }
403 }
404
405 CurrSyncGroupIdx = BeginSyncGroupIdx;
406 CurrConflInstNo = 0;
407 CurrCost = 0;
408}
409
410void PipelineSolver::convertSyncMapsToArrays() {
411 for (auto &SyncPipe : SyncedSchedGroups) {
412 BestPipeline.insert(BestPipeline.begin(), SyncPipe.second);
413 }
414
415 int PipelineIDx = SyncedInstrs.size() - 1;
416 PipelineInstrs.resize(SyncedInstrs.size());
417 for (auto &SyncInstrMap : SyncedInstrs) {
418 for (auto &SUsToCandSGs : SyncInstrMap.second) {
419 if (PipelineInstrs[PipelineIDx].size() == 0) {
420 PipelineInstrs[PipelineIDx].push_back(
421 std::pair(SUsToCandSGs.first, SUsToCandSGs.second));
422 continue;
423 }
424 auto SortPosition = PipelineInstrs[PipelineIDx].begin();
425 // Insert them in sorted order -- this allows for good parsing order in
426 // the greedy algorithm
427 while (SortPosition != PipelineInstrs[PipelineIDx].end() &&
428 SUsToCandSGs.first->NodeNum > SortPosition->first->NodeNum)
429 ++SortPosition;
430 PipelineInstrs[PipelineIDx].insert(
431 SortPosition, std::pair(SUsToCandSGs.first, SUsToCandSGs.second));
432 }
433 --PipelineIDx;
434 }
435}
436
437template <typename T> void PipelineSolver::linkSchedGroups(T I, T E) {
438 for (; I != E; ++I) {
439 auto &GroupA = *I;
440 for (auto J = std::next(I); J != E; ++J) {
441 auto &GroupB = *J;
442 GroupA.link(GroupB);
443 }
444 }
445}
446
447void PipelineSolver::makePipeline() {
448 // Preserve the order of barrier for subsequent SchedGroupBarrier mutations
449 for (auto &SyncPipeline : BestPipeline) {
450 LLVM_DEBUG(dbgs() << "Printing SchedGroups\n");
451 for (auto &SG : SyncPipeline) {
452 LLVM_DEBUG(dbgs() << "SchedGroup with SGID " << SG.getSGID()
453 << " has: \n");
454 SUnit *SGBarr = nullptr;
455 for (auto &SU : SG.Collection) {
456 if (SU->getInstr()->getOpcode() == AMDGPU::SCHED_GROUP_BARRIER)
457 SGBarr = SU;
458 LLVM_DEBUG(dbgs() << "SU(" << SU->NodeNum << ")\n");
459 }
460 // Command line requested IGroupLP doesn't have SGBarr
461 if (!SGBarr)
462 continue;
463 resetEdges(*SGBarr, DAG);
464 SG.link(*SGBarr, false);
465 }
466 }
467
468 for (auto &SyncPipeline : BestPipeline) {
469 IsBottomUp ? linkSchedGroups(SyncPipeline.rbegin(), SyncPipeline.rend())
470 : linkSchedGroups(SyncPipeline.begin(), SyncPipeline.end());
471 }
472}
473
474template <typename T>
475int PipelineSolver::linkSUnit(
476 SUnit *SU, int SGID, std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges,
477 T I, T E) {
478 bool MakePred = false;
479 int AddedCost = 0;
480 for (; I < E; ++I) {
481 if (I->getSGID() == SGID) {
482 MakePred = true;
483 continue;
484 }
485 auto Group = *I;
486 AddedCost += Group.link(*SU, MakePred, AddedEdges);
487 assert(AddedCost >= 0);
488 }
489 return AddedCost;
490}
491
492int PipelineSolver::addEdges(
493 SmallVectorImpl<SchedGroup> &SyncPipeline, SUnit *SU, int SGID,
494 std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges) {
495
496 // For IsBottomUp, the first SchedGroup in SyncPipeline contains the
497 // instructions that are the ultimate successors in the resultant mutation.
498 // Therefore, in such a configuration, the SchedGroups occurring before the
499 // candidate SGID are successors of the candidate SchedGroup, thus the current
500 // SU should be linked as a predecessor to SUs in those SchedGroups. The
501 // opposite is true if !IsBottomUp. IsBottomUp occurs in the case of multiple
502 // SCHED_GROUP_BARRIERS, or if a user specifies IGLP_OPT SchedGroups using
503 // IsBottomUp (in reverse).
504 return IsBottomUp ? linkSUnit(SU, SGID, AddedEdges, SyncPipeline.rbegin(),
505 SyncPipeline.rend())
506 : linkSUnit(SU, SGID, AddedEdges, SyncPipeline.begin(),
507 SyncPipeline.end());
508}
509
510void PipelineSolver::removeEdges(
511 const std::vector<std::pair<SUnit *, SUnit *>> &EdgesToRemove) {
512 // Only remove the edges that we have added when testing
513 // the fit.
514 for (auto &PredSuccPair : EdgesToRemove) {
515 SUnit *Pred = PredSuccPair.first;
516 SUnit *Succ = PredSuccPair.second;
517
518 auto Match = llvm::find_if(
519 Succ->Preds, [&Pred](SDep &P) { return P.getSUnit() == Pred; });
520 if (Match != Succ->Preds.end()) {
521 assert(Match->isArtificial());
522 Succ->removePred(*Match);
523 }
524 }
525}
526
527void PipelineSolver::advancePosition() {
528 ++CurrConflInstNo;
529
530 if (static_cast<size_t>(CurrConflInstNo) >=
531 PipelineInstrs[CurrSyncGroupIdx].size()) {
532 CurrConflInstNo = 0;
533 ++CurrSyncGroupIdx;
534 // Advance to next non-trivial pipeline
535 while (static_cast<size_t>(CurrSyncGroupIdx) < PipelineInstrs.size() &&
536 PipelineInstrs[CurrSyncGroupIdx].size() == 0)
537 ++CurrSyncGroupIdx;
538 }
539}
540
541void PipelineSolver::retreatPosition() {
542 assert(CurrConflInstNo >= 0);
543 assert(CurrSyncGroupIdx >= 0);
544
545 if (CurrConflInstNo > 0) {
546 --CurrConflInstNo;
547 return;
548 }
549
550 if (CurrConflInstNo == 0) {
551 // If we return to the starting position, we have explored
552 // the entire tree
553 if (CurrSyncGroupIdx == BeginSyncGroupIdx)
554 return;
555
556 --CurrSyncGroupIdx;
557 // Go to previous non-trivial pipeline
558 while (PipelineInstrs[CurrSyncGroupIdx].size() == 0)
559 --CurrSyncGroupIdx;
560
561 CurrConflInstNo = PipelineInstrs[CurrSyncGroupIdx].size() - 1;
562 }
563}
564
565bool PipelineSolver::checkOptimal() {
566 if (static_cast<size_t>(CurrSyncGroupIdx) == PipelineInstrs.size()) {
567 if (BestCost == -1 || CurrCost < BestCost) {
568 BestPipeline = CurrPipeline;
569 BestCost = CurrCost;
570 LLVM_DEBUG(dbgs() << "Found Fit with cost " << BestCost << "\n");
571 }
572 assert(BestCost >= 0);
573 }
574
575 bool DoneExploring = false;
576 if (MaxBranchesExplored > 0 && BranchesExplored >= MaxBranchesExplored)
577 DoneExploring = true;
578
579 return (DoneExploring || BestCost == 0);
580}
581
582template <typename T>
583void PipelineSolver::populateReadyList(
584 SmallVectorImpl<std::pair<int, int>> &ReadyList, T I, T E) {
585 SUToCandSGsPair CurrSU = PipelineInstrs[CurrSyncGroupIdx][CurrConflInstNo];
586 auto SyncPipeline = CurrPipeline[CurrSyncGroupIdx];
587 assert(CurrSU.second.size() >= 1);
588
589 for (; I != E; ++I) {
590 std::vector<std::pair<SUnit *, SUnit *>> AddedEdges;
591 int CandSGID = *I;
592 SchedGroup *Match = llvm::find_if(SyncPipeline, [CandSGID](SchedGroup &SG) {
593 return SG.getSGID() == CandSGID;
594 });
595 assert(Match);
596
597 if (UseCostHeur) {
598 if (Match->isFull()) {
599 ReadyList.push_back(std::pair(*I, MissPenalty));
600 continue;
601 }
602
603 int TempCost = addEdges(SyncPipeline, CurrSU.first, CandSGID, AddedEdges);
604 ReadyList.push_back(std::pair(*I, TempCost));
605 removeEdges(AddedEdges);
606 } else
607 ReadyList.push_back(std::pair(*I, -1));
608 }
609
610 if (UseCostHeur) {
611 std::sort(ReadyList.begin(), ReadyList.end(),
612 [](std::pair<int, int> A, std::pair<int, int> B) {
613 return A.second < B.second;
614 });
615 }
616
617 assert(ReadyList.size() == CurrSU.second.size());
618}
619
620bool PipelineSolver::solveExact() {
621 if (checkOptimal())
622 return true;
623
624 if (static_cast<size_t>(CurrSyncGroupIdx) == PipelineInstrs.size())
625 return false;
626
627 assert(static_cast<size_t>(CurrSyncGroupIdx) < PipelineInstrs.size());
628 assert(static_cast<size_t>(CurrConflInstNo) <
629 PipelineInstrs[CurrSyncGroupIdx].size());
630 SUToCandSGsPair CurrSU = PipelineInstrs[CurrSyncGroupIdx][CurrConflInstNo];
631 LLVM_DEBUG(dbgs() << "Fitting SU(" << CurrSU.first->NodeNum
632 << ") in Pipeline # " << CurrSyncGroupIdx << "\n");
633
634 // SchedGroup -> Cost pairs
636 // Prioritize the candidate sched groups in terms of lowest cost first
637 IsBottomUp ? populateReadyList(ReadyList, CurrSU.second.rbegin(),
638 CurrSU.second.rend())
639 : populateReadyList(ReadyList, CurrSU.second.begin(),
640 CurrSU.second.end());
641
642 auto I = ReadyList.begin();
643 auto E = ReadyList.end();
644 for (; I != E; ++I) {
645 // If we are trying SGs in least cost order, and the current SG is cost
646 // infeasible, then all subsequent SGs will also be cost infeasible, so we
647 // can prune.
648 if (BestCost != -1 && (CurrCost + I->second > BestCost))
649 return false;
650
651 int CandSGID = I->first;
652 int AddedCost = 0;
653 std::vector<std::pair<SUnit *, SUnit *>> AddedEdges;
654 auto &SyncPipeline = CurrPipeline[CurrSyncGroupIdx];
655 SchedGroup *Match;
656 for (auto &SG : SyncPipeline) {
657 if (SG.getSGID() == CandSGID)
658 Match = &SG;
659 }
660
661 if (Match->isFull())
662 continue;
663
664 if (!Match->allowedByRules(CurrSU.first, SyncPipeline))
665 continue;
666
667 LLVM_DEBUG(dbgs() << "Assigning to SchedGroup with Mask "
668 << (int)Match->getMask() << "and ID " << CandSGID
669 << "\n");
670 Match->add(*CurrSU.first);
671 AddedCost = addEdges(SyncPipeline, CurrSU.first, CandSGID, AddedEdges);
672 LLVM_DEBUG(dbgs() << "Cost of Assignment: " << AddedCost << "\n");
673 CurrCost += AddedCost;
674 advancePosition();
675 ++BranchesExplored;
676 bool FinishedExploring = false;
677 // If the Cost after adding edges is greater than a known solution,
678 // backtrack
679 if (CurrCost < BestCost || BestCost == -1) {
680 if (solveExact()) {
681 FinishedExploring = BestCost != 0;
682 if (!FinishedExploring)
683 return true;
684 }
685 }
686
687 retreatPosition();
688 CurrCost -= AddedCost;
689 removeEdges(AddedEdges);
690 Match->pop();
691 CurrPipeline[CurrSyncGroupIdx] = SyncPipeline;
692 if (FinishedExploring)
693 return true;
694 }
695
696 // Try the pipeline where the current instruction is omitted
697 // Potentially if we omit a problematic instruction from the pipeline,
698 // all the other instructions can nicely fit.
699 CurrCost += MissPenalty;
700 advancePosition();
701
702 LLVM_DEBUG(dbgs() << "NOT Assigned (" << CurrSU.first->NodeNum << ")\n");
703
704 bool FinishedExploring = false;
705 if (CurrCost < BestCost || BestCost == -1) {
706 if (solveExact()) {
707 bool FinishedExploring = BestCost != 0;
708 if (!FinishedExploring)
709 return true;
710 }
711 }
712
713 retreatPosition();
714 CurrCost -= MissPenalty;
715 return FinishedExploring;
716}
717
718template <typename T>
719void PipelineSolver::greedyFind(
720 std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges, T I, T E) {
721 SUToCandSGsPair CurrSU = PipelineInstrs[CurrSyncGroupIdx][CurrConflInstNo];
722 int BestNodeCost = -1;
723 int TempCost;
724 SchedGroup *BestGroup = nullptr;
725 int BestGroupID = -1;
726 auto &SyncPipeline = CurrPipeline[CurrSyncGroupIdx];
727 LLVM_DEBUG(dbgs() << "Fitting SU(" << CurrSU.first->NodeNum
728 << ") in Pipeline # " << CurrSyncGroupIdx << "\n");
729
730 // Since we have added the potential SchedGroups from bottom up, but
731 // traversed the DAG from top down, parse over the groups from last to
732 // first. If we fail to do this for the greedy algorithm, the solution will
733 // likely not be good in more complex cases.
734 for (; I != E; ++I) {
735 std::vector<std::pair<SUnit *, SUnit *>> AddedEdges;
736 int CandSGID = *I;
737 SchedGroup *Match = llvm::find_if(SyncPipeline, [CandSGID](SchedGroup &SG) {
738 return SG.getSGID() == CandSGID;
739 });
740 assert(Match);
741
742 LLVM_DEBUG(dbgs() << "Trying SGID # " << CandSGID << " with Mask "
743 << (int)Match->getMask() << "\n");
744
745 if (Match->isFull()) {
746 LLVM_DEBUG(dbgs() << "SGID # " << CandSGID << " is full\n");
747 continue;
748 }
749 if (!Match->allowedByRules(CurrSU.first, SyncPipeline)) {
750 LLVM_DEBUG(dbgs() << "SGID # " << CandSGID << " has conflicting rule\n");
751 continue;
752 }
753 TempCost = addEdges(SyncPipeline, CurrSU.first, CandSGID, AddedEdges);
754 LLVM_DEBUG(dbgs() << "Cost of Group " << TempCost << "\n");
755 if (TempCost < BestNodeCost || BestNodeCost == -1) {
756 BestGroup = Match;
757 BestNodeCost = TempCost;
758 BestGroupID = CandSGID;
759 }
760 removeEdges(AddedEdges);
761 if (BestNodeCost == 0)
762 break;
763 }
764
765 if (BestGroupID != -1) {
766 BestGroup->add(*CurrSU.first);
767 addEdges(SyncPipeline, CurrSU.first, BestGroupID, AddedEdges);
768 LLVM_DEBUG(dbgs() << "Best Group has ID: " << BestGroupID << " and Mask"
769 << (int)BestGroup->getMask() << "\n");
770 BestCost += TempCost;
771 } else
772 BestCost += MissPenalty;
773
774 CurrPipeline[CurrSyncGroupIdx] = SyncPipeline;
775}
776
777bool PipelineSolver::solveGreedy() {
778 BestCost = 0;
779 std::vector<std::pair<SUnit *, SUnit *>> AddedEdges;
780
781 while (static_cast<size_t>(CurrSyncGroupIdx) < PipelineInstrs.size()) {
782 SUToCandSGsPair CurrSU = PipelineInstrs[CurrSyncGroupIdx][CurrConflInstNo];
783 IsBottomUp
784 ? greedyFind(AddedEdges, CurrSU.second.rbegin(), CurrSU.second.rend())
785 : greedyFind(AddedEdges, CurrSU.second.begin(), CurrSU.second.end());
786 advancePosition();
787 }
788 BestPipeline = CurrPipeline;
789 removeEdges(AddedEdges);
790 return false;
791}
792
793unsigned PipelineSolver::computeProblemSize() {
794 unsigned ProblemSize = 0;
795 for (auto &PipeConflicts : PipelineInstrs) {
796 ProblemSize += PipeConflicts.size();
797 }
798
799 return ProblemSize;
800}
801
802void PipelineSolver::solve() {
803 if (!NeedsSolver)
804 return;
805
806 unsigned ProblemSize = computeProblemSize();
807 assert(ProblemSize > 0);
808
809 bool BelowCutoff = (CutoffForExact > 0) && ProblemSize <= CutoffForExact;
810 MissPenalty = (ProblemSize / 2) + 1;
811
812 LLVM_DEBUG(DAG->dump());
813 if (EnableExactSolver || BelowCutoff) {
814 LLVM_DEBUG(dbgs() << "Starting Greedy pipeline solver\n");
815 solveGreedy();
816 reset();
817 LLVM_DEBUG(dbgs() << "Greedy produced best cost of " << BestCost << "\n");
818 if (BestCost > 0) {
819 LLVM_DEBUG(dbgs() << "Starting EXACT pipeline solver\n");
820 solveExact();
821 LLVM_DEBUG(dbgs() << "Exact produced best cost of " << BestCost << "\n");
822 }
823 } else { // Use the Greedy Algorithm by default
824 LLVM_DEBUG(dbgs() << "Starting GREEDY pipeline solver\n");
825 solveGreedy();
826 }
827
828 makePipeline();
829 LLVM_DEBUG(dbgs() << "After applying mutation\n");
830 LLVM_DEBUG(DAG->dump());
831}
832
833enum IGLPStrategyID : int {
834 MFMASmallGemmOptID = 0,
835 MFMASmallGemmSingleWaveOptID = 1,
836 MFMAExpInterleave = 2
837};
838
839// Implement a IGLP scheduling strategy.
840class IGLPStrategy {
841protected:
843
844 const SIInstrInfo *TII;
845
846public:
847 /// Add SchedGroups to \p SyncedSchedGroups to implement this Strategy.
848 virtual bool applyIGLPStrategy(
850 DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
852
853 // Returns true if this strategy should be applied to a ScheduleDAG.
854 virtual bool shouldApplyStrategy(ScheduleDAGInstrs *DAG,
856
857 bool IsBottomUp = true;
858
859 IGLPStrategy(ScheduleDAGInstrs *DAG, const SIInstrInfo *TII)
860 : DAG(DAG), TII(TII) {}
861
862 virtual ~IGLPStrategy() = default;
863};
864
865class MFMASmallGemmOpt final : public IGLPStrategy {
866private:
867public:
868 bool applyIGLPStrategy(
870 DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
872
873 bool shouldApplyStrategy(ScheduleDAGInstrs *DAG,
875 return true;
876 }
877
878 MFMASmallGemmOpt(ScheduleDAGInstrs *DAG, const SIInstrInfo *TII)
879 : IGLPStrategy(DAG, TII) {
880 IsBottomUp = true;
881 }
882};
883
884bool MFMASmallGemmOpt::applyIGLPStrategy(
886 DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
888 // Count the number of MFMA instructions.
889 unsigned MFMACount = 0;
890 for (const MachineInstr &I : *DAG)
891 if (TII->isMFMAorWMMA(I))
892 ++MFMACount;
893
894 const unsigned PipelineSyncID = 0;
895 SchedGroup *SG = nullptr;
896 for (unsigned I = 0; I < MFMACount * 3; ++I) {
897 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
898 SchedGroupMask::DS, 2, PipelineSyncID, DAG, TII);
899 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
900
901 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
902 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
903 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
904 }
905
906 return true;
907}
908
909class MFMAExpInterleaveOpt final : public IGLPStrategy {
910private:
911 // The count of TRANS SUs involved in the interleaved pipeline
912 static unsigned TransPipeCount;
913 // The count of MFMA SUs involved in the interleaved pipeline
914 static unsigned MFMAPipeCount;
915 // The count of Add SUs involved in the interleaved pipeline
916 static unsigned AddPipeCount;
917 // The number of transitive MFMA successors for each TRANS SU
918 static unsigned MFMAEnablement;
919 // The number of transitive TRANS predecessors for each MFMA SU
920 static unsigned ExpRequirement;
921 // The count of independent "chains" of MFMA instructions in the pipeline
922 static unsigned MFMAChains;
923 // The length of each independent "chain" of MFMA instructions
924 static unsigned MFMAChainLength;
925 // Whether or not the pipeline has V_CVT instructions
926 static bool HasCvt;
927 // Whether or not there are instructions between the TRANS instruction and
928 // V_CVT
929 static bool HasChainBetweenCvt;
930 // The first occuring DS_READ which feeds an MFMA chain
931 static std::optional<unsigned> FirstPipeDSR;
932 // The MFMAPipe SUs with no MFMA predecessors
933 SmallVector<SUnit *, 4> MFMAChainSeeds;
934 // Compute the heuristics for the pipeline, returning whether or not the DAG
935 // is well formatted for the mutation
936 bool analyzeDAG(const SIInstrInfo *TII);
937
938 /// Whether or not the instruction is a transitive predecessor of an MFMA
939 /// instruction
940 class IsPipeExp final : public InstructionRule {
941 public:
942 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
943 SmallVectorImpl<SchedGroup> &SyncPipe) override {
944
945 auto DAG = SyncPipe[0].DAG;
946
947 if (Cache->empty()) {
948 auto I = DAG->SUnits.rbegin();
949 auto E = DAG->SUnits.rend();
950 for (; I != E; I++) {
951 if (TII->isMFMAorWMMA(*I->getInstr()))
952 Cache->push_back(&*I);
953 }
954 if (Cache->empty())
955 return false;
956 }
957
958 auto Reaches = any_of(*Cache, [&SU, &DAG](SUnit *TargetSU) {
959 return DAG->IsReachable(TargetSU, const_cast<SUnit *>(SU));
960 });
961
962 return Reaches;
963 }
964 IsPipeExp(const SIInstrInfo *TII, unsigned SGID, bool NeedsCache = false)
965 : InstructionRule(TII, SGID, NeedsCache) {}
966 };
967
968 /// Whether or not the instruction is a transitive predecessor of the
969 /// \p Number th MFMA of the MFMAs occuring after a TRANS instruction
970 class EnablesNthMFMA final : public InstructionRule {
971 private:
972 unsigned Number = 1;
973
974 public:
975 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
976 SmallVectorImpl<SchedGroup> &SyncPipe) override {
977 bool FoundTrans = false;
978 unsigned Counter = 1;
979 auto DAG = SyncPipe[0].DAG;
980
981 if (Cache->empty()) {
983
984 auto I = DAG->SUnits.begin();
985 auto E = DAG->SUnits.end();
986 for (; I != E; I++) {
987 if (FoundTrans && TII->isMFMAorWMMA(*I->getInstr())) {
988 if (Counter == Number) {
989 Cache->push_back(&*I);
990 break;
991 }
992 ++Counter;
993 }
994 if (!FoundTrans && TII->isTRANS(I->getInstr()->getOpcode()))
995 FoundTrans = true;
996 }
997 if (Cache->empty())
998 return false;
999 }
1000
1001 return DAG->IsReachable((*Cache)[0], const_cast<SUnit *>(SU));
1002 }
1003
1004 EnablesNthMFMA(unsigned Number, const SIInstrInfo *TII, unsigned SGID,
1005 bool NeedsCache = false)
1006 : InstructionRule(TII, SGID, NeedsCache), Number(Number) {}
1007 };
1008
1009 /// Whether or not the instruction enables the exact MFMA that is the \p
1010 /// Number th MFMA in the chain starting with \p ChainSeed
1011 class EnablesNthMFMAInChain final : public InstructionRule {
1012 private:
1013 unsigned Number = 1;
1014 SUnit *ChainSeed;
1015
1016 public:
1017 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1018 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1019 auto DAG = SyncPipe[0].DAG;
1020
1021 if (!SU || !TII->isMFMAorWMMA(*ChainSeed->getInstr()))
1022 return false;
1023
1024 if (Cache->empty()) {
1025 auto TempSU = ChainSeed;
1026 auto Depth = Number;
1027 while (Depth > 0) {
1028 --Depth;
1029 bool Found = false;
1030 for (auto &Succ : TempSU->Succs) {
1031 if (TII->isMFMAorWMMA(*Succ.getSUnit()->getInstr())) {
1032 TempSU = Succ.getSUnit();
1033 Found = true;
1034 break;
1035 }
1036 }
1037 if (!Found)
1038 return false;
1039 }
1040
1041 Cache->push_back(TempSU);
1042 }
1043 // If we failed to find the instruction to be placed into the cache, we
1044 // would have already exited.
1045 assert(!Cache->empty());
1046
1047 return DAG->IsReachable((*Cache)[0], const_cast<SUnit *>(SU));
1048 }
1049
1050 EnablesNthMFMAInChain(unsigned Number, SUnit *ChainSeed,
1051 const SIInstrInfo *TII, unsigned SGID,
1052 bool NeedsCache = false)
1053 : InstructionRule(TII, SGID, NeedsCache), Number(Number),
1054 ChainSeed(ChainSeed) {}
1055 };
1056
1057 /// Whether or not the instruction has less than \p Size immediate successors.
1058 /// If \p HasIntermediary is true, this tests also whether all successors of
1059 /// the SUnit have less than \p Size successors.
1060 class LessThanNSuccs final : public InstructionRule {
1061 private:
1062 unsigned Size = 1;
1063 bool HasIntermediary = false;
1064
1065 public:
1066 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1067 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1068 if (!SyncPipe.size())
1069 return false;
1070
1071 auto SuccSize = std::count_if(
1072 SU->Succs.begin(), SU->Succs.end(),
1073 [](const SDep &Succ) { return Succ.getKind() == SDep::Data; });
1074 if (SuccSize >= Size)
1075 return false;
1076
1077 if (HasIntermediary) {
1078 for (auto Succ : SU->Succs) {
1079 auto SuccSize = std::count_if(
1080 Succ.getSUnit()->Succs.begin(), Succ.getSUnit()->Succs.end(),
1081 [](const SDep &SuccSucc) {
1082 return SuccSucc.getKind() == SDep::Data;
1083 });
1084 if (SuccSize >= Size)
1085 return false;
1086 }
1087 }
1088
1089 return true;
1090 }
1091 LessThanNSuccs(unsigned Size, const SIInstrInfo *TII, unsigned SGID,
1092 bool HasIntermediary = false, bool NeedsCache = false)
1093 : InstructionRule(TII, SGID, NeedsCache), Size(Size),
1094 HasIntermediary(HasIntermediary) {}
1095 };
1096
1097 /// Whether or not the instruction has greater than or equal to \p Size
1098 /// immediate successors. If \p HasIntermediary is true, this tests also
1099 /// whether all successors of the SUnit have greater than or equal to \p Size
1100 /// successors.
1101 class GreaterThanOrEqualToNSuccs final : public InstructionRule {
1102 private:
1103 unsigned Size = 1;
1104 bool HasIntermediary = false;
1105
1106 public:
1107 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1108 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1109 if (!SyncPipe.size())
1110 return false;
1111
1112 auto SuccSize = std::count_if(
1113 SU->Succs.begin(), SU->Succs.end(),
1114 [](const SDep &Succ) { return Succ.getKind() == SDep::Data; });
1115 if (SuccSize >= Size)
1116 return true;
1117
1118 if (HasIntermediary) {
1119 for (auto Succ : SU->Succs) {
1120 auto SuccSize = std::count_if(
1121 Succ.getSUnit()->Succs.begin(), Succ.getSUnit()->Succs.end(),
1122 [](const SDep &SuccSucc) {
1123 return SuccSucc.getKind() == SDep::Data;
1124 });
1125 if (SuccSize >= Size)
1126 return true;
1127 }
1128 }
1129
1130 return false;
1131 }
1132 GreaterThanOrEqualToNSuccs(unsigned Size, const SIInstrInfo *TII,
1133 unsigned SGID, bool HasIntermediary = false,
1134 bool NeedsCache = false)
1135 : InstructionRule(TII, SGID, NeedsCache), Size(Size),
1136 HasIntermediary(HasIntermediary) {}
1137 };
1138
1139 // Whether or not the instruction is a relevant V_CVT instruction.
1140 class IsCvt final : public InstructionRule {
1141 public:
1142 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1143 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1144 auto Opc = SU->getInstr()->getOpcode();
1145 return Opc == AMDGPU::V_CVT_F16_F32_e32 ||
1146 Opc == AMDGPU::V_CVT_I32_F32_e32;
1147 }
1148 IsCvt(const SIInstrInfo *TII, unsigned SGID, bool NeedsCache = false)
1149 : InstructionRule(TII, SGID, NeedsCache) {}
1150 };
1151
1152 // Whether or not the instruction is FMA_F32.
1153 class IsFMA final : public InstructionRule {
1154 public:
1155 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1156 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1157 return SU->getInstr()->getOpcode() == AMDGPU::V_FMA_F32_e64 ||
1158 SU->getInstr()->getOpcode() == AMDGPU::V_PK_FMA_F32;
1159 }
1160 IsFMA(const SIInstrInfo *TII, unsigned SGID, bool NeedsCache = false)
1161 : InstructionRule(TII, SGID, NeedsCache) {}
1162 };
1163
1164 // Whether or not the instruction is a V_ADD_F32 instruction.
1165 class IsPipeAdd final : public InstructionRule {
1166 public:
1167 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1168 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1169 return SU->getInstr()->getOpcode() == AMDGPU::V_ADD_F32_e32;
1170 }
1171 IsPipeAdd(const SIInstrInfo *TII, unsigned SGID, bool NeedsCache = false)
1172 : InstructionRule(TII, SGID, NeedsCache) {}
1173 };
1174
1175 /// Whether or not the instruction is an immediate RAW successor
1176 /// of the SchedGroup \p Distance steps before.
1177 class IsSuccOfPrevNthGroup final : public InstructionRule {
1178 private:
1179 unsigned Distance = 1;
1180
1181 public:
1182 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1183 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1184 SchedGroup *OtherGroup = nullptr;
1185 if (!SyncPipe.size())
1186 return false;
1187
1188 for (auto &PipeSG : SyncPipe) {
1189 if ((unsigned)PipeSG.getSGID() == SGID - Distance)
1190 OtherGroup = &PipeSG;
1191 }
1192
1193 if (!OtherGroup)
1194 return false;
1195 if (!OtherGroup->Collection.size())
1196 return true;
1197
1198 for (auto &OtherEle : OtherGroup->Collection) {
1199 for (auto &Succ : OtherEle->Succs) {
1200 if (Succ.getSUnit() == SU && Succ.getKind() == SDep::Data)
1201 return true;
1202 }
1203 }
1204
1205 return false;
1206 }
1207 IsSuccOfPrevNthGroup(unsigned Distance, const SIInstrInfo *TII,
1208 unsigned SGID, bool NeedsCache = false)
1209 : InstructionRule(TII, SGID, NeedsCache), Distance(Distance) {}
1210 };
1211
1212 /// Whether or not the instruction is a transitive successor of any
1213 /// instruction the the SchedGroup \p Distance steps before.
1214 class IsReachableFromPrevNthGroup final : public InstructionRule {
1215 private:
1216 unsigned Distance = 1;
1217
1218 public:
1219 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1220 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1221 SchedGroup *OtherGroup = nullptr;
1222 if (!SyncPipe.size())
1223 return false;
1224
1225 for (auto &PipeSG : SyncPipe) {
1226 if ((unsigned)PipeSG.getSGID() == SGID - Distance)
1227 OtherGroup = &PipeSG;
1228 }
1229
1230 if (!OtherGroup)
1231 return false;
1232 if (!OtherGroup->Collection.size())
1233 return true;
1234
1235 auto DAG = SyncPipe[0].DAG;
1236
1237 for (auto &OtherEle : OtherGroup->Collection)
1238 if (DAG->IsReachable(const_cast<SUnit *>(SU), OtherEle))
1239 return true;
1240
1241 return false;
1242 }
1243 IsReachableFromPrevNthGroup(unsigned Distance, const SIInstrInfo *TII,
1244 unsigned SGID, bool NeedsCache = false)
1245 : InstructionRule(TII, SGID, NeedsCache), Distance(Distance) {}
1246 };
1247
1248 /// Whether or not the instruction occurs after the SU with NodeNUm \p Number
1249 class OccursAtOrAfterNode final : public InstructionRule {
1250 private:
1251 unsigned Number = 1;
1252
1253 public:
1254 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1255 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1256
1257 return SU->NodeNum >= Number;
1258 }
1259 OccursAtOrAfterNode(unsigned Number, const SIInstrInfo *TII, unsigned SGID,
1260 bool NeedsCache = false)
1261 : InstructionRule(TII, SGID, NeedsCache), Number(Number) {}
1262 };
1263
1264 /// Whether or not the SU is exactly the \p Number th MFMA in the chain
1265 /// starting with \p ChainSeed
1266 class IsExactMFMA final : public InstructionRule {
1267 private:
1268 unsigned Number = 1;
1269 SUnit *ChainSeed;
1270
1271 public:
1272 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1273 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1274 if (!SU || !TII->isMFMAorWMMA(*ChainSeed->getInstr()))
1275 return false;
1276
1277 if (Cache->empty()) {
1278 auto TempSU = ChainSeed;
1279 auto Depth = Number;
1280 while (Depth > 0) {
1281 --Depth;
1282 bool Found = false;
1283 for (auto &Succ : TempSU->Succs) {
1284 if (TII->isMFMAorWMMA(*Succ.getSUnit()->getInstr())) {
1285 TempSU = Succ.getSUnit();
1286 Found = true;
1287 break;
1288 }
1289 }
1290 if (!Found) {
1291 return false;
1292 }
1293 }
1294 Cache->push_back(TempSU);
1295 }
1296 // If we failed to find the instruction to be placed into the cache, we
1297 // would have already exited.
1298 assert(!Cache->empty());
1299
1300 return (*Cache)[0] == SU;
1301 }
1302
1303 IsExactMFMA(unsigned Number, SUnit *ChainSeed, const SIInstrInfo *TII,
1304 unsigned SGID, bool NeedsCache = false)
1305 : InstructionRule(TII, SGID, NeedsCache), Number(Number),
1306 ChainSeed(ChainSeed) {}
1307 };
1308
1309 // Whether the instruction occurs after the first TRANS instruction. This
1310 // implies the instruction can not be a predecessor of the first TRANS
1311 // insruction
1312 class OccursAfterExp final : public InstructionRule {
1313 public:
1314 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1315 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1316
1317 SmallVector<SUnit *, 12> Worklist;
1318 auto DAG = SyncPipe[0].DAG;
1319 if (Cache->empty()) {
1320 for (auto &SU : DAG->SUnits)
1321 if (TII->isTRANS(SU.getInstr()->getOpcode())) {
1322 Cache->push_back(&SU);
1323 break;
1324 }
1325 if (Cache->empty())
1326 return false;
1327 }
1328
1329 return SU->NodeNum > (*Cache)[0]->NodeNum;
1330 }
1331
1332 OccursAfterExp(const SIInstrInfo *TII, unsigned SGID,
1333 bool NeedsCache = false)
1334 : InstructionRule(TII, SGID, NeedsCache) {}
1335 };
1336
1337public:
1338 bool applyIGLPStrategy(
1340 DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
1342
1343 bool shouldApplyStrategy(ScheduleDAGInstrs *DAG,
1345
1346 MFMAExpInterleaveOpt(ScheduleDAGInstrs *DAG, const SIInstrInfo *TII)
1347 : IGLPStrategy(DAG, TII) {
1348 IsBottomUp = false;
1349 }
1350};
1351
1352unsigned MFMAExpInterleaveOpt::TransPipeCount = 0;
1353unsigned MFMAExpInterleaveOpt::MFMAPipeCount = 0;
1354unsigned MFMAExpInterleaveOpt::AddPipeCount = 0;
1355unsigned MFMAExpInterleaveOpt::MFMAEnablement = 0;
1356unsigned MFMAExpInterleaveOpt::ExpRequirement = 0;
1357unsigned MFMAExpInterleaveOpt::MFMAChains = 0;
1358unsigned MFMAExpInterleaveOpt::MFMAChainLength = 0;
1359bool MFMAExpInterleaveOpt::HasCvt = false;
1360bool MFMAExpInterleaveOpt::HasChainBetweenCvt = false;
1361std::optional<unsigned> MFMAExpInterleaveOpt::FirstPipeDSR = std::nullopt;
1362
1363bool MFMAExpInterleaveOpt::analyzeDAG(const SIInstrInfo *TII) {
1364 SmallVector<SUnit *, 10> ExpPipeCands;
1365 SmallVector<SUnit *, 10> MFMAPipeCands;
1366 SmallVector<SUnit *, 10> MFMAPipeSUs;
1369
1370 auto isBitPack = [](unsigned Opc) {
1371 return Opc == AMDGPU::V_PACK_B32_F16_e64 || Opc == AMDGPU::V_PERM_B32_e64;
1372 };
1373
1374 auto isCvt = [](unsigned Opc) {
1375 return Opc == AMDGPU::V_CVT_F16_F32_e32 || Opc == AMDGPU::V_CVT_I32_F32_e32;
1376 };
1377
1378 auto isAdd = [](unsigned Opc) { return Opc == AMDGPU::V_ADD_F32_e32; };
1379
1380 AddPipeCount = 0;
1381 for (SUnit &SU : DAG->SUnits) {
1382 auto Opc = SU.getInstr()->getOpcode();
1383 if (TII->isTRANS(Opc)) {
1384 // Avoid counting a potential bonus V_EXP which all the MFMA depend on
1385 if (SU.Succs.size() >= 7)
1386 continue;
1387 for (auto &Succ : SU.Succs) {
1388 if (Succ.getSUnit()->Succs.size() >= 7)
1389 continue;
1390 }
1391 ExpPipeCands.push_back(&SU);
1392 }
1393
1394 if (TII->isMFMAorWMMA(*SU.getInstr()))
1395 MFMAPipeCands.push_back(&SU);
1396
1397 if (isBitPack(Opc))
1398 PackSUs.push_back(&SU);
1399
1400 if (isCvt(Opc))
1401 CvtSUs.push_back(&SU);
1402
1403 if (isAdd(Opc))
1404 ++AddPipeCount;
1405 }
1406
1407 if (!(PackSUs.size() && MFMAPipeCands.size() && ExpPipeCands.size()))
1408 return false;
1409
1410 TransPipeCount = 0;
1411
1412 std::optional<SUnit *> TempMFMA;
1413 std::optional<SUnit *> TempExp;
1414 // Count the number of EXPs that reach an MFMA
1415 for (auto &PredSU : ExpPipeCands) {
1416 for (auto &SuccSU : MFMAPipeCands) {
1417 if (DAG->IsReachable(SuccSU, PredSU)) {
1418 if (!TempExp) {
1419 TempExp = PredSU;
1420 TempMFMA = SuccSU;
1421 }
1422 MFMAPipeSUs.push_back(SuccSU);
1423 ++TransPipeCount;
1424 break;
1425 }
1426 }
1427 }
1428
1429 if (!(TempExp && TempMFMA))
1430 return false;
1431
1432 HasChainBetweenCvt = none_of((*TempExp)->Succs, [&isCvt](SDep &Succ) {
1433 return isCvt(Succ.getSUnit()->getInstr()->getOpcode());
1434 });
1435
1436 // Count the number of MFMAs that are reached by an EXP
1437 for (auto &SuccSU : MFMAPipeCands) {
1438 if (MFMAPipeSUs.size() &&
1439 any_of(MFMAPipeSUs, [&SuccSU](SUnit *PotentialMatch) {
1440 return PotentialMatch->NodeNum == SuccSU->NodeNum;
1441 }))
1442 continue;
1443
1444 for (auto &PredSU : ExpPipeCands) {
1445 if (DAG->IsReachable(SuccSU, PredSU)) {
1446 MFMAPipeSUs.push_back(SuccSU);
1447 break;
1448 }
1449 }
1450 }
1451
1452 MFMAPipeCount = MFMAPipeSUs.size();
1453
1454 assert(TempExp && TempMFMA);
1455 assert(MFMAPipeCount > 0);
1456
1457 std::optional<SUnit *> TempCvt;
1458 for (auto &SuccSU : CvtSUs) {
1459 if (DAG->IsReachable(SuccSU, *TempExp)) {
1460 TempCvt = SuccSU;
1461 break;
1462 }
1463 }
1464
1465 HasCvt = false;
1466 if (TempCvt.has_value()) {
1467 for (auto &SuccSU : MFMAPipeSUs) {
1468 if (DAG->IsReachable(SuccSU, *TempCvt)) {
1469 HasCvt = true;
1470 break;
1471 }
1472 }
1473 }
1474
1475 MFMAChains = 0;
1476 for (auto &MFMAPipeSU : MFMAPipeSUs) {
1477 if (is_contained(MFMAChainSeeds, MFMAPipeSU))
1478 continue;
1479 if (none_of(MFMAPipeSU->Preds, [&TII](SDep &Succ) {
1480 return TII->isMFMAorWMMA(*Succ.getSUnit()->getInstr());
1481 })) {
1482 MFMAChainSeeds.push_back(MFMAPipeSU);
1483 ++MFMAChains;
1484 }
1485 }
1486
1487 if (!MFMAChains)
1488 return false;
1489
1490 for (auto Pred : MFMAChainSeeds[0]->Preds) {
1491 if (TII->isDS(Pred.getSUnit()->getInstr()->getOpcode()) &&
1492 Pred.getSUnit()->getInstr()->mayLoad())
1493 FirstPipeDSR = Pred.getSUnit()->NodeNum;
1494 }
1495
1496 MFMAChainLength = MFMAPipeCount / MFMAChains;
1497
1498 // The number of bit pack operations that depend on a single V_EXP
1499 unsigned PackSuccCount = std::count_if(
1500 PackSUs.begin(), PackSUs.end(), [this, &TempExp](SUnit *VPack) {
1501 return DAG->IsReachable(VPack, *TempExp);
1502 });
1503
1504 // The number of bit pack operations an MFMA depends on
1505 unsigned PackPredCount =
1506 std::count_if((*TempMFMA)->Preds.begin(), (*TempMFMA)->Preds.end(),
1507 [&isBitPack](SDep &Pred) {
1508 auto Opc = Pred.getSUnit()->getInstr()->getOpcode();
1509 return isBitPack(Opc);
1510 });
1511
1512 auto PackPred =
1513 std::find_if((*TempMFMA)->Preds.begin(), (*TempMFMA)->Preds.end(),
1514 [&isBitPack](SDep &Pred) {
1515 auto Opc = Pred.getSUnit()->getInstr()->getOpcode();
1516 return isBitPack(Opc);
1517 });
1518
1519 if (PackPred == (*TempMFMA)->Preds.end())
1520 return false;
1521
1522 MFMAEnablement = 0;
1523 ExpRequirement = 0;
1524 // How many MFMAs depend on a single bit pack operation
1525 MFMAEnablement =
1526 std::count_if(PackPred->getSUnit()->Succs.begin(),
1527 PackPred->getSUnit()->Succs.end(), [&TII](SDep &Succ) {
1528 return TII->isMFMAorWMMA(*Succ.getSUnit()->getInstr());
1529 });
1530
1531 // The number of MFMAs that depend on a single V_EXP
1532 MFMAEnablement *= PackSuccCount;
1533
1534 // The number of V_EXPs required to resolve all dependencies for an MFMA
1535 ExpRequirement =
1536 std::count_if(ExpPipeCands.begin(), ExpPipeCands.end(),
1537 [this, &PackPred](SUnit *ExpBase) {
1538 return DAG->IsReachable(PackPred->getSUnit(), ExpBase);
1539 });
1540
1541 ExpRequirement *= PackPredCount;
1542 return true;
1543}
1544
1545bool MFMAExpInterleaveOpt::shouldApplyStrategy(ScheduleDAGInstrs *DAG,
1547 const GCNSubtarget &ST = DAG->MF.getSubtarget<GCNSubtarget>();
1548 const SIInstrInfo *TII = ST.getInstrInfo();
1549
1550 if (Phase != AMDGPU::SchedulingPhase::PostRA)
1551 MFMAChainSeeds.clear();
1552 if (Phase != AMDGPU::SchedulingPhase::PostRA && !analyzeDAG(TII))
1553 return false;
1554
1555 return true;
1556}
1557
1558bool MFMAExpInterleaveOpt::applyIGLPStrategy(
1560 DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
1562
1563 bool IsSmallKernelType =
1564 MFMAEnablement == 2 && ExpRequirement == 4 && TransPipeCount == 32;
1565 bool IsLargeKernelType =
1566 MFMAEnablement == 4 && ExpRequirement == 4 && TransPipeCount == 64;
1567
1568 if (!(IsSmallKernelType || IsLargeKernelType))
1569 return false;
1570
1571 const GCNSubtarget &ST = DAG->MF.getSubtarget<GCNSubtarget>();
1572 const SIInstrInfo *TII = ST.getInstrInfo();
1573
1574 unsigned PipelineSyncID = 0;
1575 SchedGroup *SG = nullptr;
1576
1577 unsigned MFMAChain = 0;
1578 unsigned PositionInChain = 0;
1579 unsigned CurrMFMAForTransPosition = 0;
1580
1581 auto incrementTransPosition = [&MFMAChain, &PositionInChain,
1582 &CurrMFMAForTransPosition]() {
1583 CurrMFMAForTransPosition += MFMAEnablement;
1584 PositionInChain = (CurrMFMAForTransPosition / MFMAChains);
1585 MFMAChain = CurrMFMAForTransPosition % MFMAChains;
1586 };
1587
1588 auto getNextTransPositionInChain = [&CurrMFMAForTransPosition]() {
1589 auto TempMFMAForTrans = CurrMFMAForTransPosition + MFMAEnablement;
1590 return (TempMFMAForTrans / MFMAChains);
1591 };
1592
1593 auto getNextTransMFMAChain = [&CurrMFMAForTransPosition]() {
1594 auto TempMFMAForTrans = CurrMFMAForTransPosition + MFMAEnablement;
1595 return TempMFMAForTrans % MFMAChains;
1596 };
1597
1598 unsigned CurrMFMAPosition = 0;
1599 unsigned MFMAChainForMFMA = 0;
1600 unsigned PositionInChainForMFMA = 0;
1601
1602 auto incrementMFMAPosition = [&CurrMFMAPosition, &MFMAChainForMFMA,
1603 &PositionInChainForMFMA]() {
1604 ++CurrMFMAPosition;
1605 MFMAChainForMFMA = CurrMFMAPosition % MFMAChains;
1606 PositionInChainForMFMA = CurrMFMAPosition / MFMAChains;
1607 };
1608
1609 bool IsPostRA = Phase == AMDGPU::SchedulingPhase::PostRA;
1610 assert(IsPostRA || MFMAChainSeeds.size() == MFMAChains);
1611
1612 bool UsesFMA = IsSmallKernelType || !IsPostRA;
1613 bool UsesDSRead = IsLargeKernelType && !IsPostRA && FirstPipeDSR;
1614 bool UsesCvt = HasCvt && (IsSmallKernelType || !IsPostRA);
1615 bool UsesVALU = IsSmallKernelType;
1616
1617 // PHASE 1: "Prefetch"
1618 if (UsesFMA) {
1619 // First Round FMA
1620 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1621 SchedGroupMask::VALU, ExpRequirement, PipelineSyncID, DAG, TII);
1622 if (!IsPostRA && MFMAChains) {
1623 SG->addRule(std::make_shared<EnablesNthMFMAInChain>(
1624 PositionInChain, MFMAChainSeeds[MFMAChain], TII, SG->getSGID(),
1625 true));
1626 } else
1627 SG->addRule(
1628 std::make_shared<EnablesNthMFMA>(1, TII, SG->getSGID(), true));
1629 SG->addRule(std::make_shared<IsFMA>(TII, SG->getSGID()));
1630 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1631
1632 // Second Round FMA
1633 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1634 SchedGroupMask::VALU, ExpRequirement, PipelineSyncID, DAG, TII);
1635 if (!IsPostRA && MFMAChains) {
1636 SG->addRule(std::make_shared<EnablesNthMFMAInChain>(
1637 getNextTransPositionInChain(),
1638 MFMAChainSeeds[getNextTransMFMAChain()], TII, SG->getSGID(), true));
1639 } else
1640 SG->addRule(std::make_shared<EnablesNthMFMA>(MFMAEnablement + 1, TII,
1641 SG->getSGID(), true));
1642 SG->addRule(std::make_shared<IsFMA>(TII, SG->getSGID()));
1643 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1644 }
1645
1646 if (UsesDSRead) {
1647 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1648 SchedGroupMask::DS_READ, 2, PipelineSyncID, DAG, TII);
1649 SG->addRule(std::make_shared<OccursAtOrAfterNode>(*FirstPipeDSR, TII,
1650 SG->getSGID()));
1651 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1652 }
1653
1654 // First Round EXP
1655 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1656 SchedGroupMask::TRANS, ExpRequirement, PipelineSyncID, DAG, TII);
1657 if (!IsPostRA && MFMAChains)
1658 SG->addRule(std::make_shared<EnablesNthMFMAInChain>(
1659 PositionInChain, MFMAChainSeeds[MFMAChain], TII, SG->getSGID(), true));
1660 else
1661 SG->addRule(std::make_shared<EnablesNthMFMA>(1, TII, SG->getSGID(), true));
1662 SG->addRule(std::make_shared<IsPipeExp>(TII, SG->getSGID(), true));
1663 SG->addRule(std::make_shared<LessThanNSuccs>(8, TII, SG->getSGID(),
1664 HasChainBetweenCvt));
1665 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1666
1667 incrementTransPosition();
1668
1669 // First Round CVT, Third Round FMA, Second Round EXP; interleaved
1670 for (unsigned I = 0; I < ExpRequirement; I++) {
1671 // First Round CVT
1672 if (UsesCvt) {
1673 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1674 SchedGroupMask::VALU, 1, PipelineSyncID, DAG, TII);
1675 SG->addRule(std::make_shared<IsCvt>(TII, SG->getSGID()));
1676 if (HasChainBetweenCvt)
1677 SG->addRule(std::make_shared<IsReachableFromPrevNthGroup>(
1678 1 + (2 + UsesFMA) * I, TII, SG->getSGID()));
1679 else
1680 SG->addRule(std::make_shared<IsSuccOfPrevNthGroup>(
1681 1 + (2 + UsesFMA) * I, TII, SG->getSGID()));
1682 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1683 }
1684
1685 // Third Round FMA
1686 if (UsesFMA) {
1687 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1688 SchedGroupMask::VALU, 1, PipelineSyncID, DAG, TII);
1689 if (!IsPostRA && MFMAChains) {
1690 SG->addRule(std::make_shared<EnablesNthMFMAInChain>(
1691 getNextTransPositionInChain(),
1692 MFMAChainSeeds[getNextTransMFMAChain()], TII, SG->getSGID(), true));
1693 } else
1694 SG->addRule(std::make_shared<EnablesNthMFMA>(2 * MFMAEnablement + 1,
1695 TII, SG->getSGID(), true));
1696 SG->addRule(std::make_shared<IsFMA>(TII, SG->getSGID()));
1697 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1698 }
1699
1700 // Second Round EXP
1701 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1702 SchedGroupMask::TRANS, 1, PipelineSyncID, DAG, TII);
1703 if (!IsPostRA && MFMAChains)
1704 SG->addRule(std::make_shared<EnablesNthMFMAInChain>(
1705 PositionInChain, MFMAChainSeeds[MFMAChain], TII, SG->getSGID(),
1706 true));
1707 else
1708 SG->addRule(std::make_shared<EnablesNthMFMA>(MFMAEnablement + 1, TII,
1709 SG->getSGID(), true));
1710 SG->addRule(std::make_shared<IsPipeExp>(TII, SG->getSGID(), true));
1711 SG->addRule(std::make_shared<LessThanNSuccs>(8, TII, SG->getSGID(),
1712 HasChainBetweenCvt));
1713 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1714 }
1715
1716 // The "extra" EXP which enables all MFMA
1717 // TODO: UsesExtraExp
1718 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1719 SchedGroupMask::TRANS, 1, PipelineSyncID, DAG, TII);
1720 SG->addRule(std::make_shared<IsPipeExp>(TII, SG->getSGID(), true));
1721 SG->addRule(std::make_shared<GreaterThanOrEqualToNSuccs>(
1722 8, TII, SG->getSGID(), HasChainBetweenCvt));
1723 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1724
1725 // PHASE 2: Main Interleave Loop
1726
1727 // The number of MFMAs per iteration
1728 unsigned MFMARatio =
1729 MFMAEnablement > ExpRequirement ? MFMAEnablement / ExpRequirement : 1;
1730 // The number of Exps per iteration
1731 unsigned ExpRatio =
1732 MFMAEnablement > ExpRequirement ? 1 : ExpRequirement / MFMAEnablement;
1733 // The reamaining Exps
1734 unsigned RemainingExp = TransPipeCount > (2 * ExpRequirement)
1735 ? TransPipeCount - (2 * ExpRequirement)
1736 : 0;
1737 unsigned ExpLoopCount = RemainingExp / ExpRatio;
1738 // In loop MFMAs
1739 unsigned MFMAInLoop = MFMAPipeCount > (MFMAEnablement * 2)
1740 ? MFMAPipeCount - (MFMAEnablement * 2)
1741 : 0;
1742 unsigned MFMALoopCount = MFMAInLoop / MFMARatio;
1743 unsigned VALUOps =
1744 AddPipeCount < MFMAPipeCount ? 1 : AddPipeCount / MFMAPipeCount;
1745 unsigned LoopSize = std::min(ExpLoopCount, MFMALoopCount);
1746
1747 for (unsigned I = 0; I < LoopSize; I++) {
1748 if (!(I * ExpRatio % ExpRequirement))
1749 incrementTransPosition();
1750
1751 // Round N MFMA
1752 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1753 SchedGroupMask::MFMA, MFMARatio, PipelineSyncID, DAG, TII);
1754 if (!IsPostRA && MFMAChains)
1755 SG->addRule(std::make_shared<IsExactMFMA>(
1756 PositionInChainForMFMA, MFMAChainSeeds[MFMAChainForMFMA], TII,
1757 SG->getSGID(), true));
1758 else
1759 SG->addRule(std::make_shared<OccursAfterExp>(TII, SG->getSGID(), true));
1760 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1761 incrementMFMAPosition();
1762
1763 if (UsesVALU) {
1764 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1765 SchedGroupMask::VALU, VALUOps, PipelineSyncID, DAG, TII);
1766 SG->addRule(std::make_shared<IsPipeAdd>(TII, SG->getSGID()));
1767 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1768 }
1769
1770 if (UsesDSRead && !(I % 4)) {
1771 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1772 SchedGroupMask::DS_READ, 2, PipelineSyncID, DAG, TII);
1773 SG->addRule(std::make_shared<OccursAtOrAfterNode>(*FirstPipeDSR, TII,
1774 SG->getSGID()));
1775 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1776 }
1777
1778 // CVT, EXP, FMA Interleaving
1779 for (unsigned J = 0; J < ExpRatio; J++) {
1780 auto MFMAOffset = (1 + UsesVALU) * MFMARatio * (I + 1);
1781 auto MaxMFMAOffset =
1782 (1 + UsesVALU) * ExpRequirement * MFMARatio / ExpRatio;
1783
1784 // Round N + 1 CVT
1785 if (UsesCvt) {
1786 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1787 SchedGroupMask::VALU, 1, PipelineSyncID, DAG, TII);
1788 SG->addRule(std::make_shared<IsCvt>(TII, SG->getSGID()));
1789 auto BaseDiff = (2 + UsesFMA) * (ExpRequirement - 1) + 1;
1790 auto DSROffset = I / 4 + 1;
1791 auto MaxDSROffset = MaxMFMAOffset / 4;
1792 // TODO: UsesExtraExp
1793 auto ExpOffset = I * ExpRatio + J >= ExpRequirement ? 0 : 1;
1794 auto CurrentOffset = UsesDSRead * std::min(MaxDSROffset, DSROffset) +
1795 std::min(MaxMFMAOffset, MFMAOffset) + BaseDiff +
1796 ExpOffset;
1797 if (HasChainBetweenCvt)
1798 SG->addRule(std::make_shared<IsReachableFromPrevNthGroup>(
1799 CurrentOffset, TII, SG->getSGID()));
1800 else
1801 SG->addRule(std::make_shared<IsSuccOfPrevNthGroup>(CurrentOffset, TII,
1802 SG->getSGID()));
1803 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1804 }
1805
1806 // Round N + 3 FMA
1807 if (UsesFMA) {
1808 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1809 SchedGroupMask::VALU, 1, PipelineSyncID, DAG, TII);
1810 if (!IsPostRA && MFMAChains)
1811 SG->addRule(std::make_shared<EnablesNthMFMAInChain>(
1812 getNextTransPositionInChain(),
1813 MFMAChainSeeds[getNextTransMFMAChain()], TII, SG->getSGID(),
1814 true));
1815 else
1816 SG->addRule(std::make_shared<EnablesNthMFMA>(
1817 (((I * ExpRatio + J) / ExpRequirement) + 3) * MFMAEnablement + 1,
1818 TII, SG->getSGID(), true));
1819 SG->addRule(std::make_shared<IsFMA>(TII, SG->getSGID()));
1820 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1821 }
1822
1823 // Round N + 2 Exp
1824 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1825 SchedGroupMask::TRANS, 1, PipelineSyncID, DAG, TII);
1826 if (!IsPostRA && MFMAChains)
1827 SG->addRule(std::make_shared<EnablesNthMFMAInChain>(
1828 PositionInChain, MFMAChainSeeds[MFMAChain], TII, SG->getSGID(),
1829 true));
1830 else
1831 SG->addRule(std::make_shared<EnablesNthMFMA>(
1832 (((I * ExpRatio + J) / ExpRequirement) + 2) * MFMAEnablement + 1,
1833 TII, SG->getSGID(), true));
1834 SG->addRule(std::make_shared<IsPipeExp>(TII, SG->getSGID(), true));
1835 SG->addRule(std::make_shared<LessThanNSuccs>(8, TII, SG->getSGID(),
1836 HasChainBetweenCvt));
1837 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1838 }
1839 }
1840
1841 // PHASE 3: Remaining MFMAs
1842 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
1843 SchedGroupMask::MFMA, MFMAEnablement * 2, PipelineSyncID, DAG, TII);
1844 SG->addRule(std::make_shared<OccursAfterExp>(TII, SG->getSGID(), true));
1845 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
1846 return true;
1847}
1848
1849class MFMASmallGemmSingleWaveOpt final : public IGLPStrategy {
1850private:
1851 // Whether the DS_READ is a predecessor of first four MFMA in region
1852 class EnablesInitialMFMA final : public InstructionRule {
1853 public:
1854 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1855 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1856 if (!SyncPipe.size())
1857 return false;
1858 int MFMAsFound = 0;
1859 if (!Cache->size()) {
1860 for (auto &Elt : SyncPipe[0].DAG->SUnits) {
1861 if (TII->isMFMAorWMMA(*Elt.getInstr())) {
1862 ++MFMAsFound;
1863 if (MFMAsFound > 4)
1864 break;
1865 Cache->push_back(&Elt);
1866 }
1867 }
1868 }
1869
1870 assert(Cache->size());
1871 auto DAG = SyncPipe[0].DAG;
1872 for (auto &Elt : *Cache) {
1873 if (DAG->IsReachable(Elt, const_cast<SUnit *>(SU)))
1874 return true;
1875 }
1876 return false;
1877 }
1878
1879 EnablesInitialMFMA(const SIInstrInfo *TII, unsigned SGID,
1880 bool NeedsCache = false)
1881 : InstructionRule(TII, SGID, NeedsCache) {}
1882 };
1883
1884 // Whether the MI is a V_PERM and is a predecessor of a common DS_WRITE
1885 class IsPermForDSW final : public InstructionRule {
1886 public:
1887 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1888 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1889 auto MI = SU->getInstr();
1890 if (MI->getOpcode() != AMDGPU::V_PERM_B32_e64)
1891 return false;
1892
1893 bool FitsInGroup = false;
1894 // Does the VALU have a DS_WRITE successor
1895 if (!Collection.size()) {
1896 for (auto &Succ : SU->Succs) {
1897 SUnit *SuccUnit = Succ.getSUnit();
1898 if (TII->isDS(*SuccUnit->getInstr()) &&
1899 SuccUnit->getInstr()->mayStore()) {
1900 Cache->push_back(SuccUnit);
1901 FitsInGroup = true;
1902 }
1903 }
1904 return FitsInGroup;
1905 }
1906
1907 assert(Cache->size());
1908
1909 // Does the VALU have a DS_WRITE successor that is the same as other
1910 // VALU already in the group. The V_PERMs will all share 1 DS_W succ
1911 return llvm::any_of(*Cache, [&SU](SUnit *Elt) {
1912 return llvm::any_of(SU->Succs, [&Elt](const SDep &ThisSucc) {
1913 return ThisSucc.getSUnit() == Elt;
1914 });
1915 });
1916 }
1917
1918 IsPermForDSW(const SIInstrInfo *TII, unsigned SGID, bool NeedsCache = false)
1919 : InstructionRule(TII, SGID, NeedsCache) {}
1920 };
1921
1922 // Whether the SU is a successor of any element in previous SchedGroup
1923 class IsSuccOfPrevGroup final : public InstructionRule {
1924 public:
1925 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1926 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1927 SchedGroup *OtherGroup = nullptr;
1928 for (auto &PipeSG : SyncPipe) {
1929 if ((unsigned)PipeSG.getSGID() == SGID - 1) {
1930 OtherGroup = &PipeSG;
1931 }
1932 }
1933
1934 if (!OtherGroup)
1935 return false;
1936 if (!OtherGroup->Collection.size())
1937 return true;
1938
1939 // Does the previous VALU have this DS_Write as a successor
1940 return any_of(OtherGroup->Collection, [&SU](SUnit *Elt) {
1941 return any_of(Elt->Succs,
1942 [&SU](SDep &Succ) { return Succ.getSUnit() == SU; });
1943 });
1944 }
1945 IsSuccOfPrevGroup(const SIInstrInfo *TII, unsigned SGID,
1946 bool NeedsCache = false)
1947 : InstructionRule(TII, SGID, NeedsCache) {}
1948 };
1949
1950 // Whether the combined load width of group is 128 bits
1951 class VMEMSize final : public InstructionRule {
1952 public:
1953 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1954 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1955 auto MI = SU->getInstr();
1956 if (MI->getOpcode() == TargetOpcode::BUNDLE)
1957 return false;
1958 if (!Collection.size())
1959 return true;
1960
1961 int NumBits = 0;
1962
1963 auto TRI = TII->getRegisterInfo();
1964 auto &MRI = MI->getParent()->getParent()->getRegInfo();
1965 for (auto &Elt : Collection) {
1966 auto Op = Elt->getInstr()->getOperand(0);
1967 auto Size =
1968 TRI.getRegSizeInBits(*TRI.getRegClassForOperandReg(MRI, Op));
1969 NumBits += Size;
1970 }
1971
1972 if (NumBits < 128) {
1973 assert(TII->isVMEM(*MI) && MI->mayLoad());
1974 if (NumBits + TRI.getRegSizeInBits(*TRI.getRegClassForOperandReg(
1975 MRI, MI->getOperand(0))) <=
1976 128)
1977 return true;
1978 }
1979
1980 return false;
1981 }
1982
1983 VMEMSize(const SIInstrInfo *TII, unsigned SGID, bool NeedsCache = false)
1984 : InstructionRule(TII, SGID, NeedsCache) {}
1985 };
1986
1987 /// Whether the SU shares a V_PERM predecessor with any SU in the SchedGroup
1988 /// that is \p Distance steps away
1989 class SharesPredWithPrevNthGroup final : public InstructionRule {
1990 private:
1991 unsigned Distance = 1;
1992
1993 public:
1994 bool apply(const SUnit *SU, const ArrayRef<SUnit *> Collection,
1995 SmallVectorImpl<SchedGroup> &SyncPipe) override {
1996 SchedGroup *OtherGroup = nullptr;
1997 if (!SyncPipe.size())
1998 return false;
1999
2000 if (!Cache->size()) {
2001
2002 for (auto &PipeSG : SyncPipe) {
2003 if ((unsigned)PipeSG.getSGID() == SGID - Distance) {
2004 OtherGroup = &PipeSG;
2005 }
2006 }
2007
2008 if (!OtherGroup)
2009 return false;
2010 if (!OtherGroup->Collection.size())
2011 return true;
2012
2013 for (auto &OtherEle : OtherGroup->Collection) {
2014 for (auto &Pred : OtherEle->Preds) {
2015 if (Pred.getSUnit()->getInstr()->getOpcode() ==
2016 AMDGPU::V_PERM_B32_e64)
2017 Cache->push_back(Pred.getSUnit());
2018 }
2019 }
2020
2021 // If the other group has no PERM preds, then this group won't share any
2022 if (!Cache->size())
2023 return false;
2024 }
2025
2026 auto DAG = SyncPipe[0].DAG;
2027 // Does the previous DS_WRITE share a V_PERM predecessor with this
2028 // VMEM_READ
2029 return llvm::any_of(*Cache, [&SU, &DAG](SUnit *Elt) {
2030 return DAG->IsReachable(const_cast<SUnit *>(SU), Elt);
2031 });
2032 }
2033 SharesPredWithPrevNthGroup(unsigned Distance, const SIInstrInfo *TII,
2034 unsigned SGID, bool NeedsCache = false)
2035 : InstructionRule(TII, SGID, NeedsCache), Distance(Distance) {}
2036 };
2037
2038public:
2039 bool applyIGLPStrategy(
2041 DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
2043
2044 bool shouldApplyStrategy(ScheduleDAGInstrs *DAG,
2045 AMDGPU::SchedulingPhase Phase) override {
2046 return true;
2047 }
2048
2049 MFMASmallGemmSingleWaveOpt(ScheduleDAGInstrs *DAG, const SIInstrInfo *TII)
2050 : IGLPStrategy(DAG, TII) {
2051 IsBottomUp = false;
2052 }
2053};
2054
2055static unsigned DSWCount = 0;
2056static unsigned DSWWithPermCount = 0;
2057static unsigned DSWWithSharedVMEMCount = 0;
2058
2059bool MFMASmallGemmSingleWaveOpt::applyIGLPStrategy(
2061 DenseMap<int, SmallVector<SchedGroup, 4>> &SyncedSchedGroups,
2063 unsigned MFMACount = 0;
2064 unsigned DSRCount = 0;
2065
2066 bool IsInitial = Phase == AMDGPU::SchedulingPhase::Initial;
2067
2068 assert((!IsInitial || (DSWCount == 0 && DSWWithPermCount == 0 &&
2069 DSWWithSharedVMEMCount == 0)) &&
2070 "DSWCounters should be zero in pre-RA scheduling!");
2071 SmallVector<SUnit *, 6> DSWithPerms;
2072 for (auto &SU : DAG->SUnits) {
2073 auto I = SU.getInstr();
2074 if (TII->isMFMAorWMMA(*I))
2075 ++MFMACount;
2076 else if (TII->isDS(*I)) {
2077 if (I->mayLoad())
2078 ++DSRCount;
2079 else if (I->mayStore() && IsInitial) {
2080 ++DSWCount;
2081 for (auto Pred : SU.Preds) {
2082 if (Pred.getSUnit()->getInstr()->getOpcode() ==
2083 AMDGPU::V_PERM_B32_e64) {
2084 DSWithPerms.push_back(&SU);
2085 break;
2086 }
2087 }
2088 }
2089 }
2090 }
2091
2092 if (IsInitial) {
2093 DSWWithPermCount = DSWithPerms.size();
2094 auto I = DSWithPerms.begin();
2095 auto E = DSWithPerms.end();
2096
2097 // Get the count of DS_WRITES with V_PERM predecessors which
2098 // have loop carried dependencies (WAR) on the same VMEM_READs.
2099 // We consider partial overlap as a miss -- in other words,
2100 // for a given DS_W, we only consider another DS_W as matching
2101 // if there is a corresponding (in terms of the VMEM_R it uses) V_PERM pred
2102 // for every V_PERM pred of this DS_W.
2105 for (; I != E; I++) {
2106 SUnit *Cand = nullptr;
2107 bool MissedAny = false;
2108 for (auto &Pred : (*I)->Preds) {
2109 if (Pred.getSUnit()->getInstr()->getOpcode() != AMDGPU::V_PERM_B32_e64)
2110 continue;
2111
2112 if (Cand && llvm::is_contained(Counted, Cand))
2113 break;
2114
2115 for (auto &Succ : Pred.getSUnit()->Succs) {
2116 auto MI = Succ.getSUnit()->getInstr();
2117 if (!TII->isVMEM(*MI) || !MI->mayLoad())
2118 continue;
2119
2120 if (MissedAny || !VMEMLookup.size()) {
2121 MissedAny = true;
2122 VMEMLookup[MI] = *I;
2123 continue;
2124 }
2125
2126 if (!VMEMLookup.contains(MI)) {
2127 MissedAny = true;
2128 VMEMLookup[MI] = *I;
2129 continue;
2130 }
2131
2132 Cand = VMEMLookup[MI];
2133 if (llvm::is_contained(Counted, Cand)) {
2134 MissedAny = true;
2135 break;
2136 }
2137 }
2138 }
2139 if (!MissedAny && Cand) {
2140 DSWWithSharedVMEMCount += 2;
2141 Counted.push_back(Cand);
2142 Counted.push_back(*I);
2143 }
2144 }
2145 }
2146
2147 assert(DSWWithSharedVMEMCount <= DSWWithPermCount);
2148 SchedGroup *SG;
2149 unsigned PipelineSyncID = 0;
2150 // For kernels with V_PERM, there are enough VALU to mix in between MFMAs
2151 if (DSWWithPermCount) {
2152 for (unsigned I = 0; I < MFMACount; I++) {
2153 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2154 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2155 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2156
2157 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2158 SchedGroupMask::VALU, 2, PipelineSyncID, DAG, TII);
2159 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2160 }
2161 }
2162
2163 PipelineSyncID = 1;
2164 // Phase 1: Break up DS_READ and MFMA clusters.
2165 // First DS_READ to make ready initial MFMA, then interleave MFMA with DS_READ
2166 // prefetch
2167
2168 // Make ready initial MFMA
2169 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2170 SchedGroupMask::DS_READ, 4, PipelineSyncID, DAG, TII);
2171 SG->addRule(std::make_shared<EnablesInitialMFMA>(TII, SG->getSGID(), true));
2172 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2173
2174 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2175 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2176 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2177
2178 // Interleave MFMA with DS_READ prefetch
2179 for (unsigned I = 0; I < DSRCount - 4; ++I) {
2180 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2181 SchedGroupMask::DS_READ, 1, PipelineSyncID, DAG, TII);
2182 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2183
2184 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2185 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2186 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2187 }
2188
2189 // Phase 2a: Loop carried dependency with V_PERM
2190 // Schedule VPerm & DS_WRITE as closely as possible to the VMEM_READ they
2191 // depend on. Interleave MFMA to keep XDL unit busy throughout.
2192 for (unsigned I = 0; I < DSWWithPermCount - DSWWithSharedVMEMCount; ++I) {
2193 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2194 SchedGroupMask::VALU, 4, PipelineSyncID, DAG, TII);
2195 SG->addRule(std::make_shared<IsPermForDSW>(TII, SG->getSGID(), true));
2196 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2197
2198 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2199 SchedGroupMask::DS_WRITE, 1, PipelineSyncID, DAG, TII);
2200 SG->addRule(std::make_shared<IsSuccOfPrevGroup>(TII, SG->getSGID()));
2201 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2202
2203 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2204 SchedGroupMask::VMEM_READ, 4, PipelineSyncID, DAG, TII);
2205 SG->addRule(std::make_shared<SharesPredWithPrevNthGroup>(
2206 1, TII, SG->getSGID(), true));
2207 SG->addRule(std::make_shared<VMEMSize>(TII, SG->getSGID()));
2208 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2209
2210 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2211 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2212 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2213
2214 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2215 SchedGroupMask::VMEM_READ, 4, PipelineSyncID, DAG, TII);
2216 SG->addRule(std::make_shared<SharesPredWithPrevNthGroup>(
2217 3, TII, SG->getSGID(), true));
2218 SG->addRule(std::make_shared<VMEMSize>(TII, SG->getSGID()));
2219 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2220
2221 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2222 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2223 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2224 }
2225
2226 // Phase 2b: Loop carried dependency without V_PERM
2227 // Schedule DS_WRITE as closely as possible to the VMEM_READ they depend on.
2228 // Interleave MFMA to keep XDL unit busy throughout.
2229 for (unsigned I = 0; I < DSWCount - DSWWithPermCount; I++) {
2230 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2231 SchedGroupMask::DS_WRITE, 1, PipelineSyncID, DAG, TII);
2232 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2233
2234 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2235 SchedGroupMask::VMEM_READ, 4, PipelineSyncID, DAG, TII);
2236 SG->addRule(std::make_shared<VMEMSize>(TII, SG->getSGID()));
2237 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2238
2239 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2240 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2241 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2242 }
2243
2244 // Phase 2c: Loop carried dependency with V_PERM, VMEM_READs are
2245 // ultimately used by two DS_WRITE
2246 // Schedule VPerm & DS_WRITE as closely as possible to the VMEM_READ they
2247 // depend on. Interleave MFMA to keep XDL unit busy throughout.
2248
2249 for (unsigned I = 0; I < DSWWithSharedVMEMCount; ++I) {
2250 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2251 SchedGroupMask::VALU, 4, PipelineSyncID, DAG, TII);
2252 SG->addRule(std::make_shared<IsPermForDSW>(TII, SG->getSGID(), true));
2253 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2254
2255 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2256 SchedGroupMask::DS_WRITE, 1, PipelineSyncID, DAG, TII);
2257 SG->addRule(std::make_shared<IsSuccOfPrevGroup>(TII, SG->getSGID()));
2258 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2259
2260 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2261 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2262 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2263
2264 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2265 SchedGroupMask::VALU, 4, PipelineSyncID, DAG, TII);
2266 SG->addRule(std::make_shared<IsPermForDSW>(TII, SG->getSGID(), true));
2267 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2268
2269 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2270 SchedGroupMask::DS_WRITE, 1, PipelineSyncID, DAG, TII);
2271 SG->addRule(std::make_shared<IsSuccOfPrevGroup>(TII, SG->getSGID()));
2272 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2273
2274 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2275 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2276 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2277
2278 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2279 SchedGroupMask::VMEM_READ, 4, PipelineSyncID, DAG, TII);
2280 SG->addRule(std::make_shared<SharesPredWithPrevNthGroup>(
2281 2, TII, SG->getSGID(), true));
2282 SG->addRule(std::make_shared<VMEMSize>(TII, SG->getSGID()));
2283 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2284
2285 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2286 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2287 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2288
2289 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2290 SchedGroupMask::VMEM_READ, 4, PipelineSyncID, DAG, TII);
2291 SG->addRule(std::make_shared<SharesPredWithPrevNthGroup>(
2292 4, TII, SG->getSGID(), true));
2293 SG->addRule(std::make_shared<VMEMSize>(TII, SG->getSGID()));
2294 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2295
2296 SG = &SyncedSchedGroups[PipelineSyncID].emplace_back(
2297 SchedGroupMask::MFMA, 1, PipelineSyncID, DAG, TII);
2298 SG->initSchedGroup(SyncedInstrs[SG->getSyncID()]);
2299 }
2300
2301 return true;
2302}
2303
2304static std::unique_ptr<IGLPStrategy>
2305createIGLPStrategy(IGLPStrategyID ID, ScheduleDAGInstrs *DAG,
2306 const SIInstrInfo *TII) {
2307 switch (ID) {
2308 case MFMASmallGemmOptID:
2309 return std::make_unique<MFMASmallGemmOpt>(DAG, TII);
2310 case MFMASmallGemmSingleWaveOptID:
2311 return std::make_unique<MFMASmallGemmSingleWaveOpt>(DAG, TII);
2312 case MFMAExpInterleave:
2313 return std::make_unique<MFMAExpInterleaveOpt>(DAG, TII);
2314 }
2315
2316 llvm_unreachable("Unknown IGLPStrategyID");
2317}
2318
2319class IGroupLPDAGMutation : public ScheduleDAGMutation {
2320private:
2321 const SIInstrInfo *TII;
2322
2323 ScheduleDAGMI *DAG;
2324
2325 // Organize lists of SchedGroups by their SyncID. SchedGroups /
2326 // SCHED_GROUP_BARRIERs with different SyncIDs will have no edges added
2327 // between then.
2329
2330 // Used to track instructions that can be mapped to multiple sched groups
2332
2333 // Add DAG edges that enforce SCHED_BARRIER ordering.
2334 void addSchedBarrierEdges(SUnit &SU);
2335
2336 // Use a SCHED_BARRIER's mask to identify instruction SchedGroups that should
2337 // not be reordered accross the SCHED_BARRIER. This is used for the base
2338 // SCHED_BARRIER, and not SCHED_GROUP_BARRIER. The difference is that
2339 // SCHED_BARRIER will always block all instructions that can be classified
2340 // into a particular SchedClass, whereas SCHED_GROUP_BARRIER has a fixed size
2341 // and may only synchronize with some SchedGroups. Returns the inverse of
2342 // Mask. SCHED_BARRIER's mask describes which instruction types should be
2343 // allowed to be scheduled across it. Invert the mask to get the
2344 // SchedGroupMask of instructions that should be barred.
2345 SchedGroupMask invertSchedBarrierMask(SchedGroupMask Mask) const;
2346
2347 // Create SchedGroups for a SCHED_GROUP_BARRIER.
2348 void initSchedGroupBarrierPipelineStage(
2349 std::vector<SUnit>::reverse_iterator RIter);
2350
2351 bool initIGLPOpt(SUnit &SU);
2352
2353public:
2354 void apply(ScheduleDAGInstrs *DAGInstrs) override;
2355
2356 // The order in which the PipelineSolver should process the candidate
2357 // SchedGroup for a PipelineInstr. BOTTOM_UP will try to add SUs to the last
2358 // created SchedGroup first, and will consider that as the ultimate
2359 // predecessor group when linking. TOP_DOWN instead links and processes the
2360 // first created SchedGroup first.
2361 bool IsBottomUp = true;
2362
2363 // The scheduling phase this application of IGLP corresponds with.
2365
2366 IGroupLPDAGMutation() = default;
2367 IGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase) : Phase(Phase) {}
2368};
2369
2370unsigned SchedGroup::NumSchedGroups = 0;
2371
2372bool SchedGroup::tryAddEdge(SUnit *A, SUnit *B) {
2373 if (A != B && DAG->canAddEdge(B, A)) {
2374 DAG->addEdge(B, SDep(A, SDep::Artificial));
2375 return true;
2376 }
2377 return false;
2378}
2379
2380bool SchedGroup::canAddMI(const MachineInstr &MI) const {
2381 bool Result = false;
2382 if (MI.isMetaInstruction())
2383 Result = false;
2384
2385 else if (((SGMask & SchedGroupMask::ALU) != SchedGroupMask::NONE) &&
2386 (TII->isVALU(MI) || TII->isMFMAorWMMA(MI) || TII->isSALU(MI) ||
2387 TII->isTRANS(MI)))
2388 Result = true;
2389
2390 else if (((SGMask & SchedGroupMask::VALU) != SchedGroupMask::NONE) &&
2391 TII->isVALU(MI) && !TII->isMFMAorWMMA(MI) && !TII->isTRANS(MI))
2392 Result = true;
2393
2394 else if (((SGMask & SchedGroupMask::SALU) != SchedGroupMask::NONE) &&
2395 TII->isSALU(MI))
2396 Result = true;
2397
2398 else if (((SGMask & SchedGroupMask::MFMA) != SchedGroupMask::NONE) &&
2399 TII->isMFMAorWMMA(MI))
2400 Result = true;
2401
2402 else if (((SGMask & SchedGroupMask::VMEM) != SchedGroupMask::NONE) &&
2403 (TII->isVMEM(MI) || (TII->isFLAT(MI) && !TII->isDS(MI))))
2404 Result = true;
2405
2406 else if (((SGMask & SchedGroupMask::VMEM_READ) != SchedGroupMask::NONE) &&
2407 MI.mayLoad() &&
2408 (TII->isVMEM(MI) || (TII->isFLAT(MI) && !TII->isDS(MI))))
2409 Result = true;
2410
2411 else if (((SGMask & SchedGroupMask::VMEM_WRITE) != SchedGroupMask::NONE) &&
2412 MI.mayStore() &&
2413 (TII->isVMEM(MI) || (TII->isFLAT(MI) && !TII->isDS(MI))))
2414 Result = true;
2415
2416 else if (((SGMask & SchedGroupMask::DS) != SchedGroupMask::NONE) &&
2417 TII->isDS(MI))
2418 Result = true;
2419
2420 else if (((SGMask & SchedGroupMask::DS_READ) != SchedGroupMask::NONE) &&
2421 MI.mayLoad() && TII->isDS(MI))
2422 Result = true;
2423
2424 else if (((SGMask & SchedGroupMask::DS_WRITE) != SchedGroupMask::NONE) &&
2425 MI.mayStore() && TII->isDS(MI))
2426 Result = true;
2427
2428 else if (((SGMask & SchedGroupMask::TRANS) != SchedGroupMask::NONE) &&
2429 TII->isTRANS(MI))
2430 Result = true;
2431
2432 LLVM_DEBUG(
2433 dbgs() << "For SchedGroup with mask " << format_hex((int)SGMask, 10, true)
2434 << (Result ? " could classify " : " unable to classify ") << MI);
2435
2436 return Result;
2437}
2438
2439int SchedGroup::link(SUnit &SU, bool MakePred,
2440 std::vector<std::pair<SUnit *, SUnit *>> &AddedEdges) {
2441 int MissedEdges = 0;
2442 for (auto *A : Collection) {
2443 SUnit *B = &SU;
2444 if (A == B || A->getInstr()->getOpcode() == AMDGPU::SCHED_GROUP_BARRIER)
2445 continue;
2446 if (MakePred)
2447 std::swap(A, B);
2448
2449 if (DAG->IsReachable(B, A))
2450 continue;
2451
2452 // tryAddEdge returns false if there is a dependency that makes adding
2453 // the A->B edge impossible, otherwise it returns true;
2454 bool Added = tryAddEdge(A, B);
2455 if (Added)
2456 AddedEdges.emplace_back(A, B);
2457 else
2458 ++MissedEdges;
2459 }
2460
2461 return MissedEdges;
2462}
2463
2464void SchedGroup::link(SUnit &SU, bool MakePred) {
2465 for (auto *A : Collection) {
2466 SUnit *B = &SU;
2467 if (A->getInstr()->getOpcode() == AMDGPU::SCHED_GROUP_BARRIER)
2468 continue;
2469 if (MakePred)
2470 std::swap(A, B);
2471
2472 tryAddEdge(A, B);
2473 }
2474}
2475
2476void SchedGroup::link(SUnit &SU,
2477 function_ref<bool(const SUnit *A, const SUnit *B)> P) {
2478 for (auto *A : Collection) {
2479 SUnit *B = &SU;
2480 if (P(A, B))
2481 std::swap(A, B);
2482
2483 tryAddEdge(A, B);
2484 }
2485}
2486
2487void SchedGroup::link(SchedGroup &OtherGroup) {
2488 for (auto *B : OtherGroup.Collection)
2489 link(*B);
2490}
2491
2492bool SchedGroup::canAddSU(SUnit &SU) const {
2493 MachineInstr &MI = *SU.getInstr();
2494 if (MI.getOpcode() != TargetOpcode::BUNDLE)
2495 return canAddMI(MI);
2496
2497 // Special case for bundled MIs.
2498 const MachineBasicBlock *MBB = MI.getParent();
2499 MachineBasicBlock::instr_iterator B = MI.getIterator(), E = ++B;
2500 while (E != MBB->end() && E->isBundledWithPred())
2501 ++E;
2502
2503 // Return true if all of the bundled MIs can be added to this group.
2504 return std::all_of(B, E, [this](MachineInstr &MI) { return canAddMI(MI); });
2505}
2506
2507void SchedGroup::initSchedGroup() {
2508 for (auto &SU : DAG->SUnits) {
2509 if (isFull())
2510 break;
2511
2512 if (canAddSU(SU))
2513 add(SU);
2514 }
2515}
2516
2517void SchedGroup::initSchedGroup(std::vector<SUnit>::reverse_iterator RIter,
2518 SUnitsToCandidateSGsMap &SyncedInstrs) {
2519 SUnit &InitSU = *RIter;
2520 for (auto E = DAG->SUnits.rend(); RIter != E; ++RIter) {
2521 auto &SU = *RIter;
2522 if (isFull())
2523 break;
2524
2525 if (canAddSU(SU))
2526 SyncedInstrs[&SU].push_back(SGID);
2527 }
2528
2529 add(InitSU);
2530 assert(MaxSize);
2531 (*MaxSize)++;
2532}
2533
2534void SchedGroup::initSchedGroup(SUnitsToCandidateSGsMap &SyncedInstrs) {
2535 auto I = DAG->SUnits.rbegin();
2536 auto E = DAG->SUnits.rend();
2537 for (; I != E; ++I) {
2538 auto &SU = *I;
2539 if (isFull())
2540 break;
2541 if (canAddSU(SU))
2542 SyncedInstrs[&SU].push_back(SGID);
2543 }
2544}
2545
2546void IGroupLPDAGMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
2547 const TargetSchedModel *TSchedModel = DAGInstrs->getSchedModel();
2548 if (!TSchedModel || DAGInstrs->SUnits.empty())
2549 return;
2550
2551 LLVM_DEBUG(dbgs() << "Applying IGroupLPDAGMutation...\n");
2552 const GCNSubtarget &ST = DAGInstrs->MF.getSubtarget<GCNSubtarget>();
2553 TII = ST.getInstrInfo();
2554 DAG = static_cast<ScheduleDAGMI *>(DAGInstrs);
2555 SyncedSchedGroups.clear();
2556 SyncedInstrs.clear();
2557 bool FoundSB = false;
2558 bool FoundIGLP = false;
2559 bool ShouldApplyIGLP = false;
2560 for (auto R = DAG->SUnits.rbegin(), E = DAG->SUnits.rend(); R != E; ++R) {
2561 unsigned Opc = R->getInstr()->getOpcode();
2562 // SCHED_[GROUP_]BARRIER and IGLP are mutually exclusive.
2563 if (Opc == AMDGPU::SCHED_BARRIER) {
2564 addSchedBarrierEdges(*R);
2565 FoundSB = true;
2566 } else if (Opc == AMDGPU::SCHED_GROUP_BARRIER) {
2567 initSchedGroupBarrierPipelineStage(R);
2568 FoundSB = true;
2569 } else if (Opc == AMDGPU::IGLP_OPT) {
2570 resetEdges(*R, DAG);
2571 if (!FoundSB && !FoundIGLP) {
2572 FoundIGLP = true;
2573 ShouldApplyIGLP = initIGLPOpt(*R);
2574 }
2575 }
2576 }
2577
2578 if (FoundSB || (FoundIGLP && ShouldApplyIGLP)) {
2579 PipelineSolver PS(SyncedSchedGroups, SyncedInstrs, DAG, IsBottomUp);
2580 // PipelineSolver performs the mutation by adding the edges it
2581 // determined as the best
2582 PS.solve();
2583 return;
2584 }
2585}
2586
2587void IGroupLPDAGMutation::addSchedBarrierEdges(SUnit &SchedBarrier) {
2588 MachineInstr &MI = *SchedBarrier.getInstr();
2589 assert(MI.getOpcode() == AMDGPU::SCHED_BARRIER);
2590 // Remove all existing edges from the SCHED_BARRIER that were added due to the
2591 // instruction having side effects.
2592 resetEdges(SchedBarrier, DAG);
2593 LLVM_DEBUG(dbgs() << "Building SchedGroup for SchedBarrier with Mask: "
2594 << MI.getOperand(0).getImm() << "\n");
2595 auto InvertedMask =
2596 invertSchedBarrierMask((SchedGroupMask)MI.getOperand(0).getImm());
2597 SchedGroup SG(InvertedMask, std::nullopt, DAG, TII);
2598 SG.initSchedGroup();
2599
2600 // Preserve original instruction ordering relative to the SCHED_BARRIER.
2601 SG.link(
2602 SchedBarrier,
2603 (function_ref<bool(const SUnit *A, const SUnit *B)>)[](
2604 const SUnit *A, const SUnit *B) { return A->NodeNum > B->NodeNum; });
2605}
2606
2607SchedGroupMask
2608IGroupLPDAGMutation::invertSchedBarrierMask(SchedGroupMask Mask) const {
2609 // Invert mask and erase bits for types of instructions that are implied to be
2610 // allowed past the SCHED_BARRIER.
2611 SchedGroupMask InvertedMask = ~Mask;
2612
2613 // ALU implies VALU, SALU, MFMA, TRANS.
2614 if ((InvertedMask & SchedGroupMask::ALU) == SchedGroupMask::NONE)
2615 InvertedMask &= ~SchedGroupMask::VALU & ~SchedGroupMask::SALU &
2616 ~SchedGroupMask::MFMA & ~SchedGroupMask::TRANS;
2617 // VALU, SALU, MFMA, TRANS implies ALU.
2618 else if ((InvertedMask & SchedGroupMask::VALU) == SchedGroupMask::NONE ||
2619 (InvertedMask & SchedGroupMask::SALU) == SchedGroupMask::NONE ||
2620 (InvertedMask & SchedGroupMask::MFMA) == SchedGroupMask::NONE ||
2621 (InvertedMask & SchedGroupMask::TRANS) == SchedGroupMask::NONE)
2622 InvertedMask &= ~SchedGroupMask::ALU;
2623
2624 // VMEM implies VMEM_READ, VMEM_WRITE.
2625 if ((InvertedMask & SchedGroupMask::VMEM) == SchedGroupMask::NONE)
2626 InvertedMask &= ~SchedGroupMask::VMEM_READ & ~SchedGroupMask::VMEM_WRITE;
2627 // VMEM_READ, VMEM_WRITE implies VMEM.
2628 else if ((InvertedMask & SchedGroupMask::VMEM_READ) == SchedGroupMask::NONE ||
2629 (InvertedMask & SchedGroupMask::VMEM_WRITE) == SchedGroupMask::NONE)
2630 InvertedMask &= ~SchedGroupMask::VMEM;
2631
2632 // DS implies DS_READ, DS_WRITE.
2633 if ((InvertedMask & SchedGroupMask::DS) == SchedGroupMask::NONE)
2634 InvertedMask &= ~SchedGroupMask::DS_READ & ~SchedGroupMask::DS_WRITE;
2635 // DS_READ, DS_WRITE implies DS.
2636 else if ((InvertedMask & SchedGroupMask::DS_READ) == SchedGroupMask::NONE ||
2637 (InvertedMask & SchedGroupMask::DS_WRITE) == SchedGroupMask::NONE)
2638 InvertedMask &= ~SchedGroupMask::DS;
2639
2640 LLVM_DEBUG(dbgs() << "After Inverting, SchedGroup Mask: " << (int)InvertedMask
2641 << "\n");
2642
2643 return InvertedMask;
2644}
2645
2646void IGroupLPDAGMutation::initSchedGroupBarrierPipelineStage(
2647 std::vector<SUnit>::reverse_iterator RIter) {
2648 // Remove all existing edges from the SCHED_GROUP_BARRIER that were added due
2649 // to the instruction having side effects.
2650 resetEdges(*RIter, DAG);
2651 MachineInstr &SGB = *RIter->getInstr();
2652 assert(SGB.getOpcode() == AMDGPU::SCHED_GROUP_BARRIER);
2653 int32_t SGMask = SGB.getOperand(0).getImm();
2654 int32_t Size = SGB.getOperand(1).getImm();
2655 int32_t SyncID = SGB.getOperand(2).getImm();
2656
2657 auto &SG = SyncedSchedGroups[SyncID].emplace_back((SchedGroupMask)SGMask,
2658 Size, SyncID, DAG, TII);
2659
2660 SG.initSchedGroup(RIter, SyncedInstrs[SG.getSyncID()]);
2661}
2662
2663bool IGroupLPDAGMutation::initIGLPOpt(SUnit &SU) {
2664 IGLPStrategyID StrategyID =
2665 (IGLPStrategyID)SU.getInstr()->getOperand(0).getImm();
2666 auto S = createIGLPStrategy(StrategyID, DAG, TII);
2667 if (!S->shouldApplyStrategy(DAG, Phase))
2668 return false;
2669
2670 IsBottomUp = S->IsBottomUp;
2671 return S->applyIGLPStrategy(SyncedInstrs, SyncedSchedGroups, Phase);
2672}
2673
2674} // namespace
2675
2676namespace llvm {
2677
2678/// \p Phase specifes whether or not this is a reentry into the
2679/// IGroupLPDAGMutation. Since there may be multiple scheduling passes on the
2680/// same scheduling region (e.g. pre and post-RA scheduling / multiple
2681/// scheduling "phases"), we can reenter this mutation framework more than once
2682/// for a given region.
2683std::unique_ptr<ScheduleDAGMutation>
2685 return std::make_unique<IGroupLPDAGMutation>(Phase);
2686}
2687
2688} // end namespace llvm
unsigned const MachineRegisterInfo * MRI
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
Provides AMDGPU specific target descriptions.
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock & MBB
#define LLVM_MARK_AS_BITMASK_ENUM(LargestValue)
LLVM_MARK_AS_BITMASK_ENUM lets you opt in an individual enum type so you can perform bitwise operatio...
Definition: BitmaskEnum.h:42
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
uint64_t Size
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
#define P(N)
uint32_t Number
Definition: Profile.cpp:47
Interface definition for SIInstrInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
This class represents an Operation in the Expression.
unsigned size() const
Definition: DenseMap.h:99
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:146
Instructions::iterator instr_iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:569
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:579
int64_t getImm() const
Scheduling dependency.
Definition: ScheduleDAG.h:49
SUnit * getSUnit() const
Definition: ScheduleDAG.h:498
@ Data
Regular data dependence (aka true-dependence).
Definition: ScheduleDAG.h:53
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition: ScheduleDAG.h:72
Scheduling unit. This is a node in the scheduling DAG.
Definition: ScheduleDAG.h:242
unsigned NodeNum
Entry # of node in the node vector.
Definition: ScheduleDAG.h:270
void removePred(const SDep &D)
Removes the specified edge as a pred of the current node if it exists.
SmallVector< SDep, 4 > Succs
All sunit successors.
Definition: ScheduleDAG.h:263
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
A ScheduleDAG for scheduling lists of MachineInstr.
const TargetSchedModel * getSchedModel() const
Gets the machine model for instruction scheduling.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
bool IsReachable(SUnit *SU, SUnit *TargetSU)
IsReachable - Checks if SU is reachable from TargetSU.
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
void dump() const override
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
Mutate the DAG as a postpass after normal DAG building.
virtual void apply(ScheduleDAGInstrs *DAG)=0
std::vector< SUnit > SUnits
The scheduling units.
Definition: ScheduleDAG.h:579
MachineFunction & MF
Machine function.
Definition: ScheduleDAG.h:577
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Provide an instruction scheduling machine model to CodeGen passes.
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1680
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
@ NONE
Definition: Attributor.h:6418
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
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:1736
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:187
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1886
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860