LLVM 24.0.0git
GCNSchedStrategy.cpp
Go to the documentation of this file.
1//===-- GCNSchedStrategy.cpp - GCN Scheduler Strategy ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This contains a MachineSchedStrategy implementation for maximizing wave
11/// occupancy on GCN hardware.
12///
13/// This pass will apply multiple scheduling stages to the same function.
14/// Regions are first recorded in GCNScheduleDAGMILive::schedule. The actual
15/// entry point for the scheduling of those regions is
16/// GCNScheduleDAGMILive::runSchedStages.
17
18/// Generally, the reason for having multiple scheduling stages is to account
19/// for the kernel-wide effect of register usage on occupancy. Usually, only a
20/// few scheduling regions will have register pressure high enough to limit
21/// occupancy for the kernel, so constraints can be relaxed to improve ILP in
22/// other regions.
23///
24//===----------------------------------------------------------------------===//
25
26#include "GCNSchedStrategy.h"
27#include "AMDGPUIGroupLP.h"
28#include "GCNHazardRecognizer.h"
29#include "GCNRegPressure.h"
30#include "GCNRematStrategy.h"
33#include "llvm/ADT/BitVector.h"
34#include "llvm/ADT/STLExtras.h"
40#include "llvm/MC/MCSchedule.h"
43
44#define DEBUG_TYPE "machine-scheduler"
45
46using namespace llvm;
47
49 unsigned &Value) {
50 if (Arg.getAsInteger(0, Value))
51 return O.error("'" + Arg + "' value invalid for uint argument!");
52
53 if (Value > 100)
54 return O.error("'" + Arg + "' value must be in the range [0, 100]!");
55
56 return false;
57}
58
60 "amdgpu-vgpr-threshold-percent", cl::Hidden,
61 cl::desc("Percent of VGPR limits that we should use as RP threshold "
62 "during scheduling. We have two limits relevant to scheduling: "
63 "Critical (avoid decreasing occupancy), Excess (avoid spilling). "
64 "This flag scales both limits back by an equal percent: (0 = use "
65 " default calculation, 1-100 = use percentage), default: 0"),
66 cl::init(0));
67
68const unsigned ScheduleMetrics::ScaleFactor = 100;
69
79
82
83 MF = &DAG->MF;
84
85 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
86
88 Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::SGPR_32RegClass);
90 Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::VGPR_32RegClass);
92 Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::AGPR_32RegClass);
93
96 UnifiedVGPRExcessLimit = ST.hasGFX90AInsts() ? ST.getMaxNumVGPRs(*MF) : 0;
97
99 // Set the initial TargetOccupnacy to the maximum occupancy that we can
100 // achieve for this function. This effectively sets a lower bound on the
101 // 'Critical' register limits in the scheduler.
102 // Allow for lower occupancy targets if kernel is wave limited or memory
103 // bound, and using the relaxed occupancy feature.
104 TargetOccupancy = CLOpts.schedule_relaxed_occupancy
106 : MFI.getOccupancy();
108 std::min(ST.getMaxNumSGPRs(TargetOccupancy, true), SGPRExcessLimit);
109
110 if (!KnownExcessRP) {
111 // Preserve the combined occupancy budget before clamping to one bank.
113 ST.getMaxNumVGPRs(TargetOccupancy, MFI.getDynamicVGPRBlockSize());
115 } else {
116 // This is similar to ST.getMaxNumVGPRs(TargetOccupancy) result except
117 // returns a reasonably small number for targets with lots of VGPRs, such
118 // as GFX10 and GFX11.
119 LLVM_DEBUG(dbgs() << "Region is known to spill, use alternative "
120 "VGPRCriticalLimit calculation method.\n");
121 unsigned DynamicVGPRBlockSize = MFI.getDynamicVGPRBlockSize();
122 unsigned Granule =
123 AMDGPU::IsaInfo::getVGPRAllocGranule(ST, DynamicVGPRBlockSize);
124 unsigned Addressable =
125 AMDGPU::IsaInfo::getAddressableNumVGPRs(ST, DynamicVGPRBlockSize);
126 unsigned VGPRBudget = alignDown(Addressable / TargetOccupancy, Granule);
127 VGPRBudget = std::max(VGPRBudget, Granule);
128 UnifiedVGPRCriticalLimit = VGPRBudget;
129 VGPRCriticalLimit = std::min(VGPRBudget, VGPRExcessLimit);
130 }
131
132 // Reuse VGPR critical limit
134
135 // Apply VGPR excess threshold percentage if specified.
136 if (VGPRThresholdPercent > 0) {
137 [[maybe_unused]] unsigned OriginalVGPRExcessLimit = VGPRExcessLimit;
138 [[maybe_unused]] unsigned OriginalVGPRCriticalLimit = VGPRCriticalLimit;
143 LLVM_DEBUG(dbgs() << "Applied VGPR excess threshold "
144 << VGPRThresholdPercent << "%, VGPRExcessLimit: "
145 << OriginalVGPRExcessLimit << " -> " << VGPRExcessLimit
146 << ". VGPRCriticalLimit: " << OriginalVGPRCriticalLimit
147 << " -> " << VGPRCriticalLimit << '\n');
148 } else {
154 }
155
156 // Subtract error margin and bias from register limits and avoid overflow.
159
162
163 LLVM_DEBUG(dbgs() << "VGPRCriticalLimit = " << VGPRCriticalLimit
164 << ", UnifiedVGPRCriticalLimit = "
166 << ", VGPRExcessLimit = " << VGPRExcessLimit
167 << ", AGPRCriticalLimit = " << AGPRCriticalLimit
168 << ", AGPRExcessLimit = " << AGPRExcessLimit
169 << ", SGPRCriticalLimit = " << SGPRCriticalLimit
170 << ", SGPRExcessLimit = " << SGPRExcessLimit << "\n\n");
171}
172
173/// Checks whether \p SU can use the cached DAG pressure diffs to compute the
174/// current register pressure.
175///
176/// This works for the common case, but it has a few exceptions that have been
177/// observed through trial and error:
178/// - Explicit physical register operands
179/// - Subregister definitions
180///
181/// In both of those cases, PressureDiff doesn't represent the actual pressure,
182/// and querying LiveIntervals through the RegPressureTracker is needed to get
183/// an accurate value.
184///
185/// We should eventually only use PressureDiff for maximum performance, but this
186/// already allows 80% of SUs to take the fast path without changing scheduling
187/// at all. Further changes would either change scheduling, or require a lot
188/// more logic to recover an accurate pressure estimate from the PressureDiffs.
189static bool canUsePressureDiffs(const SUnit &SU) {
190 if (!SU.isInstr())
191 return false;
192
193 // Cannot use pressure diffs for subregister defs or with physregs, it's
194 // imprecise in both cases. For a bundle, check the instructions inside it:
195 // the BUNDLE header only has implicit operands.
196 for (const auto &Op : const_mi_bundle_ops(*SU.getInstr())) {
197 if (!Op.isReg() || Op.isImplicit())
198 continue;
199 if (Op.getReg().isPhysical() ||
200 (Op.isDef() && Op.getSubReg() != AMDGPU::NoSubRegister))
201 return false;
202 }
203 return true;
204}
205
206std::pair<unsigned, unsigned>
208 if (!CLOpts.avgpr_banking)
209 return {RP.getArchVGPRNum(), RP.getAGPRNum()};
210 return RP.getBankedVGPRNum(ArchVGPRBankLimit, AGPRBankLimit);
211}
212
213/// Fills \p Pressure and \p MaxPressure, indexed by pressure set, with the
214/// generic RegPressureTracker's pressure after scheduling \p SU.
215static void getRegisterPressures(bool AtTop,
216 const RegPressureTracker &RPTracker, SUnit *SU,
217 std::vector<unsigned> &Pressure,
218 std::vector<unsigned> &MaxPressure) {
219 // getDownwardPressure() and getUpwardPressure() make temporary changes to
220 // the tracker, so we need to pass those function a non-const copy.
221 RegPressureTracker &TempTracker = const_cast<RegPressureTracker &>(RPTracker);
222 AtTop ? TempTracker.getDownwardPressure(SU->getInstr(), Pressure, MaxPressure)
223 : TempTracker.getUpwardPressure(SU->getInstr(), Pressure, MaxPressure);
224}
225
228 const SIRegisterInfo *SRI) const {
229 MachineInstr *MI = SU->getInstr();
230 if (AtTop)
231 return DownwardTracker.bumpDownwardPressure(MI, SRI);
232 GCNUpwardRPTracker TempUpwardTracker(UpwardTracker);
233 TempUpwardTracker.recede(*MI);
234 return TempUpwardTracker.getPressure();
235}
236
238 bool AtTop,
239 const RegPressureTracker &RPTracker,
240 const SIRegisterInfo *SRI,
241 unsigned SGPRPressure,
242 unsigned VGPRPressure,
243 unsigned AGPRPressure, bool IsBottomUp) {
244 Cand.SU = SU;
245 Cand.AtTop = AtTop;
246
247 if (!DAG->isTrackingPressure())
248 return;
249
250 unsigned NewSGPRPressure, NewVGPRPressure, NewAGPRPressure;
251 // Only computed when the GCN trackers are in use.
252 unsigned CandUnifiedVGPRPressure = 0;
253 if (useGCNTrackers()) {
254 GCNRegPressure NewPressure = getGCNTrackerPressure(AtTop, SU, SRI);
255 NewSGPRPressure = NewPressure.getSGPRNum();
256 std::tie(NewVGPRPressure, NewAGPRPressure) = getBankedPressure(NewPressure);
257 CandUnifiedVGPRPressure = GCNRegPressure::getBankedUnifiedVGPRNum(
258 NewVGPRPressure, NewAGPRPressure);
259 } else {
260 Pressure.clear();
261 MaxPressure.clear();
262
263 // We try to use the cached PressureDiffs in the ScheduleDAG whenever
264 // possible over querying the RegPressureTracker.
265 //
266 // RegPressureTracker will make a lot of LIS queries which are very
267 // expensive, it is considered a slow function in this context.
268 //
269 // PressureDiffs are precomputed and cached, and getPressureDiff is just a
270 // trivial lookup into an array. It is pretty much free.
271 //
272 // In EXPENSIVE_CHECKS, we always query RPTracker to verify the results of
273 // PressureDiffs.
274 if (AtTop || !canUsePressureDiffs(*SU)) {
275 getRegisterPressures(AtTop, RPTracker, SU, Pressure, MaxPressure);
276 } else {
277 // Reserve 4 slots.
278 Pressure.resize(4, 0);
279 Pressure[AMDGPU::RegisterPressureSets::SReg_32] = SGPRPressure;
280 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] = VGPRPressure;
281 Pressure[AMDGPU::RegisterPressureSets::AGPR_32] = AGPRPressure;
282
283 for (const auto &Diff : DAG->getPressureDiff(SU)) {
284 if (!Diff.isValid())
285 continue;
286 // PressureDiffs is always bottom-up so if we're working top-down we
287 // need to invert its sign.
288 Pressure[Diff.getPSet()] +=
289 (IsBottomUp ? Diff.getUnitInc() : -Diff.getUnitInc());
290 }
291
292#ifdef EXPENSIVE_CHECKS
293 std::vector<unsigned> CheckPressure, CheckMaxPressure;
294 getRegisterPressures(AtTop, RPTracker, SU, CheckPressure,
295 CheckMaxPressure);
296 if (Pressure[AMDGPU::RegisterPressureSets::SReg_32] !=
297 CheckPressure[AMDGPU::RegisterPressureSets::SReg_32] ||
298 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] !=
299 CheckPressure[AMDGPU::RegisterPressureSets::VGPR_32] ||
300 Pressure[AMDGPU::RegisterPressureSets::AGPR_32] !=
301 CheckPressure[AMDGPU::RegisterPressureSets::AGPR_32]) {
302 errs() << "Register Pressure is inaccurate when calculated through "
303 "PressureDiff\n"
304 << "SGPR got " << Pressure[AMDGPU::RegisterPressureSets::SReg_32]
305 << ", expected "
306 << CheckPressure[AMDGPU::RegisterPressureSets::SReg_32] << "\n"
307 << "VGPR got " << Pressure[AMDGPU::RegisterPressureSets::VGPR_32]
308 << ", expected "
309 << CheckPressure[AMDGPU::RegisterPressureSets::VGPR_32] << "\n"
310 << "AGPR got " << Pressure[AMDGPU::RegisterPressureSets::AGPR_32]
311 << ", expected "
312 << CheckPressure[AMDGPU::RegisterPressureSets::AGPR_32] << "\n";
313 report_fatal_error("inaccurate register pressure calculation");
314 }
315#endif
316 }
317
318 NewSGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
319 NewVGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
320 NewAGPRPressure = Pressure[AMDGPU::RegisterPressureSets::AGPR_32];
321 }
322
323 // If two instructions increase the pressure of different register sets
324 // by the same amount, the generic scheduler will prefer to schedule the
325 // instruction that increases the set with the least amount of registers,
326 // which in our case would be SGPRs. This is rarely what we want, so
327 // when we report excess/critical register pressure, we do it either
328 // only for VGPRs, AGPRs or SGPRs. Priority: VGPR > AGPR > SGPR.
329
330 // FIXME: Better heuristics to determine whether to prefer SGPRs or VGPRs.
331 const unsigned MaxVGPRPressureInc = 16;
332 bool ShouldTrackVGPRs = VGPRPressure + MaxVGPRPressureInc >= VGPRExcessLimit;
333 bool ShouldTrackAGPRs = AGPRExcessLimit > 0 && !ShouldTrackVGPRs &&
334 AGPRPressure + MaxVGPRPressureInc >= AGPRExcessLimit;
335 bool ShouldTrackSGPRs =
336 !ShouldTrackVGPRs && !ShouldTrackAGPRs && SGPRPressure >= SGPRExcessLimit;
337 // FIXME: We have to enter REG-EXCESS before we reach the actual threshold
338 // to increase the likelihood we don't go over the limits. We should improve
339 // the analysis to look through dependencies to find the path with the least
340 // register pressure.
341 // We only need to update the RPDelta for instructions that increase register
342 // pressure. Instructions that decrease or keep reg pressure the same will be
343 // marked as RegExcess in tryCandidate() when they are compared with
344 // instructions that increase the register pressure.
345 if (ShouldTrackVGPRs && NewVGPRPressure >= VGPRExcessLimit) {
346 HasHighPressure = true;
347 Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
348 Cand.RPDelta.Excess.setUnitInc(NewVGPRPressure - VGPRExcessLimit);
349 }
350
351 if (ShouldTrackAGPRs && NewAGPRPressure >= AGPRExcessLimit) {
352 HasHighPressure = true;
353 Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::AGPR_32);
354 Cand.RPDelta.Excess.setUnitInc(NewAGPRPressure - AGPRExcessLimit);
355 }
356
357 if (ShouldTrackSGPRs && NewSGPRPressure >= SGPRExcessLimit) {
358 HasHighPressure = true;
359 Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
360 Cand.RPDelta.Excess.setUnitInc(NewSGPRPressure - SGPRExcessLimit);
361 }
362
363 // Because of alignment padding, the combined file can overflow when both
364 // banks are within limits. This check catches overflow that the others above
365 // miss.
366 if (CLOpts.avgpr_banking && UnifiedVGPRExcessLimit &&
367 CandUnifiedVGPRPressure >= UnifiedVGPRExcessLimit) {
368 HasHighPressure = true;
369 int UnifiedExcess = CandUnifiedVGPRPressure - UnifiedVGPRExcessLimit;
370 PressureChange &Excess = Cand.RPDelta.Excess;
371 bool HasBankExcess =
372 Excess.isValid() &&
373 Excess.getPSet() != AMDGPU::RegisterPressureSets::SReg_32;
374 if (!HasBankExcess || UnifiedExcess > Excess.getUnitInc()) {
375 Excess = PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
376 Excess.setUnitInc(UnifiedExcess);
377 }
378 }
379
380 // Register pressure is considered 'CRITICAL' if it is approaching a value
381 // that would reduce the wave occupancy for the execution unit. When
382 // register pressure is 'CRITICAL', increasing SGPR, VGPR, and AGPR
383 // pressure all has the same cost, so we pick the most critical type.
384
385 // Unified targets allocate both vector banks from the same occupancy budget.
386 // Keep the bank pressures above for excess checks, and do not align VGPRs
387 // when there are no AGPRs, matching GCNRegPressure::getVGPRNum().
388 bool UnifiedVGPRFile = MF->getSubtarget<GCNSubtarget>().hasGFX90AInsts();
389 unsigned VectorCriticalLimit = VGPRCriticalLimit;
390 if (UnifiedVGPRFile) {
391 if (NewAGPRPressure)
392 NewVGPRPressure = GCNRegPressure::getUnifiedVGPRNum(NewVGPRPressure,
393 NewAGPRPressure, 0);
394 VectorCriticalLimit = UnifiedVGPRCriticalLimit;
395 }
396
397 int SGPRDelta = NewSGPRPressure - SGPRCriticalLimit;
398 int VGPRDelta = NewVGPRPressure - VectorCriticalLimit;
399 int AGPRDelta = !UnifiedVGPRFile && AGPRExcessLimit > 0
400 ? NewAGPRPressure - AGPRCriticalLimit
401 : std::numeric_limits<int>::min();
402
403 if (SGPRDelta >= 0 || VGPRDelta >= 0 || AGPRDelta >= 0) {
404 HasHighPressure = true;
405 // Pick the most critical type.
406 if (VGPRDelta >= SGPRDelta && VGPRDelta >= AGPRDelta) {
407 Cand.RPDelta.CriticalMax =
408 PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
409 Cand.RPDelta.CriticalMax.setUnitInc(VGPRDelta);
410 } else if (AGPRDelta >= SGPRDelta) {
411 Cand.RPDelta.CriticalMax =
412 PressureChange(AMDGPU::RegisterPressureSets::AGPR_32);
413 Cand.RPDelta.CriticalMax.setUnitInc(AGPRDelta);
414 } else {
415 Cand.RPDelta.CriticalMax =
416 PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
417 Cand.RPDelta.CriticalMax.setUnitInc(SGPRDelta);
418 }
419 }
420}
421
422static bool shouldCheckPending(unsigned PendingQueueLimit, SchedBoundary &Zone,
423 const TargetSchedModel *SchedModel) {
424 bool HasBufferedModel =
425 SchedModel->hasInstrSchedModel() && SchedModel->getMicroOpBufferSize();
426 unsigned Combined = Zone.Available.size() + Zone.Pending.size();
427 return Combined <= PendingQueueLimit && HasBufferedModel;
428}
429
430static SUnit *pickOnlyChoice(unsigned PendingQueueLimit, SchedBoundary &Zone,
431 const TargetSchedModel *SchedModel) {
432 // pickOnlyChoice() releases pending instructions and checks for new hazards.
433 SUnit *OnlyChoice = Zone.pickOnlyChoice();
434 if (!shouldCheckPending(PendingQueueLimit, Zone, SchedModel) ||
435 Zone.Pending.empty())
436 return OnlyChoice;
437
438 return nullptr;
439}
440
442 const SchedCandidate &Preferred) {
443 LLVM_DEBUG({
444 dbgs() << "Prefer:\t\t";
445 DAG->dumpNode(*Preferred.SU);
446
447 if (Current.SU) {
448 dbgs() << "Not:\t";
449 DAG->dumpNode(*Current.SU);
450 }
451
452 dbgs() << "Reason:\t\t";
453 traceCandidate(Preferred);
454 });
455}
456
457// This function is mostly cut and pasted from
458// GenericScheduler::pickNodeFromQueue()
460 const CandPolicy &ZonePolicy,
461 const RegPressureTracker &RPTracker,
462 SchedCandidate &Cand, bool &IsPending,
463 bool IsBottomUp) {
464 const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo *>(TRI);
466 unsigned SGPRPressure = 0;
467 unsigned VGPRPressure = 0;
468 unsigned AGPRPressure = 0;
469 IsPending = false;
470 if (DAG->isTrackingPressure()) {
471 if (!useGCNTrackers()) {
472 SGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
473 VGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
474 AGPRPressure = Pressure[AMDGPU::RegisterPressureSets::AGPR_32];
475 } else {
476 GCNRPTracker *T = IsBottomUp
477 ? static_cast<GCNRPTracker *>(&UpwardTracker)
478 : static_cast<GCNRPTracker *>(&DownwardTracker);
479 SGPRPressure = T->getPressure().getSGPRNum();
480 std::tie(VGPRPressure, AGPRPressure) =
481 getBankedPressure(T->getPressure());
482 }
483 }
484 LLVM_DEBUG(dbgs() << "Available Q:\n");
485 ReadyQueue &AQ = Zone.Available;
486 for (SUnit *SU : AQ) {
487
488 SchedCandidate TryCand(ZonePolicy);
489 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI, SGPRPressure,
490 VGPRPressure, AGPRPressure, IsBottomUp);
491 // Pass SchedBoundary only when comparing nodes from the same boundary.
492 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
493 tryCandidate(Cand, TryCand, ZoneArg);
494 if (TryCand.Reason != NoCand) {
495 // Initialize resource delta if needed in case future heuristics query it.
496 if (TryCand.ResDelta == SchedResourceDelta())
497 TryCand.initResourceDelta(Zone.DAG, SchedModel);
498 LLVM_DEBUG(printCandidateDecision(Cand, TryCand));
499 Cand.setBest(TryCand);
500 } else {
501 printCandidateDecision(TryCand, Cand);
502 }
503 }
504
505 if (!shouldCheckPending(CLOpts.scheduler_pending_queue_limit, Zone,
506 SchedModel))
507 return;
508
509 LLVM_DEBUG(dbgs() << "Pending Q:\n");
510 ReadyQueue &PQ = Zone.Pending;
511 for (SUnit *SU : PQ) {
512
513 SchedCandidate TryCand(ZonePolicy);
514 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI, SGPRPressure,
515 VGPRPressure, AGPRPressure, IsBottomUp);
516 // Pass SchedBoundary only when comparing nodes from the same boundary.
517 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
518 tryPendingCandidate(Cand, TryCand, ZoneArg);
519 if (TryCand.Reason != NoCand) {
520 // Initialize resource delta if needed in case future heuristics query it.
521 if (TryCand.ResDelta == SchedResourceDelta())
522 TryCand.initResourceDelta(Zone.DAG, SchedModel);
523 LLVM_DEBUG(printCandidateDecision(Cand, TryCand));
524 IsPending = true;
525 Cand.setBest(TryCand);
526 } else {
527 printCandidateDecision(TryCand, Cand);
528 }
529 }
530}
531
532// This function is mostly cut and pasted from
533// GenericScheduler::pickNodeBidirectional()
535 bool &PickedPending) {
536 // Schedule as far as possible in the direction of no choice. This is most
537 // efficient, but also provides the best heuristics for CriticalPSets.
538 if (SUnit *SU = pickOnlyChoice(CLOpts.scheduler_pending_queue_limit, Bot,
539 SchedModel)) {
540 IsTopNode = false;
541 return SU;
542 }
543 if (SUnit *SU = pickOnlyChoice(CLOpts.scheduler_pending_queue_limit, Top,
544 SchedModel)) {
545 IsTopNode = true;
546 return SU;
547 }
548 // Set the bottom-up policy based on the state of the current bottom zone
549 // and the instructions outside the zone, including the top zone.
550 CandPolicy BotPolicy;
551 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
552 // Set the top-down policy based on the state of the current top zone and
553 // the instructions outside the zone, including the bottom zone.
554 CandPolicy TopPolicy;
555 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
556
557 bool BotPending = false;
558 // See if BotCand is still valid (because we previously scheduled from Top).
559 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
560 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
561 BotCand.Policy != BotPolicy) {
562 BotCand.reset(CandPolicy());
563 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand,
564 BotPending,
565 /*IsBottomUp=*/true);
566 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
567 } else {
569#ifndef NDEBUG
570 if (shouldVerifyScheduling(DAG->MF)) {
571 SchedCandidate TCand;
572 TCand.reset(CandPolicy());
573 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand,
574 BotPending,
575 /*IsBottomUp=*/true);
576 assert(TCand.SU == BotCand.SU &&
577 "Last pick result should correspond to re-picking right now");
578 }
579#endif
580 }
581
582 bool TopPending = false;
583 // Check if the top Q has a better candidate.
584 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
585 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
586 TopCand.Policy != TopPolicy) {
587 TopCand.reset(CandPolicy());
588 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand,
589 TopPending,
590 /*IsBottomUp=*/false);
591 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
592 } else {
594#ifndef NDEBUG
595 if (shouldVerifyScheduling(DAG->MF)) {
596 SchedCandidate TCand;
597 TCand.reset(CandPolicy());
598 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand,
599 TopPending,
600 /*IsBottomUp=*/false);
601 assert(TCand.SU == TopCand.SU &&
602 "Last pick result should correspond to re-picking right now");
603 }
604#endif
605 }
606
607 // Pick best from BotCand and TopCand.
608 LLVM_DEBUG(dbgs() << "Top Cand: "; traceCandidate(TopCand);
609 dbgs() << "Bot Cand: "; traceCandidate(BotCand););
610 SchedCandidate Cand = BotPending ? TopCand : BotCand;
611 SchedCandidate TryCand = BotPending ? BotCand : TopCand;
612 PickedPending = BotPending && TopPending;
613
614 TryCand.Reason = NoCand;
615 if (BotPending || TopPending) {
616 PickedPending |= tryPendingCandidate(Cand, TopCand, nullptr);
617 } else {
618 tryCandidate(Cand, TryCand, nullptr);
619 }
620
621 if (TryCand.Reason != NoCand) {
622 Cand.setBest(TryCand);
623 }
624
625 LLVM_DEBUG(dbgs() << "Picking: "; traceCandidate(Cand););
626
627 IsTopNode = Cand.AtTop;
628 return Cand.SU;
629}
630
631// This function is mostly cut and pasted from
632// GenericScheduler::pickNode()
634 if (DAG->top() == DAG->bottom()) {
635 assert(Top.Available.empty() && Top.Pending.empty() &&
636 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
637 return nullptr;
638 }
639 bool PickedPending;
640 SUnit *SU;
641 do {
642 PickedPending = false;
643 if (RegionPolicy.OnlyTopDown) {
644 SU =
645 pickOnlyChoice(CLOpts.scheduler_pending_queue_limit, Top, SchedModel);
646 if (!SU) {
647 CandPolicy NoPolicy;
648 TopCand.reset(NoPolicy);
649 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand,
650 PickedPending,
651 /*IsBottomUp=*/false);
652 assert(TopCand.Reason != NoCand && "failed to find a candidate");
653 SU = TopCand.SU;
654 }
655 IsTopNode = true;
656 } else if (RegionPolicy.OnlyBottomUp) {
657 SU =
658 pickOnlyChoice(CLOpts.scheduler_pending_queue_limit, Bot, SchedModel);
659 if (!SU) {
660 CandPolicy NoPolicy;
661 BotCand.reset(NoPolicy);
662 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand,
663 PickedPending,
664 /*IsBottomUp=*/true);
665 assert(BotCand.Reason != NoCand && "failed to find a candidate");
666 SU = BotCand.SU;
667 }
668 IsTopNode = false;
669 } else {
670 SU = pickNodeBidirectional(IsTopNode, PickedPending);
671 }
672 } while (SU->isScheduled);
673
674 if (PickedPending) {
675 unsigned ReadyCycle = IsTopNode ? SU->TopReadyCycle : SU->BotReadyCycle;
676 SchedBoundary &Zone = IsTopNode ? Top : Bot;
677 unsigned CurrentCycle = Zone.getCurrCycle();
678 if (ReadyCycle > CurrentCycle)
679 Zone.bumpCycle(ReadyCycle);
680
681 // FIXME: checkHazard() doesn't give information about which cycle the
682 // hazard will resolve so just keep bumping the cycle by 1. This could be
683 // made more efficient if checkHazard() returned more details.
684 while (Zone.checkHazard(SU))
685 Zone.bumpCycle(Zone.getCurrCycle() + 1);
686
687 Zone.releasePending();
688 }
689
690 if (SU->isTopReady())
691 Top.removeReady(SU);
692 if (SU->isBottomReady())
693 Bot.removeReady(SU);
694
695 LLVM_DEBUG(dbgs() << "Scheduling " << *SU << " " << *SU->getInstr());
696 return SU;
697}
698
699void GCNSchedStrategy::schedNode(SUnit *SU, bool IsTopNode) {
700 if (useGCNTrackers()) {
701 MachineInstr *MI = SU->getInstr();
702 IsTopNode ? DownwardTracker.advance(*MI) : UpwardTracker.recede(*MI);
703 }
704
705 return GenericScheduler::schedNode(SU, IsTopNode);
706}
707
712
715 if (!CurrentStage)
716 CurrentStage = SchedStages.begin();
717 else
718 CurrentStage++;
719
720 return CurrentStage != SchedStages.end();
721}
722
725 return std::next(CurrentStage) != SchedStages.end();
726}
727
729 SchedCandidate &TryCand,
730 SchedBoundary *Zone) const {
731 // Initialize the candidate if needed.
732 if (!Cand.isValid()) {
733 TryCand.Reason = NodeOrder;
734 return true;
735 }
736
737 // Bias PhysReg Defs and copies to their uses and defined respectively.
738 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
739 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
740 return TryCand.Reason != NoCand;
741
742 // Avoid exceeding the target's limit.
743 if (DAG->isTrackingPressure() &&
744 tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
745 RegExcess, TRI, DAG->MF))
746 return TryCand.Reason != NoCand;
747
748 // Avoid increasing the max critical pressure in the scheduled region.
749 if (DAG->isTrackingPressure() &&
751 TryCand, Cand, RegCritical, TRI, DAG->MF))
752 return TryCand.Reason != NoCand;
753
754 bool SameBoundary = Zone != nullptr;
755 if (SameBoundary) {
758 TryCand, Cand, ResourceReduce))
759 return TryCand.Reason != NoCand;
761 Cand.ResDelta.DemandedResources, TryCand, Cand,
763 return TryCand.Reason != NoCand;
764 }
765
766 return false;
767}
768
781
786
788 SchedCandidate &TryCand,
789 SchedBoundary *Zone) const {
790 // Initialize the candidate if needed.
791 if (!Cand.isValid()) {
792 TryCand.Reason = NodeOrder;
793 return true;
794 }
795
796 // Avoid spilling by exceeding the register limit.
797 if (DAG->isTrackingPressure() &&
798 tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
799 RegExcess, TRI, DAG->MF))
800 return TryCand.Reason != NoCand;
801
802 // Bias PhysReg Defs and copies to their uses and defined respectively.
803 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
804 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
805 return TryCand.Reason != NoCand;
806
807 bool SameBoundary = Zone != nullptr;
808 if (SameBoundary) {
809 // Prioritize instructions that read unbuffered resources by stall cycles.
810 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
811 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
812 return TryCand.Reason != NoCand;
813
814 // Avoid critical resource consumption and balance the schedule.
817 TryCand, Cand, ResourceReduce))
818 return TryCand.Reason != NoCand;
820 Cand.ResDelta.DemandedResources, TryCand, Cand,
822 return TryCand.Reason != NoCand;
823
824 // Unconditionally try to reduce latency.
825 if (tryLatency(TryCand, Cand, *Zone))
826 return TryCand.Reason != NoCand;
827
828 // Weak edges are for clustering and other constraints.
829 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
830 getWeakLeft(Cand.SU, Cand.AtTop), TryCand, Cand, Weak))
831 return TryCand.Reason != NoCand;
832 }
833
834 // Keep clustered nodes together to encourage downstream peephole
835 // optimizations which may reduce resource requirements.
836 //
837 // This is a best effort to set things up for a post-RA pass. Optimizations
838 // like generating loads of multiple registers should ideally be done within
839 // the scheduler pass by combining the loads during DAG postprocessing.
840 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
841 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
842 bool CandIsClusterSucc =
843 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
844 bool TryCandIsClusterSucc =
845 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
846 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
847 Cluster))
848 return TryCand.Reason != NoCand;
849
850 // Avoid increasing the max critical pressure in the scheduled region.
851 if (DAG->isTrackingPressure() &&
853 TryCand, Cand, RegCritical, TRI, DAG->MF))
854 return TryCand.Reason != NoCand;
855
856 // Avoid increasing the max pressure of the entire region.
857 if (DAG->isTrackingPressure() &&
858 tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax, TryCand,
859 Cand, RegMax, TRI, DAG->MF))
860 return TryCand.Reason != NoCand;
861
862 if (SameBoundary) {
863 // Fall through to original instruction order.
864 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) ||
865 (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
866 TryCand.Reason = NodeOrder;
867 return true;
868 }
869 }
870 return false;
871}
872
878
879/// GCNMaxMemoryClauseSchedStrategy tries best to clause memory instructions as
880/// much as possible. This is achieved by:
881// 1. Prioritize clustered operations before stall latency heuristic.
882// 2. Prioritize long-latency-load before stall latency heuristic.
883///
884/// \param Cand provides the policy and current best candidate.
885/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
886/// \param Zone describes the scheduled zone that we are extending, or nullptr
887/// if Cand is from a different zone than TryCand.
888/// \return \c true if TryCand is better than Cand (Reason is NOT NoCand)
890 SchedCandidate &TryCand,
891 SchedBoundary *Zone) const {
892 // Initialize the candidate if needed.
893 if (!Cand.isValid()) {
894 TryCand.Reason = NodeOrder;
895 return true;
896 }
897
898 // Bias PhysReg Defs and copies to their uses and defined respectively.
899 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
900 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
901 return TryCand.Reason != NoCand;
902
903 if (DAG->isTrackingPressure()) {
904 // Avoid exceeding the target's limit.
905 if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
906 RegExcess, TRI, DAG->MF))
907 return TryCand.Reason != NoCand;
908
909 // Avoid increasing the max critical pressure in the scheduled region.
911 TryCand, Cand, RegCritical, TRI, DAG->MF))
912 return TryCand.Reason != NoCand;
913 }
914
915 // MaxMemoryClause-specific: We prioritize clustered instructions as we would
916 // get more benefit from clausing these memory instructions.
917 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
918 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
919 bool CandIsClusterSucc =
920 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
921 bool TryCandIsClusterSucc =
922 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
923 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
924 Cluster))
925 return TryCand.Reason != NoCand;
926
927 // We only compare a subset of features when comparing nodes between
928 // Top and Bottom boundary. Some properties are simply incomparable, in many
929 // other instances we should only override the other boundary if something
930 // is a clear good pick on one boundary. Skip heuristics that are more
931 // "tie-breaking" in nature.
932 bool SameBoundary = Zone != nullptr;
933 if (SameBoundary) {
934 // For loops that are acyclic path limited, aggressively schedule for
935 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
936 // heuristics to take precedence.
937 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
938 tryLatency(TryCand, Cand, *Zone))
939 return TryCand.Reason != NoCand;
940
941 // MaxMemoryClause-specific: Prioritize long latency memory load
942 // instructions in top-bottom order to hide more latency. The mayLoad check
943 // is used to exclude store-like instructions, which we do not want to
944 // scheduler them too early.
945 bool TryMayLoad =
946 TryCand.SU->isInstr() && TryCand.SU->getInstr()->mayLoad();
947 bool CandMayLoad = Cand.SU->isInstr() && Cand.SU->getInstr()->mayLoad();
948
949 if (TryMayLoad || CandMayLoad) {
950 bool TryLongLatency =
951 TryCand.SU->Latency > 10 * Cand.SU->Latency && TryMayLoad;
952 bool CandLongLatency =
953 10 * TryCand.SU->Latency < Cand.SU->Latency && CandMayLoad;
954
955 if (tryGreater(Zone->isTop() ? TryLongLatency : CandLongLatency,
956 Zone->isTop() ? CandLongLatency : TryLongLatency, TryCand,
957 Cand, Stall))
958 return TryCand.Reason != NoCand;
959 }
960 // Prioritize instructions that read unbuffered resources by stall cycles.
961 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
962 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
963 return TryCand.Reason != NoCand;
964 }
965
966 if (SameBoundary) {
967 // Weak edges are for clustering and other constraints.
968 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
969 getWeakLeft(Cand.SU, Cand.AtTop), TryCand, Cand, Weak))
970 return TryCand.Reason != NoCand;
971 }
972
973 // Avoid increasing the max pressure of the entire region.
974 if (DAG->isTrackingPressure() &&
975 tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax, TryCand,
976 Cand, RegMax, TRI, DAG->MF))
977 return TryCand.Reason != NoCand;
978
979 if (SameBoundary) {
980 // Avoid critical resource consumption and balance the schedule.
983 TryCand, Cand, ResourceReduce))
984 return TryCand.Reason != NoCand;
986 Cand.ResDelta.DemandedResources, TryCand, Cand,
988 return TryCand.Reason != NoCand;
989
990 // Avoid serializing long latency dependence chains.
991 // For acyclic path limited loops, latency was already checked above.
992 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
993 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
994 return TryCand.Reason != NoCand;
995
996 // Fall through to original instruction order.
997 if (Zone->isTop() == (TryCand.SU->NodeNum < Cand.SU->NodeNum)) {
998 assert(TryCand.SU->NodeNum != Cand.SU->NodeNum);
999 TryCand.Reason = NodeOrder;
1000 return true;
1001 }
1002 }
1003
1004 return false;
1005}
1006
1008 MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S)
1009 : ScheduleDAGMILive(C, std::move(S)), ST(MF.getSubtarget<GCNSubtarget>()),
1010 MFI(*MF.getInfo<SIMachineFunctionInfo>()),
1011 StartingOccupancy(MFI.getOccupancy()), MinOccupancy(StartingOccupancy),
1012 RegionLiveOuts(this, /*IsLiveOut=*/true) {
1013
1014 // We want regions with a single MI to be scheduled so that we can reason
1015 // about them correctly during scheduling stages that move MIs between regions
1016 // (e.g., rematerialization).
1018 LLVM_DEBUG(dbgs() << "Starting occupancy is " << StartingOccupancy << ".\n");
1019 if (ST.getCLOpts().schedule_relaxed_occupancy) {
1020 MinOccupancy = std::min(MFI.getMinAllowedOccupancy(), StartingOccupancy);
1021 if (MinOccupancy != StartingOccupancy)
1022 LLVM_DEBUG(dbgs() << "Allowing Occupancy drops to " << MinOccupancy
1023 << ".\n");
1024 }
1025}
1026
1027std::unique_ptr<GCNSchedStage>
1028GCNScheduleDAGMILive::createSchedStage(GCNSchedStageID SchedStageID) {
1029 switch (SchedStageID) {
1031 return std::make_unique<OccInitialScheduleStage>(SchedStageID, *this);
1033 return std::make_unique<RewriteMFMAFormStage>(SchedStageID, *this);
1035 return std::make_unique<UnclusteredHighRPStage>(SchedStageID, *this);
1037 return std::make_unique<ClusteredLowOccStage>(SchedStageID, *this);
1039 return std::make_unique<PreRARematStage>(SchedStageID, *this);
1041 return std::make_unique<ILPInitialScheduleStage>(SchedStageID, *this);
1043 return std::make_unique<MemoryClauseInitialScheduleStage>(SchedStageID,
1044 *this);
1046 return std::make_unique<LiveIntervalRPStage>(SchedStageID, *this);
1047 }
1048
1049 llvm_unreachable("Unknown SchedStageID.");
1050}
1051
1053 // Collect all scheduling regions. The actual scheduling is performed in
1054 // GCNScheduleDAGMILive::finalizeSchedule.
1055 Regions.push_back(std::pair(RegionBegin, RegionEnd));
1056}
1057
1058GCNRegPressure GCNScheduleDAGMILive::getRealRegPressure(
1059 unsigned RegionIdx,
1060 std::function<void(const GCNRegPressure &)> PressureCallback) const {
1061 if (Regions[RegionIdx].first == Regions[RegionIdx].second) {
1062 GCNRegPressure RP = llvm::getRegPressure(MRI, LiveIns[RegionIdx]);
1063 if (PressureCallback)
1064 PressureCallback(RP);
1065 return RP;
1066 }
1068 bool HasInstrs =
1069 RPTracker.reset(*Regions[RegionIdx].first, Regions[RegionIdx].second,
1070 &LiveIns[RegionIdx]);
1071 // reset() does not pass the live-in pressure to the callback.
1072 if (PressureCallback) {
1073 PressureCallback(RPTracker.getPressure());
1074 RPTracker.setPressureCallback(std::move(PressureCallback));
1075 }
1076 if (HasInstrs)
1077 RPTracker.advance(Regions[RegionIdx].second);
1078 return RPTracker.moveMaxPressure();
1079}
1080
1082 MachineBasicBlock::iterator RegionEnd) {
1083 assert(RegionBegin != RegionEnd && "Region must not be empty");
1084 return &*skipDebugInstructionsBackward(std::prev(RegionEnd), RegionBegin);
1085}
1086
1087void GCNScheduleDAGMILive::computeBlockPressure(unsigned RegionIdx,
1088 const MachineBasicBlock *MBB) {
1089 GCNDownwardRPTracker RPTracker(*LIS);
1090
1091 // If the block has the only successor then live-ins of that successor are
1092 // live-outs of the current block. We can reuse calculated live set if the
1093 // successor will be sent to scheduling past current block.
1094
1095 // However, due to the bug in LiveInterval analysis it may happen that two
1096 // predecessors of the same successor block have different lane bitmasks for
1097 // a live-out register. Workaround that by sticking to one-to-one relationship
1098 // i.e. one predecessor with one successor block.
1099 const MachineBasicBlock *OnlySucc = nullptr;
1100 if (MBB->succ_size() == 1) {
1101 auto *Candidate = *MBB->succ_begin();
1102 if (!Candidate->empty() && Candidate->pred_size() == 1) {
1103 SlotIndexes *Ind = LIS->getSlotIndexes();
1104 if (Ind->getMBBStartIdx(MBB) < Ind->getMBBStartIdx(Candidate))
1105 OnlySucc = Candidate;
1106 }
1107 }
1108
1109 // Scheduler sends regions from the end of the block upwards.
1110 size_t CurRegion = RegionIdx;
1111 for (size_t E = Regions.size(); CurRegion != E; ++CurRegion)
1112 if (Regions[CurRegion].first->getParent() != MBB)
1113 break;
1114 --CurRegion;
1115
1116 auto I = MBB->begin();
1117 auto LiveInIt = MBBLiveIns.find(MBB);
1118 auto &Rgn = Regions[CurRegion];
1119 auto *NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
1120 if (LiveInIt != MBBLiveIns.end()) {
1121 auto LiveIn = std::move(LiveInIt->second);
1122 RPTracker.reset(*MBB->begin(), MBB->end(), &LiveIn);
1123 MBBLiveIns.erase(LiveInIt);
1124 } else {
1125 I = Rgn.first;
1126 auto LRS = BBLiveInMap.lookup(NonDbgMI);
1127#ifdef EXPENSIVE_CHECKS
1128 assert(isEqual(getLiveRegsBefore(*NonDbgMI, *LIS), LRS));
1129#endif
1130 RPTracker.reset(*I, I->getParent()->end(), &LRS);
1131 }
1132
1133 for (;;) {
1134 I = RPTracker.getNext();
1135
1136 if (Regions[CurRegion].first == I || NonDbgMI == I) {
1137 LiveIns[CurRegion] = RPTracker.getLiveRegs();
1138 RPTracker.clearMaxPressure();
1139 }
1140
1141 if (Regions[CurRegion].second == I) {
1142 Pressure[CurRegion] = RPTracker.moveMaxPressure();
1143 if (CurRegion-- == RegionIdx)
1144 break;
1145 auto &Rgn = Regions[CurRegion];
1146 NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
1147 }
1148 RPTracker.advanceBeforeNext();
1149 RPTracker.advanceToNext();
1150 }
1151
1152 if (OnlySucc) {
1153 if (I != MBB->end()) {
1154 RPTracker.advanceBeforeNext();
1155 RPTracker.advanceToNext();
1156 RPTracker.advance(MBB->end());
1157 }
1158 MBBLiveIns[OnlySucc] = RPTracker.moveLiveRegs();
1159 }
1160}
1161
1163GCNScheduleDAGMILive::getRegionLiveInMap() const {
1164 assert(!Regions.empty());
1165 std::vector<MachineInstr *> RegionFirstMIs;
1166 RegionFirstMIs.reserve(Regions.size());
1167 for (auto &[RegionBegin, RegionEnd] : reverse(Regions))
1168 RegionFirstMIs.push_back(
1170
1171 return getLiveRegMap(RegionFirstMIs, /*After=*/false, *LIS);
1172}
1173
1175GCNScheduleDAGMILive::getRegionLiveOutMap() const {
1176 assert(!Regions.empty());
1177 std::vector<MachineInstr *> RegionLastMIs;
1178 RegionLastMIs.reserve(Regions.size());
1179 for (auto &[RegionBegin, RegionEnd] : reverse(Regions)) {
1180 // Skip empty regions.
1181 if (RegionBegin == RegionEnd)
1182 continue;
1183 RegionLastMIs.push_back(getLastMIForRegion(RegionBegin, RegionEnd));
1184 }
1185 return getLiveRegMap(RegionLastMIs, /*After=*/true, *LIS);
1186}
1187
1189 IdxToInstruction.clear();
1190
1191 RegionLiveRegMap =
1192 IsLiveOut ? DAG->getRegionLiveOutMap() : DAG->getRegionLiveInMap();
1193 for (unsigned I = 0; I < DAG->Regions.size(); I++) {
1194 auto &[RegionBegin, RegionEnd] = DAG->Regions[I];
1195 // Skip empty regions.
1196 if (RegionBegin == RegionEnd)
1197 continue;
1198 MachineInstr *RegionKey =
1199 IsLiveOut ? getLastMIForRegion(RegionBegin, RegionEnd) : &*RegionBegin;
1200 IdxToInstruction[I] = RegionKey;
1201 }
1202}
1203
1205 // Start actual scheduling here. This function is called by the base
1206 // MachineScheduler after all regions have been recorded by
1207 // GCNScheduleDAGMILive::schedule().
1208 LiveIns.resize(Regions.size());
1209 Pressure.resize(Regions.size());
1210 RegionsWithHighRP.resize(static_cast<unsigned>(Regions.size()));
1211 RegionsWithExcessRP.resize(static_cast<unsigned>(Regions.size()));
1212 RegionsWithIGLPInstrs.resize(static_cast<unsigned>(Regions.size()));
1213 RegionsWithHighRP.reset();
1214 RegionsWithExcessRP.reset();
1215 RegionsWithIGLPInstrs.reset();
1216
1217 runSchedStages();
1218}
1219
1220void GCNScheduleDAGMILive::runSchedStages() {
1221 LLVM_DEBUG(dbgs() << "All regions recorded, starting actual scheduling.\n");
1222
1223 GCNSchedStrategy &S = static_cast<GCNSchedStrategy &>(*SchedImpl);
1224 if (!Regions.empty()) {
1225 BBLiveInMap = getRegionLiveInMap();
1226 if (S.useGCNTrackers())
1227 RegionLiveOuts.buildLiveRegMap();
1228 }
1229
1230#ifndef NDEBUG
1231 if (ST.getCLOpts().print_max_reg_pressure_regusage_before_scheduler) {
1234 LIS->dump();
1235 }
1236#endif
1237
1238 while (S.advanceStage()) {
1239 auto Stage = createSchedStage(S.getCurrentStage());
1240 if (!Stage->initGCNSchedStage())
1241 continue;
1242
1243 for (auto Region : Regions) {
1244 RegionBegin = Region.first;
1245 RegionEnd = Region.second;
1246 // Setup for scheduling the region and check whether it should be skipped.
1247 if (!Stage->initGCNRegion()) {
1248 Stage->advanceRegion();
1249 exitRegion();
1250 continue;
1251 }
1252
1253 if (S.useGCNTrackers()) {
1254 const unsigned RegionIdx = Stage->getRegionIdx();
1255 S.getDownwardTracker().reset(MRI, LiveIns[RegionIdx]);
1257 MRI, RegionLiveOuts.getLiveRegsForRegionIdx(RegionIdx));
1258 }
1259
1261 Stage->finalizeGCNRegion();
1262 Stage->advanceRegion();
1263 exitRegion();
1264 }
1265
1266 Stage->finalizeGCNSchedStage();
1267 }
1268
1269#ifndef NDEBUG
1270 if (ST.getCLOpts().print_max_reg_pressure_regusage_after_scheduler) {
1273 LIS->dump();
1274 }
1275#endif
1276}
1277
1278#ifndef NDEBUG
1280 switch (StageID) {
1282 OS << "Max Occupancy Initial Schedule";
1283 break;
1285 OS << "Instruction Rewriting Reschedule";
1286 break;
1288 OS << "Unclustered High Register Pressure Reschedule";
1289 break;
1291 OS << "Clustered Low Occupancy Reschedule";
1292 break;
1294 OS << "Pre-RA Rematerialize";
1295 break;
1297 OS << "Max ILP Initial Schedule";
1298 break;
1300 OS << "Max memory clause Initial Schedule";
1301 break;
1303 OS << "Live Interval RP Reschedule";
1304 break;
1305 }
1306
1307 return OS;
1308}
1309#endif
1310
1314
1316 if (!DAG.LIS)
1317 return false;
1318
1319 LLVM_DEBUG(dbgs() << "Starting scheduling stage: " << StageID << "\n");
1320 return true;
1321}
1322
1323void RewriteMFMAFormStage::findReachingDefs(
1324 MachineOperand &UseMO, LiveIntervals *LIS,
1325 SmallVectorImpl<SlotIndex> &DefIdxs) {
1326 MachineInstr *UseMI = UseMO.getParent();
1327 LiveInterval &UseLI = LIS->getInterval(UseMO.getReg());
1328 VNInfo *VNI = UseLI.getVNInfoAt(LIS->getInstructionIndex(*UseMI));
1329
1330 // If the def is not a PHI, then it must be the only reaching def.
1331 if (!VNI->isPHIDef()) {
1332 DefIdxs.push_back(VNI->def);
1333 return;
1334 }
1335
1336 SmallPtrSet<MachineBasicBlock *, 8> Visited = {UseMI->getParent()};
1338
1339 // Mark the predecessor blocks for traversal
1340 for (MachineBasicBlock *PredMBB : UseMI->getParent()->predecessors()) {
1341 Worklist.push_back(PredMBB);
1342 Visited.insert(PredMBB);
1343 }
1344
1345 while (!Worklist.empty()) {
1346 MachineBasicBlock *CurrMBB = Worklist.pop_back_val();
1347
1348 SlotIndex CurrMBBEnd = LIS->getMBBEndIdx(CurrMBB);
1349 VNInfo *VNI = UseLI.getVNInfoAt(CurrMBBEnd.getPrevSlot());
1350
1351 MachineBasicBlock *DefMBB = LIS->getMBBFromIndex(VNI->def);
1352
1353 // If there is a def in this block, then add it to the list. This is the
1354 // reaching def of this path.
1355 if (!VNI->isPHIDef()) {
1356 DefIdxs.push_back(VNI->def);
1357 continue;
1358 }
1359
1360 for (MachineBasicBlock *PredMBB : DefMBB->predecessors()) {
1361 if (Visited.insert(PredMBB).second)
1362 Worklist.push_back(PredMBB);
1363 }
1364 }
1365}
1366
1367void RewriteMFMAFormStage::findReachingUses(
1368 const MachineInstr *DefMI, LiveIntervals *LIS,
1369 SmallVectorImpl<MachineOperand *> &ReachingUses) {
1370 SlotIndex DefIdx = LIS->getInstructionIndex(*DefMI);
1371 for (MachineOperand &UseMO :
1372 DAG.MRI.use_nodbg_operands(DefMI->getOperand(0).getReg())) {
1373 SmallVector<SlotIndex, 8> ReachingDefIndexes;
1374 findReachingDefs(UseMO, LIS, ReachingDefIndexes);
1375
1376 // If we find a use that contains this DefMI in its reachingDefs, then it is
1377 // a reaching use.
1378 if (any_of(ReachingDefIndexes, [DefIdx](SlotIndex RDIdx) {
1379 return SlotIndex::isSameInstr(RDIdx, DefIdx);
1380 }))
1381 ReachingUses.push_back(&UseMO);
1382 }
1383}
1384
1386 // We only need to run this pass if the architecture supports AGPRs.
1387 // Additionally, we don't use AGPRs at occupancy levels above 1 so there
1388 // is no need for this pass in that case, either.
1389 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1390 if (!ST.hasGFX90AInsts() || MFI.getMinWavesPerEU() > 1)
1391 return false;
1392
1393 RegionsWithExcessArchVGPR.resize(static_cast<unsigned>(DAG.Regions.size()));
1394 RegionsWithExcessArchVGPR.reset();
1395 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++) {
1397 if (PressureBefore.getArchVGPRNum() > ST.getAddressableNumArchVGPRs())
1398 RegionsWithExcessArchVGPR[Region] = true;
1399 }
1400
1401 if (RegionsWithExcessArchVGPR.none())
1402 return false;
1403
1404 TII = ST.getInstrInfo();
1405 SRI = ST.getRegisterInfo();
1406
1407 std::vector<std::pair<MachineInstr *, unsigned>> RewriteCands;
1410
1411 if (!initHeuristics(RewriteCands, CopyForUse, CopyForDef))
1412 return false;
1413
1414 int64_t Cost = getRewriteCost(RewriteCands, CopyForUse, CopyForDef);
1415
1416 // If we haven't found the beneficial conditions, prefer the VGPR form which
1417 // may result in less cross RC copies.
1418 if (Cost > 0)
1419 return false;
1420
1421 return rewrite(RewriteCands);
1422}
1423
1425 if (!ST.getCLOpts().unclustered_high_rp_reschedule)
1426 return false;
1427
1429 return false;
1430
1431 if (DAG.RegionsWithHighRP.none() && DAG.RegionsWithExcessRP.none())
1432 return false;
1433
1434 SavedMutations.swap(DAG.Mutations);
1435 DAG.addMutation(
1437
1438 InitialOccupancy = DAG.MinOccupancy;
1439 // Aggressively try to reduce register pressure in the unclustered high RP
1440 // stage. Temporarily increase occupancy target in the region.
1441 TempTargetOccupancy = MFI.getMaxWavesPerEU() > DAG.MinOccupancy
1442 ? InitialOccupancy + 1
1443 : InitialOccupancy;
1444 IsAnyRegionScheduled = false;
1445 S.SGPRLimitBias = S.HighRPSGPRBias;
1446 S.VGPRLimitBias = S.HighRPVGPRBias;
1447
1448 LLVM_DEBUG(
1449 dbgs()
1450 << "Retrying function scheduling without clustering. "
1451 "Aggressively try to reduce register pressure to achieve occupancy "
1452 << TempTargetOccupancy << ".\n");
1453
1454 return true;
1455}
1456
1458 if (!ST.getCLOpts().clustered_low_occupancy_reschedule)
1459 return false;
1460
1462 return false;
1463
1464 // Don't bother trying to improve ILP in lower RP regions if occupancy has not
1465 // been dropped. All regions will have already been scheduled with the ideal
1466 // occupancy targets.
1467 if (DAG.StartingOccupancy <= DAG.MinOccupancy)
1468 return false;
1469
1470 LLVM_DEBUG(
1471 dbgs() << "Retrying function scheduling with lowest recorded occupancy "
1472 << DAG.MinOccupancy << ".\n");
1473 return true;
1474}
1475
1477 // FIXME: This pass will invalidate cached BBLiveInMap and MBBLiveIns for
1478 // regions inbetween the defs and region we sinked the def to. Will need to be
1479 // fixed if there is another pass after this pass.
1480 assert(!S.hasNextStage());
1481
1482 if (!GCNSchedStage::initGCNSchedStage() || DAG.Regions.size() <= 1)
1483 return false;
1484
1485 // Set up "spilling targets" for all regions.
1486 const Function &F = MF.getFunction();
1487 unsigned MaxSGPRs = ST.getMaxNumSGPRs(F);
1488 unsigned MaxVGPRs = ST.getMaxNumVGPRs(F);
1489
1490 const unsigned VGPRBlockSize = MFI.getDynamicVGPRBlockSize();
1491 bool HasVectorRegisterExcess = false;
1492 for (const GCNRegPressure &RP : DAG.Pressure) {
1493 if (GCNRPTarget(MaxSGPRs, MaxVGPRs, MF, RP).hasVectorRegisterExcess()) {
1494 HasVectorRegisterExcess = true;
1495 break;
1496 }
1497 }
1498 if (HasVectorRegisterExcess || DAG.MinOccupancy >= MFI.getMaxWavesPerEU()) {
1499 // In addition to register usage being above addressable limits, occupancy
1500 // below the minimum is considered like "spilling" as well.
1501 TargetOcc = std::nullopt;
1502 } else {
1503 // There is no spilling and room to improve occupancy; set up "increased
1504 // occupancy targets" for all regions.
1505 TargetOcc = DAG.MinOccupancy + 1;
1506 MaxSGPRs = ST.getMaxNumSGPRs(*TargetOcc, false);
1507 MaxVGPRs = ST.getMaxNumVGPRs(*TargetOcc, VGPRBlockSize);
1508 }
1509
1510 LLVM_DEBUG({
1511 dbgs() << "In function ";
1512 MF.getFunction().printAsOperand(dbgs(), false);
1513 dbgs() << ": rematerializing to ";
1514 if (TargetOcc) {
1515 dbgs() << "increase occupancy from " << *TargetOcc - 1 << '\n';
1516 } else {
1517 dbgs() << "reduce spilling (minimum target occupancy is "
1518 << MFI.getMinWavesPerEU() << ")\n";
1519 }
1520 });
1521
1522 LiveOuts.reserve(DAG.Regions.size());
1523 DAG.RegionLiveOuts.buildLiveRegMap();
1524 for (unsigned RegionIdx : seq(DAG.Regions.size()))
1525 LiveOuts.push_back(DAG.RegionLiveOuts.getLiveRegsForRegionIdx(RegionIdx));
1526
1527 Strategy = std::make_unique<GCNRematStrategy>(MF, DAG.Regions, DAG.LiveIns,
1528 LiveOuts, *DAG.LIS, *DAG.MBFI);
1529 if (TargetOcc.has_value()) {
1530 // Rematerialization is likely to move instructions into higher frequency
1531 // regions, increasing their total sum latency. This is acceptable if we are
1532 // eliminating spills in the process, but when the goal is increasing
1533 // occupancy we get nothing out of rematerialization if occupancy is not
1534 // increased in the end; in such cases we want to be able to roll back
1535 // rematerializations.
1536 Strategy->startRecordingRemats();
1537 }
1538
1539 RescheduleRegions.resize(DAG.Regions.size());
1540 MutableArrayRef<GCNRegPressure> MaxPressure = DAG.Pressure;
1541 Strategy->rematerializeFor(MaxSGPRs, MaxVGPRs,
1542 /*ReduceSpill=*/!TargetOcc.has_value(),
1543 RescheduleRegions, &MaxPressure);
1544 if (RescheduleRegions.none())
1545 return false;
1546
1547 // Reflect changes in the DAG and compute achieved occupancy.
1548 LLVM_DEBUG(dbgs() << "==== REMAT RESULTS ====\n");
1549 for (unsigned RegionIdx : RescheduleRegions.set_bits()) {
1550 DAG.RegionLiveOuts.getLiveRegsForRegionIdx(RegionIdx) = LiveOuts[RegionIdx];
1551 LLVM_DEBUG(dbgs() << '[' << RegionIdx << "] Achieved occupancy "
1552 << DAG.Pressure[RegionIdx].getOccupancy(ST, VGPRBlockSize)
1553 << '\n');
1554 }
1555 AchievedOcc = MFI.getMaxWavesPerEU();
1556 for (const GCNRegPressure &RP : DAG.Pressure)
1557 AchievedOcc = std::min(AchievedOcc, RP.getOccupancy(ST, VGPRBlockSize));
1558
1559 LLVM_DEBUG({
1560 dbgs() << "Retrying function scheduling with new min. occupancy of "
1561 << AchievedOcc << " from rematerializing (original was "
1562 << DAG.MinOccupancy;
1563 if (TargetOcc)
1564 dbgs() << ", target was " << *TargetOcc;
1565 dbgs() << ")\n";
1566 });
1567
1568 DAG.setTargetOccupancy(getStageTargetOccupancy());
1569 return true;
1570}
1571
1573 DAG.finishBlock();
1574 LLVM_DEBUG(dbgs() << "Ending scheduling stage: " << StageID << "\n");
1575}
1576
1578 SavedMutations.swap(DAG.Mutations);
1579 S.SGPRLimitBias = S.VGPRLimitBias = 0;
1580 if (DAG.MinOccupancy > InitialOccupancy) {
1581 assert(IsAnyRegionScheduled);
1583 << " stage successfully increased occupancy to "
1584 << DAG.MinOccupancy << '\n');
1585 } else if (!IsAnyRegionScheduled) {
1586 assert(DAG.MinOccupancy == InitialOccupancy);
1588 << ": No regions scheduled, min occupancy stays at "
1589 << DAG.MinOccupancy << ", MFI occupancy stays at "
1590 << MFI.getOccupancy() << ".\n");
1591 }
1592
1594}
1595
1597 // Skip empty scheduling region.
1598 if (DAG.begin() == DAG.end())
1599 return false;
1600
1601 // Check whether this new region is also a new block.
1602 if (DAG.RegionBegin->getParent() != CurrentMBB)
1603 setupNewBlock();
1604
1605 unsigned NumRegionInstrs =
1606 static_cast<unsigned>(std::distance(DAG.begin(), DAG.end()));
1607 DAG.enterRegion(CurrentMBB, DAG.begin(), DAG.end(), NumRegionInstrs);
1608
1609 // Skip regions with 1 schedulable instruction.
1610 if (DAG.begin() == std::prev(DAG.end()))
1611 return false;
1612
1613 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
1614 LLVM_DEBUG(dbgs() << MF.getName() << ":" << printMBBReference(*CurrentMBB)
1615 << " " << CurrentMBB->getName()
1616 << "\n From: " << *DAG.begin() << " To: ";
1617 if (DAG.RegionEnd != CurrentMBB->end()) dbgs() << *DAG.RegionEnd;
1618 else dbgs() << "End";
1619 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
1620
1621 // Save original instruction order before scheduling for possible revert.
1622 Unsched.clear();
1623 Unsched.reserve(DAG.NumRegionInstrs);
1626 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG.TII);
1627 for (auto &I : DAG) {
1628 Unsched.push_back(&I);
1629 if (SII->isIGLPMutationOnly(I.getOpcode()))
1630 DAG.RegionsWithIGLPInstrs[RegionIdx] = true;
1631 }
1632 } else {
1633 for (auto &I : DAG)
1634 Unsched.push_back(&I);
1635 }
1636
1637 PressureBefore = DAG.Pressure[RegionIdx];
1638
1639 LLVM_DEBUG(
1640 dbgs() << "Pressure before scheduling:\nRegion live-ins:"
1641 << print(DAG.LiveIns[RegionIdx], DAG.MRI)
1642 << "Region live-in pressure: "
1643 << print(llvm::getRegPressure(DAG.MRI, DAG.LiveIns[RegionIdx]))
1644 << "Region register pressure: " << print(PressureBefore));
1645
1646 S.HasHighPressure = false;
1647 S.KnownExcessRP = isRegionWithExcessRP();
1648
1649 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1651 SavedMutations.clear();
1652 SavedMutations.swap(DAG.Mutations);
1653 bool IsInitialStage = StageID == GCNSchedStageID::OccInitialSchedule ||
1655 DAG.addMutation(createIGroupLPDAGMutation(
1656 IsInitialStage ? AMDGPU::SchedulingPhase::Initial
1658 }
1659
1660 return true;
1661}
1662
1664 // Only reschedule regions that have excess register pressure (i.e. spilling)
1665 // or had minimum occupancy at the beginning of the stage (as long as
1666 // rescheduling of previous regions did not make occupancy drop back down to
1667 // the initial minimum).
1668 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1669 // If no region has been scheduled yet, the DAG has not yet been updated with
1670 // the occupancy target. So retrieve it from the temporary.
1671 unsigned CurrentTargetOccupancy =
1672 IsAnyRegionScheduled ? DAG.MinOccupancy : TempTargetOccupancy;
1673 if (!DAG.RegionsWithExcessRP[RegionIdx] &&
1674 (CurrentTargetOccupancy <= InitialOccupancy ||
1675 DAG.Pressure[RegionIdx].getOccupancy(ST, DynamicVGPRBlockSize) !=
1676 InitialOccupancy))
1677 return false;
1678
1679 bool IsSchedulingThisRegion = GCNSchedStage::initGCNRegion();
1680 // If this is the first region scheduled during this stage, make the target
1681 // occupancy changes in the DAG and MFI.
1682 if (!IsAnyRegionScheduled && IsSchedulingThisRegion) {
1683 IsAnyRegionScheduled = true;
1684 if (MFI.getMaxWavesPerEU() > DAG.MinOccupancy)
1685 DAG.setTargetOccupancy(TempTargetOccupancy);
1686 }
1687 return IsSchedulingThisRegion;
1688}
1689
1691 // We may need to reschedule this region if it wasn't rescheduled in the last
1692 // stage, or if we found it was testing critical register pressure limits in
1693 // the unclustered reschedule stage. The later is because we may not have been
1694 // able to raise the min occupancy in the previous stage so the region may be
1695 // overly constrained even if it was already rescheduled.
1696 if (!DAG.RegionsWithHighRP[RegionIdx])
1697 return false;
1698
1700}
1701
1703 return !RevertAllRegions && RescheduleRegions[RegionIdx] &&
1705}
1706
1708 if (CurrentMBB)
1709 DAG.finishBlock();
1710
1711 CurrentMBB = DAG.RegionBegin->getParent();
1712 DAG.startBlock(CurrentMBB);
1713 // Get real RP for the region if it hasn't be calculated before. After the
1714 // initial schedule stage real RP will be collected after scheduling.
1718 DAG.computeBlockPressure(RegionIdx, CurrentMBB);
1719}
1720
1722 DAG.Regions[RegionIdx] = std::pair(DAG.RegionBegin, DAG.RegionEnd);
1723 if (S.HasHighPressure)
1724 DAG.RegionsWithHighRP[RegionIdx] = true;
1725
1726 // Revert scheduling if we have dropped occupancy or there is some other
1727 // reason that the original schedule is better.
1729
1730 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1732 SavedMutations.swap(DAG.Mutations);
1733}
1734
1737 // When the goal is to increase occupancy, all regions must reach the target
1738 // occupancy for rematerializations to be possibly useful, otherwise we will
1739 // just hurt latency for no benefit. If minimum occupancy drops below the
1740 // target there is no point in trying to re-schedule further regions.
1741 if (!TargetOcc)
1742 return;
1743 RegionReverts.emplace_back(RegionIdx, Unsched, PressureBefore);
1744 if (DAG.MinOccupancy < *TargetOcc) {
1745 LLVM_DEBUG(dbgs() << "Region " << RegionIdx
1746 << " cannot meet occupancy target, interrupting "
1747 "re-scheduling in all regions\n");
1748 RevertAllRegions = true;
1749 }
1750}
1751
1753 // The maximum number of arch VGPR on non-unified register file, or the
1754 // maximum VGPR + AGPR in the unified register file case.
1755 unsigned MaxVGPRs = ST.getMaxNumVGPRs(MF);
1756 // The maximum number of arch VGPR for both unified and non-unified register
1757 // file.
1758 unsigned MaxArchVGPRs = std::min(MaxVGPRs, ST.getAddressableNumArchVGPRs());
1759
1760 // The region maximum keeps the VGPR and AVGPR pressure of a single point, so
1761 // distributing it across the banks can miss a rigid peak at another point.
1762 // Distribute the pressure of each point instead.
1763 bool AVGPRBanking = ST.getCLOpts().avgpr_banking;
1764 unsigned ArchVGPRBankLimit, AGPRBankLimit;
1765 std::tie(ArchVGPRBankLimit, AGPRBankLimit) = S.getBankLimits();
1766 unsigned BankedArchVGPRPeak = 0, BankedAGPRPeak = 0, BankedUnifiedPeak = 0;
1767 std::function<void(const GCNRegPressure &)> TrackBankedPeaks;
1768 if (AVGPRBanking) {
1769 TrackBankedPeaks = [&](const GCNRegPressure &RP) {
1770 auto [ArchNum, AccNum] =
1771 RP.getBankedVGPRNum(ArchVGPRBankLimit, AGPRBankLimit);
1772 BankedArchVGPRPeak = std::max(BankedArchVGPRPeak, ArchNum);
1773 BankedAGPRPeak = std::max(BankedAGPRPeak, AccNum);
1774 BankedUnifiedPeak =
1775 std::max(BankedUnifiedPeak,
1777 };
1778 }
1779
1780 // Check the results of scheduling.
1781 PressureAfter = DAG.getRealRegPressure(RegionIdx, TrackBankedPeaks);
1782
1783 LLVM_DEBUG(dbgs() << "Pressure after scheduling: " << print(PressureAfter));
1784 LLVM_DEBUG(dbgs() << "Region: " << RegionIdx << ".\n");
1785
1786 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1787
1788 bool UnifiedVGPRFile = ST.hasGFX90AInsts();
1789 unsigned VectorCriticalLimit =
1790 UnifiedVGPRFile ? S.UnifiedVGPRCriticalLimit : S.VGPRCriticalLimit;
1791 // Fitting the combined occupancy budget does not rule out spilling in one
1792 // bank. Keep the per-bank excess checks before taking this early exit.
1793 if (PressureAfter.getSGPRNum() <= S.SGPRCriticalLimit &&
1794 PressureAfter.getVGPRNum(UnifiedVGPRFile) <= VectorCriticalLimit &&
1795 (!UnifiedVGPRFile ||
1796 (PressureAfter.getArchVGPRNum() <= S.VGPRExcessLimit &&
1797 PressureAfter.getAGPRNum() <= S.AGPRExcessLimit))) {
1798 DAG.Pressure[RegionIdx] = PressureAfter;
1799
1800 // Early out if we have achieved the occupancy target.
1801 LLVM_DEBUG(dbgs() << "Pressure in desired limits, done.\n");
1802 return;
1803 }
1804
1805 unsigned TargetOccupancy = std::min(
1806 S.getTargetOccupancy(), ST.getOccupancyWithWorkGroupSizes(MF).second);
1807 unsigned WavesAfter = std::min(
1808 TargetOccupancy, PressureAfter.getOccupancy(ST, DynamicVGPRBlockSize));
1809 unsigned WavesBefore = std::min(
1810 TargetOccupancy, PressureBefore.getOccupancy(ST, DynamicVGPRBlockSize));
1811 LLVM_DEBUG(dbgs() << "Occupancy before scheduling: " << WavesBefore
1812 << ", after " << WavesAfter << ".\n");
1813
1814 // We may not be able to keep the current target occupancy because of the just
1815 // scheduled region. We might still be able to revert scheduling if the
1816 // occupancy before was higher, or if the current schedule has register
1817 // pressure higher than the excess limits which could lead to more spilling.
1818 unsigned NewOccupancy = std::max(WavesAfter, WavesBefore);
1819
1820 // Allow memory bound functions to drop to 4 waves if not limited by an
1821 // attribute.
1822 if (WavesAfter < WavesBefore && WavesAfter < DAG.MinOccupancy &&
1823 WavesAfter >= MFI.getMinAllowedOccupancy()) {
1824 LLVM_DEBUG(dbgs() << "Function is memory bound, allow occupancy drop up to "
1825 << MFI.getMinAllowedOccupancy() << " waves\n");
1826 NewOccupancy = WavesAfter;
1827 }
1828
1829 if (NewOccupancy < DAG.MinOccupancy) {
1830 DAG.MinOccupancy = NewOccupancy;
1831 MFI.limitOccupancy(DAG.MinOccupancy);
1832 LLVM_DEBUG(dbgs() << "Occupancy lowered for the function to "
1833 << DAG.MinOccupancy << ".\n");
1834 }
1835 unsigned MaxSGPRs = ST.getMaxNumSGPRs(MF);
1836
1837 bool BankExcess = AVGPRBanking
1838 ? BankedArchVGPRPeak > ArchVGPRBankLimit ||
1839 BankedAGPRPeak > AGPRBankLimit
1840 : PressureAfter.getArchVGPRNum() > MaxArchVGPRs ||
1841 PressureAfter.getAGPRNum() > MaxArchVGPRs;
1842
1843 unsigned VGPRNum = AVGPRBanking && UnifiedVGPRFile
1844 ? BankedUnifiedPeak
1845 : PressureAfter.getVGPRNum(UnifiedVGPRFile);
1846 if (VGPRNum > MaxVGPRs || BankExcess ||
1847 PressureAfter.getSGPRNum() > MaxSGPRs) {
1848 DAG.RegionsWithHighRP[RegionIdx] = true;
1849 DAG.RegionsWithExcessRP[RegionIdx] = true;
1850 }
1851
1852 // Revert if this region's schedule would cause a drop in occupancy or
1853 // spilling.
1854 if (shouldRevertScheduling(WavesAfter)) {
1856 std::tie(DAG.RegionBegin, DAG.RegionEnd) = DAG.Regions[RegionIdx];
1857 } else {
1858 DAG.Pressure[RegionIdx] = PressureAfter;
1859 }
1860}
1861
1862unsigned
1863GCNSchedStage::computeSUnitReadyCycle(const SUnit &SU, unsigned CurrCycle,
1864 DenseMap<unsigned, unsigned> &ReadyCycles,
1865 const TargetSchedModel &SM) {
1866 unsigned ReadyCycle = CurrCycle;
1867 for (auto &D : SU.Preds) {
1868 if (D.isAssignedRegDep()) {
1869 MachineInstr *DefMI = D.getSUnit()->getInstr();
1870 unsigned Latency = SM.computeInstrLatency(DefMI);
1871 unsigned DefReady = ReadyCycles[DAG.getSUnit(DefMI)->NodeNum];
1872 ReadyCycle = std::max(ReadyCycle, DefReady + Latency);
1873 }
1874 }
1875 ReadyCycles[SU.NodeNum] = ReadyCycle;
1876 return ReadyCycle;
1877}
1878
1879#ifndef NDEBUG
1881 bool operator()(std::pair<MachineInstr *, unsigned> A,
1882 std::pair<MachineInstr *, unsigned> B) const {
1883 return A.second < B.second;
1884 }
1885};
1886
1887static void printScheduleModel(std::set<std::pair<MachineInstr *, unsigned>,
1888 EarlierIssuingCycle> &ReadyCycles) {
1889 if (ReadyCycles.empty())
1890 return;
1891 unsigned BBNum = ReadyCycles.begin()->first->getParent()->getNumber();
1892 dbgs() << "\n################## Schedule time ReadyCycles for MBB : " << BBNum
1893 << " ##################\n# Cycle #\t\t\tInstruction "
1894 " "
1895 " \n";
1896 unsigned IPrev = 1;
1897 for (auto &I : ReadyCycles) {
1898 if (I.second > IPrev + 1)
1899 dbgs() << "****************************** BUBBLE OF " << I.second - IPrev
1900 << " CYCLES DETECTED ******************************\n\n";
1901 dbgs() << "[ " << I.second << " ] : " << *I.first << "\n";
1902 IPrev = I.second;
1903 }
1904}
1905#endif
1906
1908GCNSchedStage::getScheduleMetrics(const std::vector<SUnit> &InputSchedule) {
1909#ifndef NDEBUG
1910 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
1911 ReadyCyclesSorted;
1912#endif
1913 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
1914 unsigned SumBubbles = 0;
1915 DenseMap<unsigned, unsigned> ReadyCycles;
1916 unsigned CurrCycle = 0;
1917 for (auto &SU : InputSchedule) {
1918 unsigned ReadyCycle =
1919 computeSUnitReadyCycle(SU, CurrCycle, ReadyCycles, SM);
1920 SumBubbles += ReadyCycle - CurrCycle;
1921#ifndef NDEBUG
1922 ReadyCyclesSorted.insert(std::make_pair(SU.getInstr(), ReadyCycle));
1923#endif
1924 CurrCycle = ++ReadyCycle;
1925 }
1926#ifndef NDEBUG
1927 LLVM_DEBUG(
1928 printScheduleModel(ReadyCyclesSorted);
1929 dbgs() << "\n\t"
1930 << "Metric: "
1931 << (SumBubbles
1932 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
1933 : 1)
1934 << "\n\n");
1935#endif
1936
1937 return ScheduleMetrics(CurrCycle, SumBubbles);
1938}
1939
1942#ifndef NDEBUG
1943 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
1944 ReadyCyclesSorted;
1945#endif
1946 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
1947 unsigned SumBubbles = 0;
1948 DenseMap<unsigned, unsigned> ReadyCycles;
1949 unsigned CurrCycle = 0;
1950 for (auto &MI : DAG) {
1951 SUnit *SU = DAG.getSUnit(&MI);
1952 if (!SU)
1953 continue;
1954 unsigned ReadyCycle =
1955 computeSUnitReadyCycle(*SU, CurrCycle, ReadyCycles, SM);
1956 SumBubbles += ReadyCycle - CurrCycle;
1957#ifndef NDEBUG
1958 ReadyCyclesSorted.insert(std::make_pair(SU->getInstr(), ReadyCycle));
1959#endif
1960 CurrCycle = ++ReadyCycle;
1961 }
1962#ifndef NDEBUG
1963 LLVM_DEBUG(
1964 printScheduleModel(ReadyCyclesSorted);
1965 dbgs() << "\n\t"
1966 << "Metric: "
1967 << (SumBubbles
1968 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
1969 : 1)
1970 << "\n\n");
1971#endif
1972
1973 return ScheduleMetrics(CurrCycle, SumBubbles);
1974}
1975
1976bool GCNSchedStage::shouldRevertScheduling(unsigned WavesAfter) {
1977 if (WavesAfter < DAG.MinOccupancy)
1978 return true;
1979
1980 // For dynamic VGPR mode, we don't want to waste any VGPR blocks.
1981 if (DAG.MFI.isDynamicVGPREnabled()) {
1982 unsigned BlocksBefore = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
1983 ST, PressureBefore.getVGPRNum(false),
1984 DAG.MFI.getDynamicVGPRBlockSize());
1985 unsigned BlocksAfter = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
1986 ST, PressureAfter.getVGPRNum(false), DAG.MFI.getDynamicVGPRBlockSize());
1987 if (BlocksAfter > BlocksBefore)
1988 return true;
1989 }
1990
1991 return false;
1992}
1993
1996 return false;
1997
1999 return true;
2000
2001 if (shouldRevertInitialSchedule(WavesAfter))
2002 return true;
2003
2004 return false;
2005}
2006
2008 // If RP is not reduced in the unclustered reschedule stage, revert to the
2009 // old schedule.
2010 if ((WavesAfter <=
2011 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()) &&
2012 mayCauseSpilling(WavesAfter)) ||
2014 LLVM_DEBUG(dbgs() << "Unclustered reschedule did not help.\n");
2015 return true;
2016 }
2017
2018 // Do not attempt to relax schedule even more if we are already spilling
2019 // VGPRs, or if reverting would spill VGPRs. SGPRs spill to VGPR lanes, which
2020 // is cheap, so if only SGPRs are in excess, still check that the new
2021 // schedule does not cost too much latency.
2022 if (isRegionWithExcessRP() &&
2023 (GCNRPTarget(MF, PressureBefore).hasVectorRegisterExcess() ||
2024 GCNRPTarget(MF, PressureAfter).hasVectorRegisterExcess()))
2025 return false;
2026
2027 LLVM_DEBUG(
2028 dbgs()
2029 << "\n\t *** In shouldRevertScheduling ***\n"
2030 << " *********** BEFORE UnclusteredHighRPStage ***********\n");
2031 ScheduleMetrics MBefore = getScheduleMetrics(DAG.SUnits);
2032 LLVM_DEBUG(
2033 dbgs()
2034 << "\n *********** AFTER UnclusteredHighRPStage ***********\n");
2036 unsigned OldMetric = MBefore.getMetric();
2037 unsigned NewMetric = MAfter.getMetric();
2038 unsigned ScheduleMetricBias = ST.getCLOpts().schedule_metric_bias;
2039 unsigned WavesBefore = std::min(
2040 S.getTargetOccupancy(),
2041 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()));
2042 unsigned Profit =
2043 ((WavesAfter * ScheduleMetrics::ScaleFactor) / WavesBefore *
2044 ((OldMetric + ScheduleMetricBias) * ScheduleMetrics::ScaleFactor) /
2045 NewMetric) /
2047 LLVM_DEBUG(dbgs() << "\tMetric before " << MBefore << "\tMetric after "
2048 << MAfter << "Profit: " << Profit << "\n");
2049 return Profit < ScheduleMetrics::ScaleFactor;
2050}
2051
2054 return false;
2055
2057 return true;
2058
2059 if (mayCauseSpilling(WavesAfter))
2060 return true;
2061
2062 return false;
2063}
2064
2066 return GCNSchedStage::shouldRevertScheduling(WavesAfter) ||
2067 mayCauseSpilling(WavesAfter);
2068}
2069
2071 if (shouldRevertInitialSchedule(WavesAfter))
2072 return true;
2073
2074 return false;
2075}
2076
2078 unsigned WavesAfter) {
2079 return shouldRevertInitialSchedule(WavesAfter);
2080}
2081
2083 if (!ST.getCLOpts().lirp_reschedule)
2084 return false;
2085
2087 return false;
2088
2089 if (!S.VGPRThresholdPercent) {
2090 LLVM_DEBUG(dbgs() << "LIRP: expected VGPRThresholdPercent to be enabled, "
2091 "not using live interval RP reschedule stage\n");
2092 return false;
2093 }
2094
2095 return true;
2096}
2097
2099 const AMDGPUOptions &CLOpts = ST.getCLOpts();
2100 unsigned InstantRP = DAG.Pressure[RegionIdx].getArchVGPRNum();
2101 auto [RegionBegin, RegionEnd] = DAG.Regions[RegionIdx];
2102 if (RegionBegin == RegionEnd)
2103 return false;
2104
2105 unsigned LIRP = estimateGreedyVGPRPressure(
2106 RegionBegin, RegionEnd, DAG.LiveIns[RegionIdx], *DAG.getLIS(),
2107 DAG.MF.getRegInfo(), static_cast<const SIRegisterInfo &>(*DAG.TRI));
2108
2109 unsigned NewVGPRThresholdPercent =
2110 (S.VGPRThresholdPercent * CLOpts.lirp_vgpr_reduction + 99) / 100;
2111
2112 LLVM_DEBUG(dbgs() << "LIRP: Region " << RegionIdx
2113 << ", VGPRThresholdPercent: " << S.VGPRThresholdPercent
2114 << " -> " << NewVGPRThresholdPercent
2115 << ", VGPRExcessLimit=" << S.VGPRExcessLimit
2116 << ", VGPRCriticalLimit=" << S.VGPRCriticalLimit
2117 << ", InstantRP=" << InstantRP << ", LIRP=" << LIRP);
2118
2119 bool DoRescheduling = false;
2120 // Lower bound on InstantRP to skip over tiny regions.
2121 unsigned InstantRPLowerBound =
2122 S.VGPRExcessLimit * CLOpts.lirp_instant_lower_bound / 100;
2123 if (LIRP > S.VGPRExcessLimit) {
2124 LLVM_DEBUG(dbgs() << " [LIRP exceeds the limit (" << S.VGPRExcessLimit
2125 << "), rescheduling]");
2126 DoRescheduling = true;
2127 } else if (LIRP > InstantRP && InstantRP > InstantRPLowerBound) {
2128 unsigned IncreasePercent = ((LIRP - InstantRP) * 100) / InstantRP;
2129 if (IncreasePercent > CLOpts.lirp_threshold) {
2130 LLVM_DEBUG(dbgs() << " [" << IncreasePercent << "% > "
2131 << CLOpts.lirp_threshold << "%, rescheduling]");
2132 DoRescheduling = true;
2133 }
2134 }
2135 LLVM_DEBUG(dbgs() << '\n');
2136
2137 if (DoRescheduling && GCNSchedStage::initGCNRegion()) {
2138 SavedVGPRExcessLimit = S.VGPRExcessLimit;
2139 SavedVGPRCriticalLimit = S.VGPRCriticalLimit;
2140 SavedUnifiedVGPRCriticalLimit = S.UnifiedVGPRCriticalLimit;
2141 SavedVGPRThresholdPercent = S.VGPRThresholdPercent;
2142 S.VGPRThresholdPercent = NewVGPRThresholdPercent;
2143 return true;
2144 }
2145
2146 return false;
2147}
2148
2150 S.VGPRExcessLimit = SavedVGPRExcessLimit;
2151 S.VGPRCriticalLimit = SavedVGPRCriticalLimit;
2152 S.UnifiedVGPRCriticalLimit = SavedUnifiedVGPRCriticalLimit;
2153 S.VGPRThresholdPercent = SavedVGPRThresholdPercent;
2155}
2156
2157bool GCNSchedStage::mayCauseSpilling(unsigned WavesAfter) {
2158 // Use the function's retained occupancy as the cap. A region that could
2159 // support more waves cannot raise the function's occupancy.
2160 if (WavesAfter <= MFI.getMinWavesPerEU() && isRegionWithExcessRP() &&
2161 !PressureAfter.less(MF, PressureBefore, DAG.MinOccupancy)) {
2162 LLVM_DEBUG(dbgs() << "New pressure will result in more spilling.\n");
2163 return true;
2164 }
2165
2166 return false;
2167}
2168
2170 if (DAG.SUnits.empty())
2171 return false;
2172
2173 ScheduleMetrics MBefore = getScheduleMetrics(DAG.SUnits);
2175 LLVM_DEBUG(dbgs() << "Metric before " << MBefore << "\tMetric after "
2176 << MAfter);
2177 return MAfter.getMetric() < MBefore.getMetric();
2178}
2179
2181 if (!mayCauseSpilling(WavesAfter))
2182 return false;
2183 // Use the same cap in both directions so latency only breaks a pressure tie.
2184 if (PressureBefore.less(MF, PressureAfter, DAG.MinOccupancy))
2185 return true;
2186
2187 if (!reducesLatency()) {
2188 LLVM_DEBUG(dbgs() << "Equivalent RP, new schedule does not reduce "
2189 "latency.\n");
2190 return true;
2191 }
2192 LLVM_DEBUG(dbgs() << "Equivalent RP, keeping schedule with better "
2193 "latency.\n");
2194 return false;
2195}
2196
2198 ArrayRef<MachineInstr *> MIOrder) {
2199 assert(static_cast<size_t>(std::distance(DAG.Regions[RegionIdx].first,
2200 DAG.Regions[RegionIdx].second)) ==
2201 MIOrder.size() &&
2202 "instruction number mismatch");
2203 if (MIOrder.empty())
2204 return;
2205
2206 LLVM_DEBUG(dbgs() << "Reverting scheduling for region " << RegionIdx << '\n');
2207
2208 // Reconstruct MI sequence by moving instructions in desired order before
2209 // the current region's start.
2210 MachineBasicBlock::iterator RegionEnd = DAG.Regions[RegionIdx].first;
2211 MachineBasicBlock *MBB = MIOrder.front()->getParent();
2212 for (MachineInstr *MI : MIOrder) {
2213 // Either move the next MI in order before the end of the region or move the
2214 // region end past the MI if it is at the correct position.
2215 MachineBasicBlock::iterator MII = MI->getIterator();
2216 if (MII != RegionEnd) {
2217 // Will subsequent splice move MI up past a non-debug instruction?
2218 bool NonDebugReordered =
2219 !MI->isDebugInstr() &&
2220 skipDebugInstructionsForward(RegionEnd, MII) != MII;
2221 MBB->splice(RegionEnd, MBB, MI);
2222 // Only update LiveIntervals information if non-debug instructions are
2223 // reordered. Otherwise debug instructions could cause code generation to
2224 // change.
2225 if (NonDebugReordered)
2226 DAG.LIS->handleMove(*MI, true);
2227 } else {
2228 // MI is already at the expected position. However, earlier splices in
2229 // this loop may have changed neighboring slot indices, so this MI's
2230 // slot index can become non-monotonic w.r.t. the physical MBB order.
2231 // Only re-seat when monotonicity is actually violated to avoid
2232 // unnecessary LiveInterval changes that could perturb scheduling.
2233 if (!MI->isDebugInstr()) {
2234 SlotIndex MIIdx = DAG.LIS->getInstructionIndex(*MI);
2235 SlotIndex PrevIdx = DAG.LIS->getSlotIndexes()->getIndexBefore(*MI);
2236 if (PrevIdx >= MIIdx)
2237 DAG.LIS->handleMove(*MI, true);
2238 }
2239 ++RegionEnd;
2240 }
2241 if (MI->isDebugInstr()) {
2242 LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
2243 continue;
2244 }
2245
2246 // Reset read-undef flags and update them later.
2248 DAG.ShouldTrackLaneMasks);
2249 LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
2250 }
2251
2252 // The region end doesn't change throughout scheduling since it itself is
2253 // outside the region (whether that is a MBB end or a terminator MI).
2254 assert(RegionEnd == DAG.Regions[RegionIdx].second && "region end mismatch");
2255 DAG.Regions[RegionIdx].first = MIOrder.front();
2256}
2257
2258/// Returns true if reaching def \p RD will be in AGPR form after the rewrite
2259/// and so needs no bridge copy: a candidate MFMA in \p RewriteSet, an
2260/// AV_MOV_*_IMM_PSEUDO, or a copy from a candidate src2 reg in \p CandSrc2Regs.
2261/// A non-candidate MFMA stays in VGPR form and still needs a bridge.
2263 MachineInstr *RD, const SmallPtrSetImpl<MachineInstr *> &RewriteSet,
2264 const DenseSet<Register> &CandSrc2Regs, const SIInstrInfo &TII) {
2265 if (TII.isMAI(*RD))
2266 return RewriteSet.contains(RD);
2267 if (RD->getOpcode() == AMDGPU::AV_MOV_B32_IMM_PSEUDO ||
2268 RD->getOpcode() == AMDGPU::AV_MOV_B64_IMM_PSEUDO)
2269 return true;
2270 if (RD->isCopy() && CandSrc2Regs.contains(RD->getOperand(1).getReg()))
2271 return true;
2272 return false;
2273}
2274
2275bool RewriteMFMAFormStage::hasUseRequiringVGPR(
2276 ArrayRef<SlotIndex> Src2ReachingDefs,
2277 const SmallPtrSetImpl<MachineInstr *> &RewriteSet) {
2278 for (SlotIndex RDIdx : Src2ReachingDefs) {
2279 const MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
2281 findReachingUses(RD, DAG.LIS, ReachingUses);
2282 for (const MachineOperand *UseMO : ReachingUses) {
2283 const MachineInstr *UseMI = UseMO->getParent();
2284 if (UseMI->isCopy())
2285 continue;
2286 if (TII->isMAI(*UseMI) && RewriteSet.contains(UseMI))
2287 continue;
2288 return true;
2289 }
2290 }
2291 return false;
2292}
2293
2294void RewriteMFMAFormStage::resetRewriteCandsToVGPR(
2295 ArrayRef<std::pair<MachineInstr *, unsigned>> RewriteCands) {
2296 for (auto [MI, OriginalOpcode] : RewriteCands) {
2297 assert(TII->isMAI(*MI));
2298 const TargetRegisterClass *ADefRC =
2299 DAG.MRI.getRegClass(MI->getOperand(0).getReg());
2300 const TargetRegisterClass *VDefRC = SRI->getEquivalentVGPRClass(ADefRC);
2301 DAG.MRI.setRegClass(MI->getOperand(0).getReg(), VDefRC);
2302 MI->setDesc(TII->get(OriginalOpcode));
2303
2304 MachineOperand *Src2 = TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
2305 if (!Src2->isReg())
2306 continue;
2307
2308 // Have to get src types separately since subregs may cause C and D
2309 // registers to be different types even though the actual operand is
2310 // the same size.
2311 const TargetRegisterClass *AUseRC = DAG.MRI.getRegClass(Src2->getReg());
2312 const TargetRegisterClass *VUseRC = SRI->getEquivalentVGPRClass(AUseRC);
2313 DAG.MRI.setRegClass(Src2->getReg(), VUseRC);
2314 }
2315}
2316
2317bool RewriteMFMAFormStage::isRewriteCandidate(MachineInstr *MI) const {
2318 if (!static_cast<const SIInstrInfo *>(DAG.TII)->isMAI(*MI))
2319 return false;
2320 if (AMDGPU::getAGPRFormOp(MI->getOpcode()) == -1)
2321 return false;
2322 // Reject candidates whose users force an unavoidable bridge copy.
2323 Register DstReg = MI->getOperand(0).getReg();
2324 for (const MachineInstr &UseMI : DAG.MRI.use_nodbg_instructions(DstReg)) {
2325 if (!TII->isMAI(UseMI) && !UseMI.isCopy())
2326 return false;
2327 }
2328 return true;
2329}
2330
2331bool RewriteMFMAFormStage::initHeuristics(
2332 std::vector<std::pair<MachineInstr *, unsigned>> &RewriteCands,
2333 DenseMap<MachineBasicBlock *, std::set<Register>> &CopyForUse,
2334 SmallPtrSetImpl<MachineInstr *> &CopyForDef) {
2335 bool Changed = false;
2336
2337 // Collect the candidate group, its members share AGPR-form operands
2338 // post-rewrite, so reaching defs feeding any member don't need bridge copy.
2339 SmallPtrSet<MachineInstr *, 16> RewriteSet;
2340 DenseSet<Register> CandSrc2Regs;
2341 for (MachineBasicBlock &MBB : MF) {
2342 for (MachineInstr &MI : MBB) {
2343 if (!isRewriteCandidate(&MI))
2344 continue;
2345 RewriteSet.insert(&MI);
2346 MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
2347 if (Src2 && Src2->isReg())
2348 CandSrc2Regs.insert(Src2->getReg());
2349 }
2350 }
2351
2352 // Prepare for the heuristics
2353 for (MachineBasicBlock &MBB : MF) {
2354 for (MachineInstr &MI : MBB) {
2355 if (!isRewriteCandidate(&MI))
2356 continue;
2357
2358 int ReplacementOp = AMDGPU::getAGPRFormOp(MI.getOpcode());
2359 assert(ReplacementOp != -1);
2360
2361 RewriteCands.push_back({&MI, MI.getOpcode()});
2362 MI.setDesc(TII->get(ReplacementOp));
2363
2364 MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
2365 if (Src2->isReg()) {
2366 SmallVector<SlotIndex, 8> Src2ReachingDefs;
2367 findReachingDefs(*Src2, DAG.LIS, Src2ReachingDefs);
2368
2369 // If src2 has a use that must remain VGPR, it cannot be reclassified to
2370 // AGPR.
2371 bool Src2NeedsVGPR = hasUseRequiringVGPR(Src2ReachingDefs, RewriteSet);
2372 Src2NeedsVGPRCache[&MI] = Src2NeedsVGPR;
2373
2374 for (SlotIndex RDIdx : Src2ReachingDefs) {
2375 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
2376 if (!Src2NeedsVGPR &&
2377 isReachingDefAGPRForm(RD, RewriteSet, CandSrc2Regs, *TII))
2378 continue;
2379 CopyForDef.insert(RD);
2380 }
2381 }
2382
2383 MachineOperand &Dst = MI.getOperand(0);
2384 SmallVector<MachineOperand *, 8> DstReachingUses;
2385
2386 findReachingUses(&MI, DAG.LIS, DstReachingUses);
2387
2388 for (MachineOperand *RUOp : DstReachingUses) {
2389 MachineInstr *UserMI = RUOp->getParent();
2390 // Group members read the AGPR result directly.
2391 if (TII->isMAI(*UserMI) && RewriteSet.contains(UserMI))
2392 continue;
2393
2394 // For any user of the result of the MFMA which is not an MFMA, we
2395 // insert a copy. For a given register, we will only insert one copy
2396 // per user block.
2397 CopyForUse[UserMI->getParent()].insert(RUOp->getReg());
2398
2399 if (TII->isMAI(*UserMI))
2400 continue;
2401
2402 SmallVector<SlotIndex, 8> DstUsesReachingDefs;
2403 findReachingDefs(*RUOp, DAG.LIS, DstUsesReachingDefs);
2404
2405 for (SlotIndex RDIndex : DstUsesReachingDefs) {
2406 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
2407 if (TII->isMAI(*RD))
2408 continue;
2409
2410 // For any definition of the user of the MFMA which is not an MFMA,
2411 // we insert a copy. We do this to transform all the reaching defs
2412 // of this use to AGPR. By doing this, we can insert a copy from
2413 // AGPR to VGPR at the user rather than after the MFMA.
2414 CopyForDef.insert(RD);
2415 }
2416 }
2417
2418 // Do the rewrite to allow for updated RP calculation.
2419 const TargetRegisterClass *VDefRC = DAG.MRI.getRegClass(Dst.getReg());
2420 const TargetRegisterClass *ADefRC = SRI->getEquivalentAGPRClass(VDefRC);
2421 DAG.MRI.setRegClass(Dst.getReg(), ADefRC);
2422 if (Src2->isReg()) {
2423 // Have to get src types separately since subregs may cause C and D
2424 // registers to be different types even though the actual operand is
2425 // the same size.
2426 const TargetRegisterClass *VUseRC = DAG.MRI.getRegClass(Src2->getReg());
2427 const TargetRegisterClass *AUseRC = SRI->getEquivalentAGPRClass(VUseRC);
2428 DAG.MRI.setRegClass(Src2->getReg(), AUseRC);
2429 }
2430 Changed = true;
2431 }
2432 }
2433
2434 return Changed;
2435}
2436
2437int64_t RewriteMFMAFormStage::getRewriteCost(
2438 ArrayRef<std::pair<MachineInstr *, unsigned>> RewriteCands,
2439 const DenseMap<MachineBasicBlock *, std::set<Register>> &CopyForUse,
2440 const SmallPtrSetImpl<MachineInstr *> &CopyForDef) {
2441 MachineBlockFrequencyInfo *MBFI = DAG.MBFI;
2442
2443 int64_t BestSpillCost = 0;
2444 int64_t Cost = 0;
2445 uint64_t EntryFreq = MBFI->getEntryFreq().getFrequency();
2446
2447 std::pair<unsigned, unsigned> MaxVectorRegs =
2448 ST.getMaxNumVectorRegs(MF.getFunction());
2449 unsigned ArchVGPRThreshold = MaxVectorRegs.first;
2450 unsigned AGPRThreshold = MaxVectorRegs.second;
2451 unsigned CombinedThreshold = ST.getMaxNumVGPRs(MF);
2452
2453 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++) {
2454 if (!RegionsWithExcessArchVGPR[Region])
2455 continue;
2456
2457 GCNRegPressure &PressureBefore = DAG.Pressure[Region];
2458 unsigned SpillCostBefore = PressureBefore.getVGPRSpills(
2459 MF, ArchVGPRThreshold, AGPRThreshold, CombinedThreshold);
2460
2461 // For the cases we care about (i.e. ArchVGPR usage is greater than the
2462 // addressable limit), rewriting alone should bring pressure to manageable
2463 // level. If we find any such region, then the rewrite is potentially
2464 // beneficial.
2465 GCNRegPressure PressureAfter = DAG.getRealRegPressure(Region);
2466 unsigned SpillCostAfter = PressureAfter.getVGPRSpills(
2467 MF, ArchVGPRThreshold, AGPRThreshold, CombinedThreshold);
2468
2469 uint64_t BlockFreq =
2470 MBFI->getBlockFreq(DAG.Regions[Region].first->getParent())
2471 .getFrequency();
2472
2473 bool RelativeFreqIsDenom = EntryFreq > BlockFreq;
2474 uint64_t RelativeFreq = EntryFreq && BlockFreq
2475 ? (RelativeFreqIsDenom ? EntryFreq / BlockFreq
2476 : BlockFreq / EntryFreq)
2477 : 1;
2478
2479 // This assumes perfect spilling / splitting -- using one spill / copy
2480 // instruction and one restoreFrom / copy for each excess register,
2481 int64_t SpillCost = ((int)SpillCostAfter - (int)SpillCostBefore) * 2;
2482
2483 // Also account for the block frequency.
2484 if (RelativeFreqIsDenom)
2485 SpillCost /= (int64_t)RelativeFreq;
2486 else
2487 SpillCost *= (int64_t)RelativeFreq;
2488
2489 // If we have increased spilling in any block, just bail.
2490 if (SpillCost > 0) {
2491 resetRewriteCandsToVGPR(RewriteCands);
2492 return SpillCost;
2493 }
2494
2495 if (SpillCost < BestSpillCost)
2496 BestSpillCost = SpillCost;
2497 }
2498
2499 // Set the cost to the largest decrease in spill cost in order to not double
2500 // count spill reductions.
2501 Cost = BestSpillCost;
2502 assert(Cost <= 0);
2503
2504 unsigned CopyCost = 0;
2505
2506 // For each CopyForDef, increase the cost by the register size while
2507 // accounting for block frequency.
2508 for (MachineInstr *DefMI : CopyForDef) {
2509 Register DefReg = DefMI->getOperand(0).getReg();
2510 uint64_t DefFreq =
2511 EntryFreq
2512 ? MBFI->getBlockFreq(DefMI->getParent()).getFrequency() / EntryFreq
2513 : 1;
2514
2515 const TargetRegisterClass *RC = DAG.MRI.getRegClass(DefReg);
2516 CopyCost += static_cast<unsigned>(RC->getCopyCost() * DefFreq);
2517 }
2518
2519 // Account for CopyForUse copies in each block that the register is used.
2520 for (auto &[UseBlock, UseRegs] : CopyForUse) {
2521 uint64_t UseFreq =
2522 EntryFreq ? MBFI->getBlockFreq(UseBlock).getFrequency() / EntryFreq : 1;
2523
2524 for (Register UseReg : UseRegs) {
2525 const TargetRegisterClass *RC = DAG.MRI.getRegClass(UseReg);
2526 CopyCost += static_cast<unsigned>(RC->getCopyCost() * UseFreq);
2527 }
2528 }
2529
2530 // Reset the classes that were changed to AGPR for better register bank
2531 // analysis. We must do rewriting after copy-insertion, as some defs of the
2532 // register may require VGPR. Additionally, if we bail out and don't perform
2533 // the rewrite then these need to be restored anyway.
2534 resetRewriteCandsToVGPR(RewriteCands);
2535
2536 return Cost + CopyCost;
2537}
2538
2539bool RewriteMFMAFormStage::rewrite(
2540 ArrayRef<std::pair<MachineInstr *, unsigned>> RewriteCands) {
2541 DenseMap<MachineInstr *, unsigned> FirstMIToRegion;
2542 DenseMap<MachineInstr *, unsigned> LastMIToRegion;
2543
2544 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++) {
2545 RegionBoundaries Entry = DAG.Regions[Region];
2546 if (Entry.first == Entry.second)
2547 continue;
2548
2549 FirstMIToRegion[&*Entry.first] = Region;
2550 if (Entry.second != Entry.first->getParent()->end())
2551 LastMIToRegion[&*Entry.second] = Region;
2552 }
2553
2554 // Rewrite the MFMAs to AGPR, and insert any copies as needed.
2555 // The general assumption of the algorithm (and the previous cost calculation)
2556 // is that it is better to insert the copies in the MBB of the def of the src2
2557 // operands, and in the MBB of the user of the dest operands. This is based on
2558 // the assumption that the MFMAs are likely to appear in loop bodies, while
2559 // the src2 and dest operands are live-in / live-out of the loop. Due to this
2560 // design, the algorithm for finding copy insertion points is more
2561 // complicated.
2562 //
2563 // There are three main cases to handle: 1. the reaching defs of the src2
2564 // operands, 2. the reaching uses of the dst operands, and 3. the reaching
2565 // defs of the reaching uses of the dst operand.
2566 //
2567 // In the first case, we simply insert copies after each of the reaching
2568 // definitions. In the second case, we collect all the uses of a given dest
2569 // and organize them by MBB. Then, we insert 1 copy for each MBB before the
2570 // earliest use. Since the use may have multiple reaching defs, and since we
2571 // want to replace the register it is using with the result of the copy, we
2572 // must handle case 3. In the third case, we simply insert a copy after each
2573 // of the reaching defs to connect to the copy of the reaching uses of the dst
2574 // reg. This allows us to avoid inserting copies next to the MFMAs.
2575 //
2576 // While inserting the copies, we maintain a map of operands which will use
2577 // different regs (i.e. the result of the copies). For example, a case 1 src2
2578 // operand will use the register result of the copies after the reaching defs,
2579 // as opposed to the original register. Now that we have completed our copy
2580 // analysis and placement, we can bulk update the registers. We do this
2581 // separately as to avoid complicating the reachingDef and reachingUse
2582 // queries.
2583 //
2584 // While inserting the copies, we also maintain a list or registers which we
2585 // will want to reclassify as AGPR. After doing the copy insertion and the
2586 // register replacement, we can finally do the reclassification. This uses the
2587 // redef map, as the registers we are interested in reclassifying may be
2588 // replaced by the result of a copy. We must do this after the copy analysis
2589 // and placement as we must have an accurate redef map -- otherwise we may end
2590 // up creating illegal instructions.
2591
2592 // The original registers of the MFMA that need to be reclassified as AGPR.
2593 DenseSet<Register> RewriteRegs;
2594 // The map of an original register in the MFMA to a new register (result of a
2595 // copy) that it should be replaced with.
2596 DenseMap<Register, Register> RedefMap;
2597 // The map of the original MFMA registers to the relevant MFMA operands.
2598 DenseMap<Register, DenseSet<MachineOperand *>> ReplaceMap;
2599 // The map of reaching defs for a given register -- to avoid duplicate copies.
2600 DenseMap<Register, SmallPtrSet<MachineInstr *, 8>> ReachingDefCopyMap;
2601 // The map of reaching uses for a given register by basic block -- to avoid
2602 // duplicate copies and to calculate per MBB insert pts.
2603 DenseMap<unsigned, DenseMap<Register, SmallPtrSet<MachineOperand *, 8>>>
2604 ReachingUseTracker;
2605
2606 // Collect the candidate group; its members share AGPR-form operands
2607 // post-rewrite, so reaching defs feeding any member need no bridge copy.
2608 SmallPtrSet<MachineInstr *, 16> RewriteCandsSet;
2609 DenseSet<Register> RewriteSrc2Regs;
2610 for (auto &[MI, OriginalOpcode] : RewriteCands) {
2611 RewriteCandsSet.insert(MI);
2612 MachineOperand *Src2 = TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
2613 if (Src2 && Src2->isReg())
2614 RewriteSrc2Regs.insert(Src2->getReg());
2615 }
2616
2617 for (auto &[MI, OriginalOpcode] : RewriteCands) {
2618 int ReplacementOp = AMDGPU::getAGPRFormOp(MI->getOpcode());
2619 if (ReplacementOp == -1)
2620 continue;
2621 MI->setDesc(TII->get(ReplacementOp));
2622
2623 // Case 1: insert copies for the reaching defs of the Src2Reg.
2624 MachineOperand *Src2 = TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
2625 if (Src2->isReg()) {
2626 Register Src2Reg = Src2->getReg();
2627 if (!Src2Reg.isVirtual())
2628 return false;
2629
2630 Register MappedReg = Src2->getReg();
2631 SmallVector<SlotIndex, 8> Src2ReachingDefs;
2632 findReachingDefs(*Src2, DAG.LIS, Src2ReachingDefs);
2633 SmallSetVector<MachineInstr *, 8> Src2DefsReplace;
2634
2635 // If src2 has a use that must remain VGPR, it cannot be reclassified to
2636 // AGPR.
2637 bool Src2NeedsVGPR = Src2NeedsVGPRCache.lookup(MI);
2638
2639 for (SlotIndex RDIndex : Src2ReachingDefs) {
2640 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
2641 if (!Src2NeedsVGPR &&
2642 isReachingDefAGPRForm(RD, RewriteCandsSet, RewriteSrc2Regs, *TII))
2643 continue;
2644
2645 Src2DefsReplace.insert(RD);
2646 }
2647
2648 if (!Src2DefsReplace.empty()) {
2649 auto RI = RedefMap.find(Src2Reg);
2650 if (RI != RedefMap.end()) {
2651 MappedReg = RI->second;
2652 } else {
2653 assert(!ReachingDefCopyMap.contains(Src2Reg));
2654 const TargetRegisterClass *Src2RC = DAG.MRI.getRegClass(Src2Reg);
2655 const TargetRegisterClass *VGPRRC =
2656 SRI->getEquivalentVGPRClass(Src2RC);
2657
2658 // Track the mapping of the original register to the new register.
2659 MappedReg = DAG.MRI.createVirtualRegister(VGPRRC);
2660 RedefMap[Src2Reg] = MappedReg;
2661 }
2662
2663 // If none exists, create a copy from this reaching def.
2664 // We may have inserted a copy already in an earlier iteration.
2665 for (MachineInstr *RD : Src2DefsReplace) {
2666 // Do not create redundant copies.
2667 if (ReachingDefCopyMap[Src2Reg].insert(RD).second) {
2668 MachineInstrBuilder VGPRCopy =
2669 BuildMI(*RD->getParent(), std::next(RD->getIterator()),
2670 RD->getDebugLoc(), TII->get(TargetOpcode::COPY))
2671 .addDef(MappedReg, {}, 0)
2672 .addUse(Src2Reg, {}, 0);
2673 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2674
2675 // If this reaching def was the last MI in the region, update the
2676 // region boundaries.
2677 if (LastMIToRegion.contains(RD)) {
2678 unsigned UpdateRegion = LastMIToRegion[RD];
2679 DAG.Regions[UpdateRegion].second = VGPRCopy;
2680 LastMIToRegion.erase(RD);
2681 }
2682 }
2683 }
2684 }
2685
2686 // Track the register for reclassification
2687 RewriteRegs.insert(Src2Reg);
2688
2689 // Always insert the operand for replacement. If this corresponds with a
2690 // chain of tied-def we may not see the VGPR requirement until later.
2691 ReplaceMap[Src2Reg].insert(Src2);
2692 }
2693
2694 // Case 2 and Case 3: insert copies before the reaching uses of the dsts,
2695 // and after the reaching defs of the reaching uses of the dsts.
2696
2697 MachineOperand *Dst = &MI->getOperand(0);
2698 Register DstReg = Dst->getReg();
2699 if (!DstReg.isVirtual())
2700 return false;
2701
2702 Register MappedReg = DstReg;
2703 SmallVector<MachineOperand *, 8> DstReachingUses;
2704
2705 SmallVector<MachineOperand *, 8> DstReachingUseCopies;
2706 SmallVector<MachineInstr *, 8> DstUseDefsReplace;
2707
2708 findReachingUses(MI, DAG.LIS, DstReachingUses);
2709
2710 for (MachineOperand *RUOp : DstReachingUses) {
2711 MachineInstr *UserMI = RUOp->getParent();
2712 // Group members read the AGPR result directly.
2713 if (TII->isMAI(*UserMI) && RewriteCandsSet.contains(UserMI))
2714 continue;
2715
2716 // If there is a non mai reaching use, then we need a copy.
2717 if (find(DstReachingUseCopies, RUOp) == DstReachingUseCopies.end())
2718 DstReachingUseCopies.push_back(RUOp);
2719
2720 // Non-rewritten MAI: its defs aren't being reclassified.
2721 if (TII->isMAI(*UserMI))
2722 continue;
2723
2724 SmallVector<SlotIndex, 8> DstUsesReachingDefs;
2725 findReachingDefs(*RUOp, DAG.LIS, DstUsesReachingDefs);
2726
2727 for (SlotIndex RDIndex : DstUsesReachingDefs) {
2728 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
2729 if (TII->isMAI(*RD))
2730 continue;
2731
2732 // If there is a non mai reaching def of this reaching use, then we will
2733 // need a copy.
2734 if (find(DstUseDefsReplace, RD) == DstUseDefsReplace.end())
2735 DstUseDefsReplace.push_back(RD);
2736 }
2737 }
2738
2739 if (!DstUseDefsReplace.empty()) {
2740 auto RI = RedefMap.find(DstReg);
2741 if (RI != RedefMap.end()) {
2742 MappedReg = RI->second;
2743 } else {
2744 assert(!ReachingDefCopyMap.contains(DstReg));
2745 const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(DstReg);
2746 const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC);
2747
2748 // Track the mapping of the original register to the new register.
2749 MappedReg = DAG.MRI.createVirtualRegister(VGPRRC);
2750 RedefMap[DstReg] = MappedReg;
2751 }
2752
2753 // If none exists, create a copy from this reaching def.
2754 // We may have inserted a copy already in an earlier iteration.
2755 for (MachineInstr *RD : DstUseDefsReplace) {
2756 // Do not create reundant copies.
2757 if (ReachingDefCopyMap[DstReg].insert(RD).second) {
2758 MachineInstrBuilder VGPRCopy =
2759 BuildMI(*RD->getParent(), std::next(RD->getIterator()),
2760 RD->getDebugLoc(), TII->get(TargetOpcode::COPY))
2761 .addDef(MappedReg, {}, 0)
2762 .addUse(DstReg, {}, 0);
2763 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2764
2765 // If this reaching def was the last MI in the region, update the
2766 // region boundaries.
2767 auto LMI = LastMIToRegion.find(RD);
2768 if (LMI != LastMIToRegion.end()) {
2769 unsigned UpdateRegion = LMI->second;
2770 DAG.Regions[UpdateRegion].second = VGPRCopy;
2771 LastMIToRegion.erase(RD);
2772 }
2773 }
2774 }
2775 }
2776
2777 DenseSet<MachineOperand *> &DstRegSet = ReplaceMap[DstReg];
2778 // One AGPR→VGPR copy per dst register, shared by all same-block uses.
2779 Register SameBlockCopyReg;
2780 MachineInstr *EarliestSameBlockUse = nullptr;
2781 for (MachineOperand *RU : DstReachingUseCopies) {
2782 MachineBasicBlock *RUBlock = RU->getParent()->getParent();
2783 // Just keep track of the reaching use of this register by block. After we
2784 // have scanned all the MFMAs we can find optimal insert pts.
2785 if (RUBlock != MI->getParent()) {
2786 ReachingUseTracker[RUBlock->getNumber()][DstReg].insert(RU);
2787 continue;
2788 }
2789
2790 // Lazily create the copy register on first same-block use.
2791 if (!SameBlockCopyReg.isValid()) {
2792 const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(DstReg);
2793 const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC);
2794 SameBlockCopyReg = DAG.MRI.createVirtualRegister(VGPRRC);
2795 }
2796
2797 // Track the earliest use for copy insertion point.
2798 MachineInstr *UseInst = RU->getParent();
2799 if (!EarliestSameBlockUse ||
2801 DAG.LIS->getInstructionIndex(*UseInst),
2802 DAG.LIS->getInstructionIndex(*EarliestSameBlockUse)))
2803 EarliestSameBlockUse = UseInst;
2804 RU->setReg(SameBlockCopyReg);
2805 }
2806
2807 // Insert the copy before the earliest same-block use.
2808 if (SameBlockCopyReg.isValid()) {
2809 MachineInstrBuilder VGPRCopy =
2810 BuildMI(*EarliestSameBlockUse->getParent(),
2811 EarliestSameBlockUse->getIterator(), DebugLoc(),
2812 TII->get(TargetOpcode::COPY), SameBlockCopyReg)
2813 .addUse(DstReg, {}, 0);
2814 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2815 DstRegSet.insert(&VGPRCopy->getOperand(1));
2816 }
2817
2818 // Track the register for reclassification
2819 RewriteRegs.insert(DstReg);
2820
2821 // Insert the dst operand for replacement. If this dst is in a chain of
2822 // tied-def MFMAs, and the first src2 needs to be replaced with a new reg,
2823 // all the correspond operands need to be replaced.
2824 DstRegSet.insert(Dst);
2825 }
2826
2827 // Handle the copies for dst uses.
2828 using RUBType =
2829 std::pair<unsigned, DenseMap<Register, SmallPtrSet<MachineOperand *, 8>>>;
2830 for (RUBType RUBlockEntry : ReachingUseTracker) {
2831 using RUDType = std::pair<Register, SmallPtrSet<MachineOperand *, 8>>;
2832 for (RUDType RUDst : RUBlockEntry.second) {
2833 MachineOperand *OpBegin = *RUDst.second.begin();
2834 SlotIndex InstPt = DAG.LIS->getInstructionIndex(*OpBegin->getParent());
2835
2836 // Find the earliest use in this block.
2837 for (MachineOperand *User : RUDst.second) {
2838 SlotIndex NewInstPt = DAG.LIS->getInstructionIndex(*User->getParent());
2839 if (SlotIndex::isEarlierInstr(NewInstPt, InstPt))
2840 InstPt = NewInstPt;
2841 }
2842
2843 const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(RUDst.first);
2844 const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC);
2845 Register NewUseReg = DAG.MRI.createVirtualRegister(VGPRRC);
2846 MachineInstr *UseInst = DAG.LIS->getInstructionFromIndex(InstPt);
2847
2848 MachineInstrBuilder VGPRCopy =
2849 BuildMI(*UseInst->getParent(), UseInst->getIterator(),
2850 UseInst->getDebugLoc(), TII->get(TargetOpcode::COPY))
2851 .addDef(NewUseReg, {}, 0)
2852 .addUse(RUDst.first, {}, 0);
2853 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2854
2855 // If this UseInst was the first MI in the region, update the region
2856 // boundaries.
2857 auto FI = FirstMIToRegion.find(UseInst);
2858 if (FI != FirstMIToRegion.end()) {
2859 unsigned UpdateRegion = FI->second;
2860 DAG.Regions[UpdateRegion].first = VGPRCopy;
2861 FirstMIToRegion.erase(UseInst);
2862 }
2863
2864 // Replace the operand for all users.
2865 for (MachineOperand *User : RUDst.second) {
2866 User->setReg(NewUseReg);
2867 }
2868
2869 // Track the copy source operand for replacement.
2870 ReplaceMap[RUDst.first].insert(&VGPRCopy->getOperand(1));
2871 }
2872 }
2873
2874 // We may have needed to insert copies after the reaching defs of the MFMAs.
2875 // Replace the original register with the result of the copy for all relevant
2876 // operands.
2877 for (std::pair<Register, Register> NewDef : RedefMap) {
2878 Register OldReg = NewDef.first;
2879 Register NewReg = NewDef.second;
2880
2881 // Replace the register for any associated operand in the MFMA chain.
2882 for (MachineOperand *ReplaceOp : ReplaceMap[OldReg])
2883 ReplaceOp->setReg(NewReg);
2884 }
2885
2886 // Finally, do the reclassification of the MFMA registers.
2887 for (Register RewriteReg : RewriteRegs) {
2888 Register RegToRewrite = RewriteReg;
2889
2890 // Be sure to update the replacement register and not the original.
2891 auto RI = RedefMap.find(RewriteReg);
2892 if (RI != RedefMap.end())
2893 RegToRewrite = RI->second;
2894
2895 const TargetRegisterClass *CurrRC = DAG.MRI.getRegClass(RegToRewrite);
2896 const TargetRegisterClass *AGPRRC = SRI->getEquivalentAGPRClass(CurrRC);
2897
2898 DAG.MRI.setRegClass(RegToRewrite, AGPRRC);
2899 }
2900
2901 // Bulk update the LIS.
2902 DAG.LIS->reanalyze(DAG.MF);
2903 // Liveins may have been modified for cross RC copies
2904 RegionPressureMap LiveInUpdater(&DAG, false);
2905 LiveInUpdater.buildLiveRegMap();
2906
2907 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++)
2908 DAG.LiveIns[Region] = LiveInUpdater.getLiveRegsForRegionIdx(Region);
2909
2910 DAG.Pressure[RegionIdx] = DAG.getRealRegPressure(RegionIdx);
2911
2912 return true;
2913}
2914
2915unsigned PreRARematStage::getStageTargetOccupancy() const {
2916 return TargetOcc ? *TargetOcc : MFI.getMinWavesPerEU();
2917}
2918
2920 // We consider that reducing spilling is always beneficial so we never
2921 // rollback rematerializations or revert scheduling in such cases.
2922 if (!TargetOcc)
2923 return;
2924
2925 // When increasing occupancy, it is possible that re-scheduling is not able to
2926 // achieve the target occupancy in all regions, in which case re-scheduling in
2927 // all regions should be reverted.
2928 if (DAG.MinOccupancy >= *TargetOcc)
2929 return;
2930
2931 // Revert re-scheduling in all affected regions.
2932 for (const auto &[RegionIdx, OrigMIOrder, MaxPressure] : RegionReverts) {
2933 LLVM_DEBUG(dbgs() << "Reverting re-scheduling in region " << RegionIdx
2934 << '\n');
2935 DAG.Pressure[RegionIdx] = MaxPressure;
2936 modifyRegionSchedule(RegionIdx, OrigMIOrder);
2937 }
2938
2939 // It is possible that re-scheduling lowers occupancy over the one achieved
2940 // just through rematerializations, in which case we revert re-scheduling in
2941 // all regions but do not roll back rematerializations.
2942 if (AchievedOcc >= *TargetOcc) {
2943 DAG.setTargetOccupancy(AchievedOcc);
2944 return;
2945 }
2946
2947 // Reset the target occupancy to what it was pre-rematerialization.
2948 DAG.setTargetOccupancy(*TargetOcc - 1);
2949 Strategy->rollbackRecordedRemats();
2950 for (unsigned RegionIdx : RescheduleRegions.set_bits()) {
2951 DAG.RegionLiveOuts.getLiveRegsForRegionIdx(RegionIdx) = LiveOuts[RegionIdx];
2952 DAG.Pressure[RegionIdx] = DAG.getRealRegPressure(RegionIdx);
2953 }
2954
2955#ifdef EXPENSIVE_CHECKS
2956 // In particular, we want to check for coherent MI/slot order in regions in
2957 // which reverts and/or rollbacks may have happened.
2958 MF.verify();
2959#endif
2960
2962}
2963
2964void GCNScheduleDAGMILive::setTargetOccupancy(unsigned TargetOccupancy) {
2965 MinOccupancy = TargetOccupancy;
2966 if (MFI.getOccupancy() < TargetOccupancy)
2967 MFI.increaseOccupancy(MF, MinOccupancy);
2968 else
2969 MFI.limitOccupancy(MinOccupancy);
2970}
2971
2973 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG->TII);
2974 return any_of(*DAG, [SII](MachineBasicBlock::iterator MI) {
2975 return SII->isIGLPMutationOnly(MI->getOpcode());
2976 });
2977}
2978
2980 MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S,
2981 bool RemoveKillFlags)
2983
2985 HasIGLPInstrs = hasIGLPInstrs(this);
2986 if (HasIGLPInstrs) {
2987 SavedMutations.clear();
2988 SavedMutations.swap(Mutations);
2990 }
2991
2993}
2994
2996 if (HasIGLPInstrs)
2997 SavedMutations.swap(Mutations);
2998
3000}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static SUnit * pickOnlyChoice(SchedBoundary &Zone)
uint64_t uint64_t
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the GCNRegPressure class, which tracks registry pressure by bookkeeping number of S...
Rematerialization strategy, based on the target-independent rematerializer.
static MachineInstr * getLastMIForRegion(MachineBasicBlock::iterator RegionBegin, MachineBasicBlock::iterator RegionEnd)
static void printScheduleModel(std::set< std::pair< MachineInstr *, unsigned >, EarlierIssuingCycle > &ReadyCycles)
static bool isReachingDefAGPRForm(MachineInstr *RD, const SmallPtrSetImpl< MachineInstr * > &RewriteSet, const DenseSet< Register > &CandSrc2Regs, const SIInstrInfo &TII)
Returns true if reaching def RD will be in AGPR form after the rewrite and so needs no bridge copy: a...
static bool hasIGLPInstrs(ScheduleDAGInstrs *DAG)
static void getRegisterPressures(bool AtTop, const RegPressureTracker &RPTracker, SUnit *SU, std::vector< unsigned > &Pressure, std::vector< unsigned > &MaxPressure)
Fills Pressure and MaxPressure, indexed by pressure set, with the generic RegPressureTracker's pressu...
static bool shouldCheckPending(unsigned PendingQueueLimit, SchedBoundary &Zone, const TargetSchedModel *SchedModel)
static bool canUsePressureDiffs(const SUnit &SU)
Checks whether SU can use the cached DAG pressure diffs to compute the current register pressure.
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
static constexpr std::pair< StringLiteral, StringLiteral > ReplaceMap[]
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
if(PassOpts->AAPipeline)
MachineRegisterInfo & MRI
This file contains some templates that are useful if you are working with the STL at all.
#define LLVM_DEBUG(...)
Definition Debug.h:119
const AMDGPUOptions & getCLOpts() const
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
bool shouldRevertScheduling(unsigned WavesAfter) override
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Downward RP tracker that relies on program order to advance down the instruction stream.
GCNMaxILPSchedStrategy(const MachineSchedContext *C)
bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const override
Apply a set of heuristics to a new candidate.
bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const override
GCNMaxMemoryClauseSchedStrategy tries best to clause memory instructions as much as possible.
GCNMaxMemoryClauseSchedStrategy(const MachineSchedContext *C)
GCNMaxOccupancySchedStrategy(const MachineSchedContext *C, bool IsLegacyScheduler=false)
void finalizeSchedule() override
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
void schedule() override
Orders nodes according to selected style.
GCNPostScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S, bool RemoveKillFlags)
Models a register pressure target, allowing to evaluate and track register savings against that targe...
GCNRegPressure getPressure() const
void reset(const MachineInstr &MI, bool After)
Resets tracker before or After the provided MI, which can be a debug instruction.
GCNSchedStrategy & S
GCNRegPressure PressureBefore
bool isRegionWithExcessRP() const
void modifyRegionSchedule(unsigned RegionIdx, ArrayRef< MachineInstr * > MIOrder)
Sets the schedule of region RegionIdx to MIOrder.
bool mayCauseSpilling(unsigned WavesAfter)
ScheduleMetrics getScheduleMetrics(const std::vector< SUnit > &InputSchedule)
GCNScheduleDAGMILive & DAG
const GCNSchedStageID StageID
std::vector< MachineInstr * > Unsched
GCNRegPressure PressureAfter
bool shouldRevertInitialSchedule(unsigned WavesAfter)
MachineFunction & MF
virtual void finalizeGCNRegion()
SIMachineFunctionInfo & MFI
unsigned computeSUnitReadyCycle(const SUnit &SU, unsigned CurrCycle, DenseMap< unsigned, unsigned > &ReadyCycles, const TargetSchedModel &SM)
virtual void finalizeGCNSchedStage()
virtual bool initGCNSchedStage()
virtual bool shouldRevertScheduling(unsigned WavesAfter)
std::vector< std::unique_ptr< ScheduleDAGMutation > > SavedMutations
GCNSchedStage(GCNSchedStageID StageID, GCNScheduleDAGMILive &DAG)
MachineBasicBlock * CurrentMBB
const GCNSubtarget & ST
This is a minimal scheduler strategy.
GCNSchedStrategy(const MachineSchedContext *C)
SmallVector< GCNSchedStageID, 4 > SchedStages
std::vector< unsigned > MaxPressure
SUnit * pickNodeBidirectional(bool &IsTopNode, bool &PickedPending)
GCNSchedStageID getCurrentStage()
bool tryPendingCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const
Evaluates instructions in the pending queue using a subset of scheduling heuristics.
SmallVectorImpl< GCNSchedStageID >::iterator CurrentStage
std::pair< unsigned, unsigned > getBankedPressure(const GCNRegPressure &RP) const
void schedNode(SUnit *SU, bool IsTopNode) override
Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an instruction and updated scheduled/rem...
GCNRegPressure getGCNTrackerPressure(bool AtTop, SUnit *SU, const SIRegisterInfo *SRI) const
unsigned AGPRBankLimit
Capacity of the AGPR bank, captured before AGPRExcessLimit is cut down by ErrorMargin and VGPRLimitBi...
unsigned ArchVGPRBankLimit
Capacity of the ArchVGPR bank, captured before VGPRExcessLimit is cut down by ErrorMargin,...
std::optional< bool > GCNTrackersOverride
std::vector< unsigned > Pressure
void initialize(ScheduleDAGMI *DAG) override
Initialize the strategy after building the DAG for a new region.
GCNUpwardRPTracker UpwardTracker
void printCandidateDecision(const SchedCandidate &Current, const SchedCandidate &Preferred)
void pickNodeFromQueue(SchedBoundary &Zone, const CandPolicy &ZonePolicy, const RegPressureTracker &RPTracker, SchedCandidate &Cand, bool &IsPending, bool IsBottomUp)
GCNManualDownwardRPTracker DownwardTracker
GCNUpwardRPTracker & getUpwardTracker()
const AMDGPUOptions & CLOpts
void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, const SIRegisterInfo *SRI, unsigned SGPRPressure, unsigned VGPRPressure, unsigned AGPRPressure, bool IsBottomUp)
GCNDownwardRPTrackerBase & getDownwardTracker()
SUnit * pickNode(bool &IsTopNode) override
Pick the next node to schedule, or return NULL.
unsigned UnifiedVGPRExcessLimit
Budget for the combined ArchVGPR + AGPR file, or zero on targets without one.
void finalizeSchedule() override
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
void schedule() override
Orders nodes according to selected style.
GCNScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S)
void recede(const MachineInstr &MI)
Move to the state of RP just before the MI.
void reset(const MachineInstr &MI)
Resets tracker to the point just after MI (in program order), which can be a debug instruction.
void traceCandidate(const SchedCandidate &Cand)
LLVM_ABI void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone, SchedBoundary *OtherZone)
Set the CandPolicy given a scheduling zone given the current resources and latencies inside and outsi...
MachineSchedPolicy RegionPolicy
const TargetSchedModel * SchedModel
const MachineSchedContext * Context
const TargetRegisterInfo * TRI
SchedCandidate BotCand
Candidate last picked from Bot boundary.
SchedCandidate TopCand
Candidate last picked from Top boundary.
virtual bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const
Apply a set of heuristics to a new candidate.
ScheduleDAGMILive * DAG
void initialize(ScheduleDAGMI *dag) override
Initialize the strategy after building the DAG for a new region.
void schedNode(SUnit *SU, bool IsTopNode) override
Update the scheduler's state after scheduling a node.
GenericScheduler(const MachineSchedContext *C)
bool shouldRevertScheduling(unsigned WavesAfter) override
LiveInterval - This class represents the liveness of a register, or stack slot.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
LLVM_ABI void dump() const
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
uint8_t getCopyCost() const
getCopyCost - Return the cost of copying a value between two registers in this class.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI BlockFrequency getEntryFreq() const
Divide a block's BlockFrequency::getFrequency() value by this value to obtain the entry block - relat...
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isCopy() const
const MachineBasicBlock * getParent() const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
bool shouldRevertScheduling(unsigned WavesAfter) override
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
bool shouldRevertScheduling(unsigned WavesAfter) override
bool shouldRevertScheduling(unsigned WavesAfter) override
void finalizeGCNRegion() override
bool initGCNSchedStage() override
Capture a change in pressure for a single pressure set.
unsigned getPSet() const
Helpers for implementing custom MachineSchedStrategy classes.
unsigned size() const
Track the current register pressure at some position in the instruction stream, and remember the high...
RegisterPressure & getPressure()
Get the resulting register pressure over the traversed region.
LLVM_ABI void getDownwardPressure(const MachineInstr *MI, std::vector< unsigned > &PressureResult, std::vector< unsigned > &MaxPressureResult)
Get the pressure of each PSet after traversing this instruction top-down.
const std::vector< unsigned > & getRegSetPressureAtPos() const
Get the register set pressure at the current position, which may be less than the pressure across the...
LLVM_ABI void getUpwardPressure(const MachineInstr *MI, std::vector< unsigned > &PressureResult, std::vector< unsigned > &MaxPressureResult)
Get the pressure of each PSet after traversing this instruction bottom-up.
static LLVM_ABI void restoreLivenessFlags(MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, LiveIntervals &LIS, bool TrackLaneMasks=true, ArrayRef< Register > OnlyRegs={})
Clear potentially-stale read-undef flags on the defs of MI, then recompute them from LIS.
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
bool isIGLPMutationOnly(unsigned Opcode) const
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
Scheduling unit. This is a node in the scheduling DAG.
bool isInstr() const
Returns true if this SUnit refers to a machine instruction as opposed to an SDNode.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
unsigned short Latency
Node latency.
bool isScheduled
True once scheduled.
unsigned ParentClusterIdx
The parent cluster id.
unsigned BotReadyCycle
Cycle relative to end when node is ready.
bool isBottomReady() const
bool isTopReady() const
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Each Scheduling boundary is associated with ready queues.
LLVM_ABI void releasePending()
Release pending ready nodes in to the available queue.
LLVM_ABI unsigned getLatencyStallCycles(SUnit *SU)
Get the difference between the given SUnit's ready time and the current cycle.
LLVM_ABI SUnit * pickOnlyChoice()
Call this before applying any other heuristics to the Available queue.
LLVM_ABI void bumpCycle(unsigned NextCycle)
Move the boundary of scheduled code by one cycle.
unsigned getCurrMOps() const
Micro-ops issued in the current cycle.
unsigned getCurrCycle() const
Number of cycles to issue the instructions scheduled in this zone.
LLVM_ABI bool checkHazard(SUnit *SU)
Does this SU have a hazard within the current instruction group.
A ScheduleDAG for scheduling lists of MachineInstr.
bool ScheduleSingleMIRegions
True if regions with a single MI should be scheduled.
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
virtual void finalizeSchedule()
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
const MachineLoopInfo * MLI
bool RemoveKillFlags
True if the DAG builder should remove kill flags (in preparation for rescheduling).
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
ScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S)
RegPressureTracker RPTracker
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void exitRegion() override
Called when the scheduler has finished scheduling the current region.
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
ScheduleDAGMI(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S, bool RemoveKillFlags)
std::vector< std::unique_ptr< ScheduleDAGMutation > > Mutations
Ordered list of DAG postprocessing steps.
MachineRegisterInfo & MRI
Virtual/real register map.
const TargetInstrInfo * TII
Target instruction information.
MachineFunction & MF
Machine function.
static const unsigned ScaleFactor
unsigned getMetric() const
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Returns the first index in the given basic block.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model.
unsigned getMicroOpBufferSize() const
Number of micro-ops that may be buffered for OOO execution.
bool shouldRevertScheduling(unsigned WavesAfter) override
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getAddressableNumVGPRs(const MCSubtargetInfo &STI, unsigned DynamicVGPRBlockSize)
unsigned getAllocatedNumVGPRBlocks(const MCSubtargetInfo &STI, unsigned NumVGPRs, unsigned DynamicVGPRBlockSize, std::optional< bool > EnableWavefrontSize32)
unsigned getVGPRAllocGranule(const MCSubtargetInfo &STI, unsigned DynamicVGPRBlockSize, std::optional< bool > EnableWavefrontSize32)
LLVM_READONLY int32_t getAGPRFormOp(uint32_t Opcode)
@ Entry
Definition COFF.h:862
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI int biasPhysReg(const SUnit *SU, bool isTop, bool BiasPRegsExtra=false)
Minimize physical register live ranges.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI unsigned getWeakLeft(const SUnit *SU, bool isTop)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
GCNRegPressure getRegPressure(const MachineRegisterInfo &MRI, Range &&LiveRegs)
LLVM_ABI bool shouldVerifyScheduling(const MachineFunction &MF)
Returns whether -verify-misched is set.
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
std::pair< MachineBasicBlock::iterator, MachineBasicBlock::iterator > RegionBoundaries
A region's boundaries i.e.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
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:1762
LLVM_ABI bool tryPressure(const PressureChange &TryP, const PressureChange &CandP, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason, const TargetRegisterInfo *TRI, const MachineFunction &MF)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
cl::opt< unsigned, false, VGPRThresholdParser > VGPRThresholdPercentOpt
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
iterator_range< ConstMIBundleOperands > const_mi_bundle_ops(const MachineInstr &MI)
LLVM_ABI bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IterT skipDebugInstructionsBackward(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool isTheSameCluster(unsigned A, unsigned B)
Return whether the input cluster ID's are the same and valid.
DWARFExpression::Operation Op
LLVM_ABI bool tryGreater(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
DenseMap< MachineInstr *, GCNRPTracker::LiveRegSet > getLiveRegMap(Range &&R, bool After, LiveIntervals &LIS)
creates a map MachineInstr -> LiveRegSet R - range of iterators on instructions After - upon entry or...
GCNRPTracker::LiveRegSet getLiveRegsBefore(const MachineInstr &MI, const LiveIntervals &LIS)
LLVM_ABI bool tryLess(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
Return true if this heuristic determines order.
LLVM_ABI void dumpMaxRegPressure(MachineFunction &MF, GCNRegPressure::RegKind Kind, LiveIntervals &LIS, const MachineLoopInfo *MLI)
unsigned estimateGreedyVGPRPressure(MachineBasicBlock::const_iterator RegionBegin, MachineBasicBlock::const_iterator RegionEnd, const GCNRPTracker::LiveRegSet &LiveIns, const LiveIntervals &LIS, const MachineRegisterInfo &MRI, const SIRegisterInfo &TRI)
Estimate VGPR pressure using greedy, non-splitting register allocation simulation,...
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
bool operator()(std::pair< MachineInstr *, unsigned > A, std::pair< MachineInstr *, unsigned > B) const
static unsigned getBankedUnifiedVGPRNum(unsigned NumArchVGPRs, unsigned NumAGPRs)
Returns the aggregated VGPR pressure for NumArchVGPRs ArchVGPRs and NumAGPRs AGPRs,...
unsigned getSGPRNum() const
static unsigned getUnifiedVGPRNum(unsigned NumArchVGPRs, unsigned NumAGPRs, unsigned NumAVGPRs)
Returns the aggregated VGPR pressure, assuming NumArchVGPRs ArchVGPRs NumAGPRs AGPRS,...
Policy for scheduling the next instruction in the candidate's zone.
Store the state used by GenericScheduler heuristics, required for the lifetime of one invocation of p...
void reset(const CandPolicy &NewPolicy)
LLVM_ABI void initResourceDelta(const ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
Status of an instruction's critical resource consumption.
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value)