1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MachineScheduler.h"
16 #include "llvm/ADT/PriorityQueue.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegisterClassInfo.h"
24 #include "llvm/CodeGen/ScheduleDFS.h"
25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetInstrInfo.h"
36 #define DEBUG_TYPE "misched"
39 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
40 cl::desc("Force top-down list scheduling"));
41 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
42 cl::desc("Force bottom-up list scheduling"));
46 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
47 cl::desc("Pop up a window to show MISched dags after they are processed"));
49 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
50 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
52 static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
53 cl::desc("Only schedule this function"));
54 static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
55 cl::desc("Only schedule this MBB#"));
57 static bool ViewMISchedDAGs = false;
60 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
61 cl::desc("Enable register pressure scheduling."), cl::init(true));
63 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
64 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
66 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
67 cl::desc("Enable load clustering."), cl::init(true));
69 // Experimental heuristics
70 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
71 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
73 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
74 cl::desc("Verify machine instrs before and after machine scheduling"));
76 // DAG subtrees must have at least this many nodes.
77 static const unsigned MinSubtreeSize = 8;
79 // Pin the vtables to this file.
80 void MachineSchedStrategy::anchor() {}
81 void ScheduleDAGMutation::anchor() {}
83 //===----------------------------------------------------------------------===//
84 // Machine Instruction Scheduling Pass and Registry
85 //===----------------------------------------------------------------------===//
87 MachineSchedContext::MachineSchedContext():
88 MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) {
89 RegClassInfo = new RegisterClassInfo();
92 MachineSchedContext::~MachineSchedContext() {
97 /// Base class for a machine scheduler class that can run at any point.
98 class MachineSchedulerBase : public MachineSchedContext,
99 public MachineFunctionPass {
101 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
103 void print(raw_ostream &O, const Module* = nullptr) const override;
106 void scheduleRegions(ScheduleDAGInstrs &Scheduler);
109 /// MachineScheduler runs after coalescing and before register allocation.
110 class MachineScheduler : public MachineSchedulerBase {
114 void getAnalysisUsage(AnalysisUsage &AU) const override;
116 bool runOnMachineFunction(MachineFunction&) override;
118 static char ID; // Class identification, replacement for typeinfo
121 ScheduleDAGInstrs *createMachineScheduler();
124 /// PostMachineScheduler runs after shortly before code emission.
125 class PostMachineScheduler : public MachineSchedulerBase {
127 PostMachineScheduler();
129 void getAnalysisUsage(AnalysisUsage &AU) const override;
131 bool runOnMachineFunction(MachineFunction&) override;
133 static char ID; // Class identification, replacement for typeinfo
136 ScheduleDAGInstrs *createPostMachineScheduler();
140 char MachineScheduler::ID = 0;
142 char &llvm::MachineSchedulerID = MachineScheduler::ID;
144 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
145 "Machine Instruction Scheduler", false, false)
146 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
147 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
148 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
149 INITIALIZE_PASS_END(MachineScheduler, "misched",
150 "Machine Instruction Scheduler", false, false)
152 MachineScheduler::MachineScheduler()
153 : MachineSchedulerBase(ID) {
154 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
157 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.setPreservesCFG();
159 AU.addRequiredID(MachineDominatorsID);
160 AU.addRequired<MachineLoopInfo>();
161 AU.addRequired<AliasAnalysis>();
162 AU.addRequired<TargetPassConfig>();
163 AU.addRequired<SlotIndexes>();
164 AU.addPreserved<SlotIndexes>();
165 AU.addRequired<LiveIntervals>();
166 AU.addPreserved<LiveIntervals>();
167 MachineFunctionPass::getAnalysisUsage(AU);
170 char PostMachineScheduler::ID = 0;
172 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
174 INITIALIZE_PASS(PostMachineScheduler, "postmisched",
175 "PostRA Machine Instruction Scheduler", false, false)
177 PostMachineScheduler::PostMachineScheduler()
178 : MachineSchedulerBase(ID) {
179 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
182 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
183 AU.setPreservesCFG();
184 AU.addRequiredID(MachineDominatorsID);
185 AU.addRequired<MachineLoopInfo>();
186 AU.addRequired<TargetPassConfig>();
187 MachineFunctionPass::getAnalysisUsage(AU);
190 MachinePassRegistry MachineSchedRegistry::Registry;
192 /// A dummy default scheduler factory indicates whether the scheduler
193 /// is overridden on the command line.
194 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
198 /// MachineSchedOpt allows command line selection of the scheduler.
199 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
200 RegisterPassParser<MachineSchedRegistry> >
201 MachineSchedOpt("misched",
202 cl::init(&useDefaultMachineSched), cl::Hidden,
203 cl::desc("Machine instruction scheduler to use"));
205 static MachineSchedRegistry
206 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
207 useDefaultMachineSched);
209 /// Forward declare the standard machine scheduler. This will be used as the
210 /// default scheduler if the target does not set a default.
211 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C);
212 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C);
214 /// Decrement this iterator until reaching the top or a non-debug instr.
215 static MachineBasicBlock::const_iterator
216 priorNonDebug(MachineBasicBlock::const_iterator I,
217 MachineBasicBlock::const_iterator Beg) {
218 assert(I != Beg && "reached the top of the region, cannot decrement");
220 if (!I->isDebugValue())
226 /// Non-const version.
227 static MachineBasicBlock::iterator
228 priorNonDebug(MachineBasicBlock::iterator I,
229 MachineBasicBlock::const_iterator Beg) {
230 return const_cast<MachineInstr*>(
231 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
234 /// If this iterator is a debug value, increment until reaching the End or a
235 /// non-debug instruction.
236 static MachineBasicBlock::const_iterator
237 nextIfDebug(MachineBasicBlock::const_iterator I,
238 MachineBasicBlock::const_iterator End) {
239 for(; I != End; ++I) {
240 if (!I->isDebugValue())
246 /// Non-const version.
247 static MachineBasicBlock::iterator
248 nextIfDebug(MachineBasicBlock::iterator I,
249 MachineBasicBlock::const_iterator End) {
250 // Cast the return value to nonconst MachineInstr, then cast to an
251 // instr_iterator, which does not check for null, finally return a
253 return MachineBasicBlock::instr_iterator(
254 const_cast<MachineInstr*>(
255 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
258 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
259 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
260 // Select the scheduler, or set the default.
261 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
262 if (Ctor != useDefaultMachineSched)
265 // Get the default scheduler set by the target for this function.
266 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
270 // Default to GenericScheduler.
271 return createGenericSchedLive(this);
274 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
275 /// the caller. We don't have a command line option to override the postRA
276 /// scheduler. The Target must configure it.
277 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
278 // Get the postRA scheduler set by the target for this function.
279 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
283 // Default to GenericScheduler.
284 return createGenericSchedPostRA(this);
287 /// Top-level MachineScheduler pass driver.
289 /// Visit blocks in function order. Divide each block into scheduling regions
290 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
291 /// consistent with the DAG builder, which traverses the interior of the
292 /// scheduling regions bottom-up.
294 /// This design avoids exposing scheduling boundaries to the DAG builder,
295 /// simplifying the DAG builder's support for "special" target instructions.
296 /// At the same time the design allows target schedulers to operate across
297 /// scheduling boundaries, for example to bundle the boudary instructions
298 /// without reordering them. This creates complexity, because the target
299 /// scheduler must update the RegionBegin and RegionEnd positions cached by
300 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
301 /// design would be to split blocks at scheduling boundaries, but LLVM has a
302 /// general bias against block splitting purely for implementation simplicity.
303 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
304 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
306 // Initialize the context of the pass.
308 MLI = &getAnalysis<MachineLoopInfo>();
309 MDT = &getAnalysis<MachineDominatorTree>();
310 PassConfig = &getAnalysis<TargetPassConfig>();
311 AA = &getAnalysis<AliasAnalysis>();
313 LIS = &getAnalysis<LiveIntervals>();
315 if (VerifyScheduling) {
317 MF->verify(this, "Before machine scheduling.");
319 RegClassInfo->runOnMachineFunction(*MF);
321 // Instantiate the selected scheduler for this target, function, and
322 // optimization level.
323 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
324 scheduleRegions(*Scheduler);
327 if (VerifyScheduling)
328 MF->verify(this, "After machine scheduling.");
332 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
333 if (skipOptnoneFunction(*mf.getFunction()))
336 const TargetSubtargetInfo &ST =
337 mf.getTarget().getSubtarget<TargetSubtargetInfo>();
338 if (!ST.enablePostMachineScheduler()) {
339 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
342 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
344 // Initialize the context of the pass.
346 PassConfig = &getAnalysis<TargetPassConfig>();
348 if (VerifyScheduling)
349 MF->verify(this, "Before post machine scheduling.");
351 // Instantiate the selected scheduler for this target, function, and
352 // optimization level.
353 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
354 scheduleRegions(*Scheduler);
356 if (VerifyScheduling)
357 MF->verify(this, "After post machine scheduling.");
361 /// Return true of the given instruction should not be included in a scheduling
364 /// MachineScheduler does not currently support scheduling across calls. To
365 /// handle calls, the DAG builder needs to be modified to create register
366 /// anti/output dependencies on the registers clobbered by the call's regmask
367 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
368 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
369 /// the boundary, but there would be no benefit to postRA scheduling across
370 /// calls this late anyway.
371 static bool isSchedBoundary(MachineBasicBlock::iterator MI,
372 MachineBasicBlock *MBB,
374 const TargetInstrInfo *TII,
376 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
379 /// Main driver for both MachineScheduler and PostMachineScheduler.
380 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
381 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
382 bool IsPostRA = Scheduler.isPostRA();
384 // Visit all machine basic blocks.
386 // TODO: Visit blocks in global postorder or postorder within the bottom-up
387 // loop tree. Then we can optionally compute global RegPressure.
388 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
389 MBB != MBBEnd; ++MBB) {
391 Scheduler.startBlock(MBB);
394 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
396 if (SchedOnlyBlock.getNumOccurrences()
397 && (int)SchedOnlyBlock != MBB->getNumber())
401 // Break the block into scheduling regions [I, RegionEnd), and schedule each
402 // region as soon as it is discovered. RegionEnd points the scheduling
403 // boundary at the bottom of the region. The DAG does not include RegionEnd,
404 // but the region does (i.e. the next RegionEnd is above the previous
405 // RegionBegin). If the current block has no terminator then RegionEnd ==
406 // MBB->end() for the bottom region.
408 // The Scheduler may insert instructions during either schedule() or
409 // exitRegion(), even for empty regions. So the local iterators 'I' and
410 // 'RegionEnd' are invalid across these calls.
412 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
413 // as a single instruction.
414 unsigned RemainingInstrs = std::distance(MBB->begin(), MBB->end());
415 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
416 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
418 // Avoid decrementing RegionEnd for blocks with no terminator.
419 if (RegionEnd != MBB->end() ||
420 isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
422 // Count the boundary instruction.
426 // The next region starts above the previous region. Look backward in the
427 // instruction stream until we find the nearest boundary.
428 unsigned NumRegionInstrs = 0;
429 MachineBasicBlock::iterator I = RegionEnd;
430 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
431 if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
434 // Notify the scheduler of the region, even if we may skip scheduling
435 // it. Perhaps it still needs to be bundled.
436 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
438 // Skip empty scheduling regions (0 or 1 schedulable instructions).
439 if (I == RegionEnd || I == std::prev(RegionEnd)) {
440 // Close the current region. Bundle the terminator if needed.
441 // This invalidates 'RegionEnd' and 'I'.
442 Scheduler.exitRegion();
445 DEBUG(dbgs() << "********** " << ((Scheduler.isPostRA()) ? "PostRA " : "")
446 << "MI Scheduling **********\n");
447 DEBUG(dbgs() << MF->getName()
448 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
449 << "\n From: " << *I << " To: ";
450 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
451 else dbgs() << "End";
452 dbgs() << " RegionInstrs: " << NumRegionInstrs
453 << " Remaining: " << RemainingInstrs << "\n");
455 // Schedule a region: possibly reorder instructions.
456 // This invalidates 'RegionEnd' and 'I'.
457 Scheduler.schedule();
459 // Close the current region.
460 Scheduler.exitRegion();
462 // Scheduling has invalidated the current iterator 'I'. Ask the
463 // scheduler for the top of it's scheduled region.
464 RegionEnd = Scheduler.begin();
466 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
467 Scheduler.finishBlock();
468 if (Scheduler.isPostRA()) {
469 // FIXME: Ideally, no further passes should rely on kill flags. However,
470 // thumb2 size reduction is currently an exception.
471 Scheduler.fixupKills(MBB);
474 Scheduler.finalizeSchedule();
477 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
481 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
482 void ReadyQueue::dump() {
483 dbgs() << Name << ": ";
484 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
485 dbgs() << Queue[i]->NodeNum << " ";
490 //===----------------------------------------------------------------------===//
491 // ScheduleDAGMI - Basic machine instruction scheduling. This is
492 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
493 // virtual registers.
494 // ===----------------------------------------------------------------------===/
496 // Provide a vtable anchor.
497 ScheduleDAGMI::~ScheduleDAGMI() {
500 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
501 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
504 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
505 if (SuccSU != &ExitSU) {
506 // Do not use WillCreateCycle, it assumes SD scheduling.
507 // If Pred is reachable from Succ, then the edge creates a cycle.
508 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
510 Topo.AddPred(SuccSU, PredDep.getSUnit());
512 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
513 // Return true regardless of whether a new edge needed to be inserted.
517 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
518 /// NumPredsLeft reaches zero, release the successor node.
520 /// FIXME: Adjust SuccSU height based on MinLatency.
521 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
522 SUnit *SuccSU = SuccEdge->getSUnit();
524 if (SuccEdge->isWeak()) {
525 --SuccSU->WeakPredsLeft;
526 if (SuccEdge->isCluster())
527 NextClusterSucc = SuccSU;
531 if (SuccSU->NumPredsLeft == 0) {
532 dbgs() << "*** Scheduling failed! ***\n";
534 dbgs() << " has been released too many times!\n";
535 llvm_unreachable(nullptr);
538 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
539 // CurrCycle may have advanced since then.
540 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
541 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
543 --SuccSU->NumPredsLeft;
544 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
545 SchedImpl->releaseTopNode(SuccSU);
548 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
549 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
550 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
552 releaseSucc(SU, &*I);
556 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
557 /// NumSuccsLeft reaches zero, release the predecessor node.
559 /// FIXME: Adjust PredSU height based on MinLatency.
560 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
561 SUnit *PredSU = PredEdge->getSUnit();
563 if (PredEdge->isWeak()) {
564 --PredSU->WeakSuccsLeft;
565 if (PredEdge->isCluster())
566 NextClusterPred = PredSU;
570 if (PredSU->NumSuccsLeft == 0) {
571 dbgs() << "*** Scheduling failed! ***\n";
573 dbgs() << " has been released too many times!\n";
574 llvm_unreachable(nullptr);
577 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
578 // CurrCycle may have advanced since then.
579 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
580 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
582 --PredSU->NumSuccsLeft;
583 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
584 SchedImpl->releaseBottomNode(PredSU);
587 /// releasePredecessors - Call releasePred on each of SU's predecessors.
588 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
589 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
591 releasePred(SU, &*I);
595 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
596 /// crossing a scheduling boundary. [begin, end) includes all instructions in
597 /// the region, including the boundary itself and single-instruction regions
598 /// that don't get scheduled.
599 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
600 MachineBasicBlock::iterator begin,
601 MachineBasicBlock::iterator end,
602 unsigned regioninstrs)
604 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
606 SchedImpl->initPolicy(begin, end, regioninstrs);
609 /// This is normally called from the main scheduler loop but may also be invoked
610 /// by the scheduling strategy to perform additional code motion.
611 void ScheduleDAGMI::moveInstruction(
612 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
613 // Advance RegionBegin if the first instruction moves down.
614 if (&*RegionBegin == MI)
617 // Update the instruction stream.
618 BB->splice(InsertPos, BB, MI);
620 // Update LiveIntervals
622 LIS->handleMove(MI, /*UpdateFlags=*/true);
624 // Recede RegionBegin if an instruction moves above the first.
625 if (RegionBegin == InsertPos)
629 bool ScheduleDAGMI::checkSchedLimit() {
631 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
632 CurrentTop = CurrentBottom;
635 ++NumInstrsScheduled;
640 /// Per-region scheduling driver, called back from
641 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
642 /// does not consider liveness or register pressure. It is useful for PostRA
643 /// scheduling and potentially other custom schedulers.
644 void ScheduleDAGMI::schedule() {
648 Topo.InitDAGTopologicalSorting();
652 SmallVector<SUnit*, 8> TopRoots, BotRoots;
653 findRootsAndBiasEdges(TopRoots, BotRoots);
655 // Initialize the strategy before modifying the DAG.
656 // This may initialize a DFSResult to be used for queue priority.
657 SchedImpl->initialize(this);
659 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
660 SUnits[su].dumpAll(this));
661 if (ViewMISchedDAGs) viewGraph();
663 // Initialize ready queues now that the DAG and priority data are finalized.
664 initQueues(TopRoots, BotRoots);
666 bool IsTopNode = false;
667 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
668 assert(!SU->isScheduled && "Node already scheduled");
669 if (!checkSchedLimit())
672 MachineInstr *MI = SU->getInstr();
674 assert(SU->isTopReady() && "node still has unscheduled dependencies");
675 if (&*CurrentTop == MI)
676 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
678 moveInstruction(MI, CurrentTop);
681 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
682 MachineBasicBlock::iterator priorII =
683 priorNonDebug(CurrentBottom, CurrentTop);
685 CurrentBottom = priorII;
687 if (&*CurrentTop == MI)
688 CurrentTop = nextIfDebug(++CurrentTop, priorII);
689 moveInstruction(MI, CurrentBottom);
693 // Notify the scheduling strategy before updating the DAG.
694 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
695 // runs, it can then use the accurate ReadyCycle time to determine whether
696 // newly released nodes can move to the readyQ.
697 SchedImpl->schedNode(SU, IsTopNode);
699 updateQueues(SU, IsTopNode);
701 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
706 unsigned BBNum = begin()->getParent()->getNumber();
707 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
713 /// Apply each ScheduleDAGMutation step in order.
714 void ScheduleDAGMI::postprocessDAG() {
715 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
716 Mutations[i]->apply(this);
721 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
722 SmallVectorImpl<SUnit*> &BotRoots) {
723 for (std::vector<SUnit>::iterator
724 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
726 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
728 // Order predecessors so DFSResult follows the critical path.
729 SU->biasCriticalPath();
731 // A SUnit is ready to top schedule if it has no predecessors.
732 if (!I->NumPredsLeft)
733 TopRoots.push_back(SU);
734 // A SUnit is ready to bottom schedule if it has no successors.
735 if (!I->NumSuccsLeft)
736 BotRoots.push_back(SU);
738 ExitSU.biasCriticalPath();
741 /// Identify DAG roots and setup scheduler queues.
742 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
743 ArrayRef<SUnit*> BotRoots) {
744 NextClusterSucc = nullptr;
745 NextClusterPred = nullptr;
747 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
749 // Nodes with unreleased weak edges can still be roots.
750 // Release top roots in forward order.
751 for (SmallVectorImpl<SUnit*>::const_iterator
752 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
753 SchedImpl->releaseTopNode(*I);
755 // Release bottom roots in reverse order so the higher priority nodes appear
756 // first. This is more natural and slightly more efficient.
757 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
758 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
759 SchedImpl->releaseBottomNode(*I);
762 releaseSuccessors(&EntrySU);
763 releasePredecessors(&ExitSU);
765 SchedImpl->registerRoots();
767 // Advance past initial DebugValues.
768 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
769 CurrentBottom = RegionEnd;
772 /// Update scheduler queues after scheduling an instruction.
773 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
774 // Release dependent instructions for scheduling.
776 releaseSuccessors(SU);
778 releasePredecessors(SU);
780 SU->isScheduled = true;
783 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
784 void ScheduleDAGMI::placeDebugValues() {
785 // If first instruction was a DBG_VALUE then put it back.
787 BB->splice(RegionBegin, BB, FirstDbgValue);
788 RegionBegin = FirstDbgValue;
791 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
792 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
793 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
794 MachineInstr *DbgValue = P.first;
795 MachineBasicBlock::iterator OrigPrevMI = P.second;
796 if (&*RegionBegin == DbgValue)
798 BB->splice(++OrigPrevMI, BB, DbgValue);
799 if (OrigPrevMI == std::prev(RegionEnd))
800 RegionEnd = DbgValue;
803 FirstDbgValue = nullptr;
806 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
807 void ScheduleDAGMI::dumpSchedule() const {
808 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
809 if (SUnit *SU = getSUnit(&(*MI)))
812 dbgs() << "Missing SUnit\n";
817 //===----------------------------------------------------------------------===//
818 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
820 //===----------------------------------------------------------------------===//
822 ScheduleDAGMILive::~ScheduleDAGMILive() {
826 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
827 /// crossing a scheduling boundary. [begin, end) includes all instructions in
828 /// the region, including the boundary itself and single-instruction regions
829 /// that don't get scheduled.
830 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
831 MachineBasicBlock::iterator begin,
832 MachineBasicBlock::iterator end,
833 unsigned regioninstrs)
835 // ScheduleDAGMI initializes SchedImpl's per-region policy.
836 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
838 // For convenience remember the end of the liveness region.
839 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
841 SUPressureDiffs.clear();
843 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
846 // Setup the register pressure trackers for the top scheduled top and bottom
847 // scheduled regions.
848 void ScheduleDAGMILive::initRegPressure() {
849 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
850 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
852 // Close the RPTracker to finalize live ins.
853 RPTracker.closeRegion();
855 DEBUG(RPTracker.dump());
857 // Initialize the live ins and live outs.
858 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
859 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
861 // Close one end of the tracker so we can call
862 // getMaxUpward/DownwardPressureDelta before advancing across any
863 // instructions. This converts currently live regs into live ins/outs.
864 TopRPTracker.closeTop();
865 BotRPTracker.closeBottom();
867 BotRPTracker.initLiveThru(RPTracker);
868 if (!BotRPTracker.getLiveThru().empty()) {
869 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
870 DEBUG(dbgs() << "Live Thru: ";
871 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
874 // For each live out vreg reduce the pressure change associated with other
875 // uses of the same vreg below the live-out reaching def.
876 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
878 // Account for liveness generated by the region boundary.
879 if (LiveRegionEnd != RegionEnd) {
880 SmallVector<unsigned, 8> LiveUses;
881 BotRPTracker.recede(&LiveUses);
882 updatePressureDiffs(LiveUses);
885 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
887 // Cache the list of excess pressure sets in this region. This will also track
888 // the max pressure in the scheduled code for these sets.
889 RegionCriticalPSets.clear();
890 const std::vector<unsigned> &RegionPressure =
891 RPTracker.getPressure().MaxSetPressure;
892 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
893 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
894 if (RegionPressure[i] > Limit) {
895 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
896 << " Limit " << Limit
897 << " Actual " << RegionPressure[i] << "\n");
898 RegionCriticalPSets.push_back(PressureChange(i));
901 DEBUG(dbgs() << "Excess PSets: ";
902 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
903 dbgs() << TRI->getRegPressureSetName(
904 RegionCriticalPSets[i].getPSet()) << " ";
908 void ScheduleDAGMILive::
909 updateScheduledPressure(const SUnit *SU,
910 const std::vector<unsigned> &NewMaxPressure) {
911 const PressureDiff &PDiff = getPressureDiff(SU);
912 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
913 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
917 unsigned ID = I->getPSet();
918 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
920 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
921 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
922 && NewMaxPressure[ID] <= INT16_MAX)
923 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
925 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
926 if (NewMaxPressure[ID] >= Limit - 2) {
927 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
928 << NewMaxPressure[ID] << " > " << Limit << "(+ "
929 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
934 /// Update the PressureDiff array for liveness after scheduling this
936 void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
937 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
938 /// FIXME: Currently assuming single-use physregs.
939 unsigned Reg = LiveUses[LUIdx];
940 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
941 if (!TRI->isVirtualRegister(Reg))
944 // This may be called before CurrentBottom has been initialized. However,
945 // BotRPTracker must have a valid position. We want the value live into the
946 // instruction or live out of the block, so ask for the previous
947 // instruction's live-out.
948 const LiveInterval &LI = LIS->getInterval(Reg);
950 MachineBasicBlock::const_iterator I =
951 nextIfDebug(BotRPTracker.getPos(), BB->end());
953 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
955 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
958 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
959 assert(VNI && "No live value at use.");
960 for (VReg2UseMap::iterator
961 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
963 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
965 // If this use comes before the reaching def, it cannot be a last use, so
966 // descrease its pressure change.
967 if (!SU->isScheduled && SU != &ExitSU) {
969 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
970 if (LRQ.valueIn() == VNI)
971 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
977 /// schedule - Called back from MachineScheduler::runOnMachineFunction
978 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
979 /// only includes instructions that have DAG nodes, not scheduling boundaries.
981 /// This is a skeletal driver, with all the functionality pushed into helpers,
982 /// so that it can be easilly extended by experimental schedulers. Generally,
983 /// implementing MachineSchedStrategy should be sufficient to implement a new
984 /// scheduling algorithm. However, if a scheduler further subclasses
985 /// ScheduleDAGMILive then it will want to override this virtual method in order
986 /// to update any specialized state.
987 void ScheduleDAGMILive::schedule() {
988 buildDAGWithRegPressure();
990 Topo.InitDAGTopologicalSorting();
994 SmallVector<SUnit*, 8> TopRoots, BotRoots;
995 findRootsAndBiasEdges(TopRoots, BotRoots);
997 // Initialize the strategy before modifying the DAG.
998 // This may initialize a DFSResult to be used for queue priority.
999 SchedImpl->initialize(this);
1001 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
1002 SUnits[su].dumpAll(this));
1003 if (ViewMISchedDAGs) viewGraph();
1005 // Initialize ready queues now that the DAG and priority data are finalized.
1006 initQueues(TopRoots, BotRoots);
1008 if (ShouldTrackPressure) {
1009 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1010 TopRPTracker.setPos(CurrentTop);
1013 bool IsTopNode = false;
1014 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
1015 assert(!SU->isScheduled && "Node already scheduled");
1016 if (!checkSchedLimit())
1019 scheduleMI(SU, IsTopNode);
1021 updateQueues(SU, IsTopNode);
1024 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1025 if (!ScheduledTrees.test(SubtreeID)) {
1026 ScheduledTrees.set(SubtreeID);
1027 DFSResult->scheduleTree(SubtreeID);
1028 SchedImpl->scheduleTree(SubtreeID);
1032 // Notify the scheduling strategy after updating the DAG.
1033 SchedImpl->schedNode(SU, IsTopNode);
1035 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1040 unsigned BBNum = begin()->getParent()->getNumber();
1041 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1047 /// Build the DAG and setup three register pressure trackers.
1048 void ScheduleDAGMILive::buildDAGWithRegPressure() {
1049 if (!ShouldTrackPressure) {
1051 RegionCriticalPSets.clear();
1052 buildSchedGraph(AA);
1056 // Initialize the register pressure tracker used by buildSchedGraph.
1057 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1058 /*TrackUntiedDefs=*/true);
1060 // Account for liveness generate by the region boundary.
1061 if (LiveRegionEnd != RegionEnd)
1064 // Build the DAG, and compute current register pressure.
1065 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
1067 // Initialize top/bottom trackers after computing region pressure.
1071 void ScheduleDAGMILive::computeDFSResult() {
1073 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1075 ScheduledTrees.clear();
1076 DFSResult->resize(SUnits.size());
1077 DFSResult->compute(SUnits);
1078 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1081 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1082 /// only provides the critical path for single block loops. To handle loops that
1083 /// span blocks, we could use the vreg path latencies provided by
1084 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1085 /// available for use in the scheduler.
1087 /// The cyclic path estimation identifies a def-use pair that crosses the back
1088 /// edge and considers the depth and height of the nodes. For example, consider
1089 /// the following instruction sequence where each instruction has unit latency
1090 /// and defines an epomymous virtual register:
1092 /// a->b(a,c)->c(b)->d(c)->exit
1094 /// The cyclic critical path is a two cycles: b->c->b
1095 /// The acyclic critical path is four cycles: a->b->c->d->exit
1096 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1097 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1098 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1099 /// LiveInDepth = depth(b) = len(a->b) = 1
1101 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1102 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1103 /// CyclicCriticalPath = min(2, 2) = 2
1105 /// This could be relevant to PostRA scheduling, but is currently implemented
1106 /// assuming LiveIntervals.
1107 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1108 // This only applies to single block loop.
1109 if (!BB->isSuccessor(BB))
1112 unsigned MaxCyclicLatency = 0;
1113 // Visit each live out vreg def to find def/use pairs that cross iterations.
1114 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1115 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1118 if (!TRI->isVirtualRegister(Reg))
1120 const LiveInterval &LI = LIS->getInterval(Reg);
1121 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1125 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1126 const SUnit *DefSU = getSUnit(DefMI);
1130 unsigned LiveOutHeight = DefSU->getHeight();
1131 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1132 // Visit all local users of the vreg def.
1133 for (VReg2UseMap::iterator
1134 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1135 if (UI->SU == &ExitSU)
1138 // Only consider uses of the phi.
1139 LiveQueryResult LRQ =
1140 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
1141 if (!LRQ.valueIn()->isPHIDef())
1144 // Assume that a path spanning two iterations is a cycle, which could
1145 // overestimate in strange cases. This allows cyclic latency to be
1146 // estimated as the minimum slack of the vreg's depth or height.
1147 unsigned CyclicLatency = 0;
1148 if (LiveOutDepth > UI->SU->getDepth())
1149 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1151 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1152 if (LiveInHeight > LiveOutHeight) {
1153 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1154 CyclicLatency = LiveInHeight - LiveOutHeight;
1159 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1160 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1161 if (CyclicLatency > MaxCyclicLatency)
1162 MaxCyclicLatency = CyclicLatency;
1165 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1166 return MaxCyclicLatency;
1169 /// Move an instruction and update register pressure.
1170 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1171 // Move the instruction to its new location in the instruction stream.
1172 MachineInstr *MI = SU->getInstr();
1175 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1176 if (&*CurrentTop == MI)
1177 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1179 moveInstruction(MI, CurrentTop);
1180 TopRPTracker.setPos(MI);
1183 if (ShouldTrackPressure) {
1184 // Update top scheduled pressure.
1185 TopRPTracker.advance();
1186 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1187 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1191 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1192 MachineBasicBlock::iterator priorII =
1193 priorNonDebug(CurrentBottom, CurrentTop);
1194 if (&*priorII == MI)
1195 CurrentBottom = priorII;
1197 if (&*CurrentTop == MI) {
1198 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1199 TopRPTracker.setPos(CurrentTop);
1201 moveInstruction(MI, CurrentBottom);
1204 if (ShouldTrackPressure) {
1205 // Update bottom scheduled pressure.
1206 SmallVector<unsigned, 8> LiveUses;
1207 BotRPTracker.recede(&LiveUses);
1208 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1209 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1210 updatePressureDiffs(LiveUses);
1215 //===----------------------------------------------------------------------===//
1216 // LoadClusterMutation - DAG post-processing to cluster loads.
1217 //===----------------------------------------------------------------------===//
1220 /// \brief Post-process the DAG to create cluster edges between neighboring
1222 class LoadClusterMutation : public ScheduleDAGMutation {
1227 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1228 : SU(su), BaseReg(reg), Offset(ofs) {}
1230 bool operator<(const LoadInfo &RHS) const {
1231 return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset);
1235 const TargetInstrInfo *TII;
1236 const TargetRegisterInfo *TRI;
1238 LoadClusterMutation(const TargetInstrInfo *tii,
1239 const TargetRegisterInfo *tri)
1240 : TII(tii), TRI(tri) {}
1242 void apply(ScheduleDAGMI *DAG) override;
1244 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1248 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1249 ScheduleDAGMI *DAG) {
1250 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1251 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1252 SUnit *SU = Loads[Idx];
1255 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1256 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1258 if (LoadRecords.size() < 2)
1260 std::sort(LoadRecords.begin(), LoadRecords.end());
1261 unsigned ClusterLength = 1;
1262 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1263 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1268 SUnit *SUa = LoadRecords[Idx].SU;
1269 SUnit *SUb = LoadRecords[Idx+1].SU;
1270 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
1271 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1273 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1274 << SUb->NodeNum << ")\n");
1275 // Copy successor edges from SUa to SUb. Interleaving computation
1276 // dependent on SUa can prevent load combining due to register reuse.
1277 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1278 // loads should have effectively the same inputs.
1279 for (SUnit::const_succ_iterator
1280 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1281 if (SI->getSUnit() == SUb)
1283 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1284 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1293 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1294 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1295 // Map DAG NodeNum to store chain ID.
1296 DenseMap<unsigned, unsigned> StoreChainIDs;
1297 // Map each store chain to a set of dependent loads.
1298 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1299 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1300 SUnit *SU = &DAG->SUnits[Idx];
1301 if (!SU->getInstr()->mayLoad())
1303 unsigned ChainPredID = DAG->SUnits.size();
1304 for (SUnit::const_pred_iterator
1305 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1307 ChainPredID = PI->getSUnit()->NodeNum;
1311 // Check if this chain-like pred has been seen
1312 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1313 unsigned NumChains = StoreChainDependents.size();
1314 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1315 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1317 StoreChainDependents.resize(NumChains + 1);
1318 StoreChainDependents[Result.first->second].push_back(SU);
1320 // Iterate over the store chains.
1321 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1322 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1325 //===----------------------------------------------------------------------===//
1326 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1327 //===----------------------------------------------------------------------===//
1330 /// \brief Post-process the DAG to create cluster edges between instructions
1331 /// that may be fused by the processor into a single operation.
1332 class MacroFusion : public ScheduleDAGMutation {
1333 const TargetInstrInfo *TII;
1335 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1337 void apply(ScheduleDAGMI *DAG) override;
1341 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1342 /// fused operations.
1343 void MacroFusion::apply(ScheduleDAGMI *DAG) {
1344 // For now, assume targets can only fuse with the branch.
1345 MachineInstr *Branch = DAG->ExitSU.getInstr();
1349 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1350 SUnit *SU = &DAG->SUnits[--Idx];
1351 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1354 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1355 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1356 // need to copy predecessor edges from ExitSU to SU, since top-down
1357 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1358 // of SU, we could create an artificial edge from the deepest root, but it
1359 // hasn't been needed yet.
1360 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1362 assert(Success && "No DAG nodes should be reachable from ExitSU");
1364 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1369 //===----------------------------------------------------------------------===//
1370 // CopyConstrain - DAG post-processing to encourage copy elimination.
1371 //===----------------------------------------------------------------------===//
1374 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1375 /// the one use that defines the copy's source vreg, most likely an induction
1376 /// variable increment.
1377 class CopyConstrain : public ScheduleDAGMutation {
1379 SlotIndex RegionBeginIdx;
1380 // RegionEndIdx is the slot index of the last non-debug instruction in the
1381 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1382 SlotIndex RegionEndIdx;
1384 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1386 void apply(ScheduleDAGMI *DAG) override;
1389 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1393 /// constrainLocalCopy handles two possibilities:
1398 /// I3: dst = src (copy)
1399 /// (create pred->succ edges I0->I1, I2->I1)
1402 /// I0: dst = src (copy)
1406 /// (create pred->succ edges I1->I2, I3->I2)
1408 /// Although the MachineScheduler is currently constrained to single blocks,
1409 /// this algorithm should handle extended blocks. An EBB is a set of
1410 /// contiguously numbered blocks such that the previous block in the EBB is
1411 /// always the single predecessor.
1412 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1413 LiveIntervals *LIS = DAG->getLIS();
1414 MachineInstr *Copy = CopySU->getInstr();
1416 // Check for pure vreg copies.
1417 unsigned SrcReg = Copy->getOperand(1).getReg();
1418 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1421 unsigned DstReg = Copy->getOperand(0).getReg();
1422 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1425 // Check if either the dest or source is local. If it's live across a back
1426 // edge, it's not local. Note that if both vregs are live across the back
1427 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1428 unsigned LocalReg = DstReg;
1429 unsigned GlobalReg = SrcReg;
1430 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1431 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1434 LocalLI = &LIS->getInterval(LocalReg);
1435 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1438 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1440 // Find the global segment after the start of the local LI.
1441 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1442 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1443 // local live range. We could create edges from other global uses to the local
1444 // start, but the coalescer should have already eliminated these cases, so
1445 // don't bother dealing with it.
1446 if (GlobalSegment == GlobalLI->end())
1449 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1450 // returned the next global segment. But if GlobalSegment overlaps with
1451 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1452 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1453 if (GlobalSegment->contains(LocalLI->beginIndex()))
1456 if (GlobalSegment == GlobalLI->end())
1459 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1460 if (GlobalSegment != GlobalLI->begin()) {
1461 // Two address defs have no hole.
1462 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1463 GlobalSegment->start)) {
1466 // If the prior global segment may be defined by the same two-address
1467 // instruction that also defines LocalLI, then can't make a hole here.
1468 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1469 LocalLI->beginIndex())) {
1472 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1473 // it would be a disconnected component in the live range.
1474 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1475 "Disconnected LRG within the scheduling region.");
1477 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1481 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1485 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1486 // constraining the uses of the last local def to precede GlobalDef.
1487 SmallVector<SUnit*,8> LocalUses;
1488 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1489 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1490 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1491 for (SUnit::const_succ_iterator
1492 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1494 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1496 if (I->getSUnit() == GlobalSU)
1498 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1500 LocalUses.push_back(I->getSUnit());
1502 // Open the top of the GlobalLI hole by constraining any earlier global uses
1503 // to precede the start of LocalLI.
1504 SmallVector<SUnit*,8> GlobalUses;
1505 MachineInstr *FirstLocalDef =
1506 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1507 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1508 for (SUnit::const_pred_iterator
1509 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1510 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1512 if (I->getSUnit() == FirstLocalSU)
1514 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1516 GlobalUses.push_back(I->getSUnit());
1518 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1519 // Add the weak edges.
1520 for (SmallVectorImpl<SUnit*>::const_iterator
1521 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1522 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1523 << GlobalSU->NodeNum << ")\n");
1524 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1526 for (SmallVectorImpl<SUnit*>::const_iterator
1527 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1528 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1529 << FirstLocalSU->NodeNum << ")\n");
1530 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1534 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1535 /// copy elimination.
1536 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1537 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1539 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1540 if (FirstPos == DAG->end())
1542 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1543 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1544 &*priorNonDebug(DAG->end(), DAG->begin()));
1546 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1547 SUnit *SU = &DAG->SUnits[Idx];
1548 if (!SU->getInstr()->isCopy())
1551 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1555 //===----------------------------------------------------------------------===//
1556 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1557 // and possibly other custom schedulers.
1558 //===----------------------------------------------------------------------===//
1560 static const unsigned InvalidCycle = ~0U;
1562 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1564 void SchedBoundary::reset() {
1565 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1566 // Destroying and reconstructing it is very expensive though. So keep
1567 // invalid, placeholder HazardRecs.
1568 if (HazardRec && HazardRec->isEnabled()) {
1570 HazardRec = nullptr;
1574 CheckPending = false;
1578 MinReadyCycle = UINT_MAX;
1579 ExpectedLatency = 0;
1580 DependentLatency = 0;
1582 MaxExecutedResCount = 0;
1584 IsResourceLimited = false;
1585 ReservedCycles.clear();
1587 // Track the maximum number of stall cycles that could arise either from the
1588 // latency of a DAG edge or the number of cycles that a processor resource is
1589 // reserved (SchedBoundary::ReservedCycles).
1590 MaxObservedStall = 0;
1592 // Reserve a zero-count for invalid CritResIdx.
1593 ExecutedResCounts.resize(1);
1594 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1597 void SchedRemainder::
1598 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1600 if (!SchedModel->hasInstrSchedModel())
1602 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1603 for (std::vector<SUnit>::iterator
1604 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1605 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1606 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1607 * SchedModel->getMicroOpFactor();
1608 for (TargetSchedModel::ProcResIter
1609 PI = SchedModel->getWriteProcResBegin(SC),
1610 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1611 unsigned PIdx = PI->ProcResourceIdx;
1612 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1613 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1618 void SchedBoundary::
1619 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1622 SchedModel = smodel;
1624 if (SchedModel->hasInstrSchedModel()) {
1625 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1626 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1630 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1631 /// these "soft stalls" differently than the hard stall cycles based on CPU
1632 /// resources and computed by checkHazard(). A fully in-order model
1633 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1634 /// available for scheduling until they are ready. However, a weaker in-order
1635 /// model may use this for heuristics. For example, if a processor has in-order
1636 /// behavior when reading certain resources, this may come into play.
1637 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1638 if (!SU->isUnbuffered)
1641 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1642 if (ReadyCycle > CurrCycle)
1643 return ReadyCycle - CurrCycle;
1647 /// Compute the next cycle at which the given processor resource can be
1649 unsigned SchedBoundary::
1650 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1651 unsigned NextUnreserved = ReservedCycles[PIdx];
1652 // If this resource has never been used, always return cycle zero.
1653 if (NextUnreserved == InvalidCycle)
1655 // For bottom-up scheduling add the cycles needed for the current operation.
1657 NextUnreserved += Cycles;
1658 return NextUnreserved;
1661 /// Does this SU have a hazard within the current instruction group.
1663 /// The scheduler supports two modes of hazard recognition. The first is the
1664 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1665 /// supports highly complicated in-order reservation tables
1666 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1668 /// The second is a streamlined mechanism that checks for hazards based on
1669 /// simple counters that the scheduler itself maintains. It explicitly checks
1670 /// for instruction dispatch limitations, including the number of micro-ops that
1671 /// can dispatch per cycle.
1673 /// TODO: Also check whether the SU must start a new group.
1674 bool SchedBoundary::checkHazard(SUnit *SU) {
1675 if (HazardRec->isEnabled()
1676 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1679 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1680 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1681 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1682 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1685 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1686 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1687 for (TargetSchedModel::ProcResIter
1688 PI = SchedModel->getWriteProcResBegin(SC),
1689 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1690 unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1691 if (NRCycle > CurrCycle) {
1692 MaxObservedStall = std::max(NRCycle - CurrCycle, MaxObservedStall);
1693 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1694 << SchedModel->getResourceName(PI->ProcResourceIdx)
1695 << "=" << NRCycle << "c\n");
1703 // Find the unscheduled node in ReadySUs with the highest latency.
1704 unsigned SchedBoundary::
1705 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1706 SUnit *LateSU = nullptr;
1707 unsigned RemLatency = 0;
1708 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1710 unsigned L = getUnscheduledLatency(*I);
1711 if (L > RemLatency) {
1717 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1718 << LateSU->NodeNum << ") " << RemLatency << "c\n");
1723 // Count resources in this zone and the remaining unscheduled
1724 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1725 // resource index, or zero if the zone is issue limited.
1726 unsigned SchedBoundary::
1727 getOtherResourceCount(unsigned &OtherCritIdx) {
1729 if (!SchedModel->hasInstrSchedModel())
1732 unsigned OtherCritCount = Rem->RemIssueCount
1733 + (RetiredMOps * SchedModel->getMicroOpFactor());
1734 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1735 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1736 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1737 PIdx != PEnd; ++PIdx) {
1738 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1739 if (OtherCount > OtherCritCount) {
1740 OtherCritCount = OtherCount;
1741 OtherCritIdx = PIdx;
1745 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1746 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1747 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1749 return OtherCritCount;
1752 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1753 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1756 // ReadyCycle was been bumped up to the CurrCycle when this node was
1757 // scheduled, but CurrCycle may have been eagerly advanced immediately after
1758 // scheduling, so may now be greater than ReadyCycle.
1759 if (ReadyCycle > CurrCycle)
1760 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
1763 if (ReadyCycle < MinReadyCycle)
1764 MinReadyCycle = ReadyCycle;
1766 // Check for interlocks first. For the purpose of other heuristics, an
1767 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1768 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1769 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1774 // Record this node as an immediate dependent of the scheduled node.
1778 void SchedBoundary::releaseTopNode(SUnit *SU) {
1779 if (SU->isScheduled)
1782 releaseNode(SU, SU->TopReadyCycle);
1785 void SchedBoundary::releaseBottomNode(SUnit *SU) {
1786 if (SU->isScheduled)
1789 releaseNode(SU, SU->BotReadyCycle);
1792 /// Move the boundary of scheduled code by one cycle.
1793 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1794 if (SchedModel->getMicroOpBufferSize() == 0) {
1795 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1796 if (MinReadyCycle > NextCycle)
1797 NextCycle = MinReadyCycle;
1799 // Update the current micro-ops, which will issue in the next cycle.
1800 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1801 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1803 // Decrement DependentLatency based on the next cycle.
1804 if ((NextCycle - CurrCycle) > DependentLatency)
1805 DependentLatency = 0;
1807 DependentLatency -= (NextCycle - CurrCycle);
1809 if (!HazardRec->isEnabled()) {
1810 // Bypass HazardRec virtual calls.
1811 CurrCycle = NextCycle;
1814 // Bypass getHazardType calls in case of long latency.
1815 for (; CurrCycle != NextCycle; ++CurrCycle) {
1817 HazardRec->AdvanceCycle();
1819 HazardRec->RecedeCycle();
1822 CheckPending = true;
1823 unsigned LFactor = SchedModel->getLatencyFactor();
1825 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1828 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1831 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
1832 ExecutedResCounts[PIdx] += Count;
1833 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1834 MaxExecutedResCount = ExecutedResCounts[PIdx];
1837 /// Add the given processor resource to this scheduled zone.
1839 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1840 /// during which this resource is consumed.
1842 /// \return the next cycle at which the instruction may execute without
1843 /// oversubscribing resources.
1844 unsigned SchedBoundary::
1845 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
1846 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1847 unsigned Count = Factor * Cycles;
1848 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
1849 << " +" << Cycles << "x" << Factor << "u\n");
1851 // Update Executed resources counts.
1852 incExecutedResources(PIdx, Count);
1853 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1854 Rem->RemainingCounts[PIdx] -= Count;
1856 // Check if this resource exceeds the current critical resource. If so, it
1857 // becomes the critical resource.
1858 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1859 ZoneCritResIdx = PIdx;
1860 DEBUG(dbgs() << " *** Critical resource "
1861 << SchedModel->getResourceName(PIdx) << ": "
1862 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1864 // For reserved resources, record the highest cycle using the resource.
1865 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1866 if (NextAvailable > CurrCycle) {
1867 DEBUG(dbgs() << " Resource conflict: "
1868 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1869 << NextAvailable << "\n");
1871 return NextAvailable;
1874 /// Move the boundary of scheduled code by one SUnit.
1875 void SchedBoundary::bumpNode(SUnit *SU) {
1876 // Update the reservation table.
1877 if (HazardRec->isEnabled()) {
1878 if (!isTop() && SU->isCall) {
1879 // Calls are scheduled with their preceding instructions. For bottom-up
1880 // scheduling, clear the pipeline state before emitting.
1883 HazardRec->EmitInstruction(SU);
1885 // checkHazard should prevent scheduling multiple instructions per cycle that
1886 // exceed the issue width.
1887 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1888 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1890 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
1891 "Cannot schedule this instruction's MicroOps in the current cycle.");
1893 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1894 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1896 unsigned NextCycle = CurrCycle;
1897 switch (SchedModel->getMicroOpBufferSize()) {
1899 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1902 if (ReadyCycle > NextCycle) {
1903 NextCycle = ReadyCycle;
1904 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1908 // We don't currently model the OOO reorder buffer, so consider all
1909 // scheduled MOps to be "retired". We do loosely model in-order resource
1910 // latency. If this instruction uses an in-order resource, account for any
1911 // likely stall cycles.
1912 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1913 NextCycle = ReadyCycle;
1916 RetiredMOps += IncMOps;
1918 // Update resource counts and critical resource.
1919 if (SchedModel->hasInstrSchedModel()) {
1920 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1921 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1922 Rem->RemIssueCount -= DecRemIssue;
1923 if (ZoneCritResIdx) {
1924 // Scale scheduled micro-ops for comparing with the critical resource.
1925 unsigned ScaledMOps =
1926 RetiredMOps * SchedModel->getMicroOpFactor();
1928 // If scaled micro-ops are now more than the previous critical resource by
1929 // a full cycle, then micro-ops issue becomes critical.
1930 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1931 >= (int)SchedModel->getLatencyFactor()) {
1933 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1934 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1937 for (TargetSchedModel::ProcResIter
1938 PI = SchedModel->getWriteProcResBegin(SC),
1939 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1941 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
1942 if (RCycle > NextCycle)
1945 if (SU->hasReservedResource) {
1946 // For reserved resources, record the highest cycle using the resource.
1947 // For top-down scheduling, this is the cycle in which we schedule this
1948 // instruction plus the number of cycles the operations reserves the
1949 // resource. For bottom-up is it simply the instruction's cycle.
1950 for (TargetSchedModel::ProcResIter
1951 PI = SchedModel->getWriteProcResBegin(SC),
1952 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1953 unsigned PIdx = PI->ProcResourceIdx;
1954 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
1955 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
1957 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
1963 // Update ExpectedLatency and DependentLatency.
1964 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1965 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1966 if (SU->getDepth() > TopLatency) {
1967 TopLatency = SU->getDepth();
1968 DEBUG(dbgs() << " " << Available.getName()
1969 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1971 if (SU->getHeight() > BotLatency) {
1972 BotLatency = SU->getHeight();
1973 DEBUG(dbgs() << " " << Available.getName()
1974 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1976 // If we stall for any reason, bump the cycle.
1977 if (NextCycle > CurrCycle) {
1978 bumpCycle(NextCycle);
1981 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1982 // resource limited. If a stall occurred, bumpCycle does this.
1983 unsigned LFactor = SchedModel->getLatencyFactor();
1985 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1988 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1989 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1990 // one cycle. Since we commonly reach the max MOps here, opportunistically
1991 // bump the cycle to avoid uselessly checking everything in the readyQ.
1992 CurrMOps += IncMOps;
1993 while (CurrMOps >= SchedModel->getIssueWidth()) {
1994 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1995 << " at cycle " << CurrCycle << '\n');
1996 bumpCycle(++NextCycle);
1998 DEBUG(dumpScheduledState());
2001 /// Release pending ready nodes in to the available queue. This makes them
2002 /// visible to heuristics.
2003 void SchedBoundary::releasePending() {
2004 // If the available queue is empty, it is safe to reset MinReadyCycle.
2005 if (Available.empty())
2006 MinReadyCycle = UINT_MAX;
2008 // Check to see if any of the pending instructions are ready to issue. If
2009 // so, add them to the available queue.
2010 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2011 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2012 SUnit *SU = *(Pending.begin()+i);
2013 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
2015 if (ReadyCycle < MinReadyCycle)
2016 MinReadyCycle = ReadyCycle;
2018 if (!IsBuffered && ReadyCycle > CurrCycle)
2021 if (checkHazard(SU))
2025 Pending.remove(Pending.begin()+i);
2028 DEBUG(if (!Pending.empty()) Pending.dump());
2029 CheckPending = false;
2032 /// Remove SU from the ready set for this boundary.
2033 void SchedBoundary::removeReady(SUnit *SU) {
2034 if (Available.isInQueue(SU))
2035 Available.remove(Available.find(SU));
2037 assert(Pending.isInQueue(SU) && "bad ready count");
2038 Pending.remove(Pending.find(SU));
2042 /// If this queue only has one ready candidate, return it. As a side effect,
2043 /// defer any nodes that now hit a hazard, and advance the cycle until at least
2044 /// one node is ready. If multiple instructions are ready, return NULL.
2045 SUnit *SchedBoundary::pickOnlyChoice() {
2050 // Defer any ready instrs that now have a hazard.
2051 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2052 if (checkHazard(*I)) {
2054 I = Available.remove(I);
2060 for (unsigned i = 0; Available.empty(); ++i) {
2061 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2062 "permanent hazard"); (void)i;
2063 bumpCycle(CurrCycle + 1);
2066 if (Available.size() == 1)
2067 return *Available.begin();
2072 // This is useful information to dump after bumpNode.
2073 // Note that the Queue contents are more useful before pickNodeFromQueue.
2074 void SchedBoundary::dumpScheduledState() {
2077 if (ZoneCritResIdx) {
2078 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2079 ResCount = getResourceCount(ZoneCritResIdx);
2082 ResFactor = SchedModel->getMicroOpFactor();
2083 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2085 unsigned LFactor = SchedModel->getLatencyFactor();
2086 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2087 << " Retired: " << RetiredMOps;
2088 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2089 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
2090 << ResCount / ResFactor << " "
2091 << SchedModel->getResourceName(ZoneCritResIdx)
2092 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2093 << (IsResourceLimited ? " - Resource" : " - Latency")
2098 //===----------------------------------------------------------------------===//
2099 // GenericScheduler - Generic implementation of MachineSchedStrategy.
2100 //===----------------------------------------------------------------------===//
2102 void GenericSchedulerBase::SchedCandidate::
2103 initResourceDelta(const ScheduleDAGMI *DAG,
2104 const TargetSchedModel *SchedModel) {
2105 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2108 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2109 for (TargetSchedModel::ProcResIter
2110 PI = SchedModel->getWriteProcResBegin(SC),
2111 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2112 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2113 ResDelta.CritResources += PI->Cycles;
2114 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2115 ResDelta.DemandedResources += PI->Cycles;
2119 /// Set the CandPolicy given a scheduling zone given the current resources and
2120 /// latencies inside and outside the zone.
2121 void GenericSchedulerBase::setPolicy(CandPolicy &Policy,
2123 SchedBoundary &CurrZone,
2124 SchedBoundary *OtherZone) {
2125 // Apply preemptive heuristics based on the the total latency and resources
2126 // inside and outside this zone. Potential stalls should be considered before
2127 // following this policy.
2129 // Compute remaining latency. We need this both to determine whether the
2130 // overall schedule has become latency-limited and whether the instructions
2131 // outside this zone are resource or latency limited.
2133 // The "dependent" latency is updated incrementally during scheduling as the
2134 // max height/depth of scheduled nodes minus the cycles since it was
2136 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2138 // The "independent" latency is the max ready queue depth:
2139 // ILat = max N.depth for N in Available|Pending
2141 // RemainingLatency is the greater of independent and dependent latency.
2142 unsigned RemLatency = CurrZone.getDependentLatency();
2143 RemLatency = std::max(RemLatency,
2144 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2145 RemLatency = std::max(RemLatency,
2146 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2148 // Compute the critical resource outside the zone.
2149 unsigned OtherCritIdx = 0;
2150 unsigned OtherCount =
2151 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2153 bool OtherResLimited = false;
2154 if (SchedModel->hasInstrSchedModel()) {
2155 unsigned LFactor = SchedModel->getLatencyFactor();
2156 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2158 // Schedule aggressively for latency in PostRA mode. We don't check for
2159 // acyclic latency during PostRA, and highly out-of-order processors will
2160 // skip PostRA scheduling.
2161 if (!OtherResLimited) {
2162 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2163 Policy.ReduceLatency |= true;
2164 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2165 << " RemainingLatency " << RemLatency << " + "
2166 << CurrZone.getCurrCycle() << "c > CritPath "
2167 << Rem.CriticalPath << "\n");
2170 // If the same resource is limiting inside and outside the zone, do nothing.
2171 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2175 if (CurrZone.isResourceLimited()) {
2176 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2177 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2180 if (OtherResLimited)
2181 dbgs() << " RemainingLimit: "
2182 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2183 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2184 dbgs() << " Latency limited both directions.\n");
2186 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2187 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2189 if (OtherResLimited)
2190 Policy.DemandResIdx = OtherCritIdx;
2194 const char *GenericSchedulerBase::getReasonStr(
2195 GenericSchedulerBase::CandReason Reason) {
2197 case NoCand: return "NOCAND ";
2198 case PhysRegCopy: return "PREG-COPY";
2199 case RegExcess: return "REG-EXCESS";
2200 case RegCritical: return "REG-CRIT ";
2201 case Stall: return "STALL ";
2202 case Cluster: return "CLUSTER ";
2203 case Weak: return "WEAK ";
2204 case RegMax: return "REG-MAX ";
2205 case ResourceReduce: return "RES-REDUCE";
2206 case ResourceDemand: return "RES-DEMAND";
2207 case TopDepthReduce: return "TOP-DEPTH ";
2208 case TopPathReduce: return "TOP-PATH ";
2209 case BotHeightReduce:return "BOT-HEIGHT";
2210 case BotPathReduce: return "BOT-PATH ";
2211 case NextDefUse: return "DEF-USE ";
2212 case NodeOrder: return "ORDER ";
2214 llvm_unreachable("Unknown reason!");
2217 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2219 unsigned ResIdx = 0;
2220 unsigned Latency = 0;
2221 switch (Cand.Reason) {
2225 P = Cand.RPDelta.Excess;
2228 P = Cand.RPDelta.CriticalMax;
2231 P = Cand.RPDelta.CurrentMax;
2233 case ResourceReduce:
2234 ResIdx = Cand.Policy.ReduceResIdx;
2236 case ResourceDemand:
2237 ResIdx = Cand.Policy.DemandResIdx;
2239 case TopDepthReduce:
2240 Latency = Cand.SU->getDepth();
2243 Latency = Cand.SU->getHeight();
2245 case BotHeightReduce:
2246 Latency = Cand.SU->getHeight();
2249 Latency = Cand.SU->getDepth();
2252 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2254 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2255 << ":" << P.getUnitInc() << " ";
2259 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2263 dbgs() << " " << Latency << " cycles ";
2270 /// Return true if this heuristic determines order.
2271 static bool tryLess(int TryVal, int CandVal,
2272 GenericSchedulerBase::SchedCandidate &TryCand,
2273 GenericSchedulerBase::SchedCandidate &Cand,
2274 GenericSchedulerBase::CandReason Reason) {
2275 if (TryVal < CandVal) {
2276 TryCand.Reason = Reason;
2279 if (TryVal > CandVal) {
2280 if (Cand.Reason > Reason)
2281 Cand.Reason = Reason;
2284 Cand.setRepeat(Reason);
2288 static bool tryGreater(int TryVal, int CandVal,
2289 GenericSchedulerBase::SchedCandidate &TryCand,
2290 GenericSchedulerBase::SchedCandidate &Cand,
2291 GenericSchedulerBase::CandReason Reason) {
2292 if (TryVal > CandVal) {
2293 TryCand.Reason = Reason;
2296 if (TryVal < CandVal) {
2297 if (Cand.Reason > Reason)
2298 Cand.Reason = Reason;
2301 Cand.setRepeat(Reason);
2305 static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2306 GenericSchedulerBase::SchedCandidate &Cand,
2307 SchedBoundary &Zone) {
2309 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2310 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2311 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2314 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2315 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2319 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2320 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2321 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2324 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2325 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2331 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2333 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2334 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n');
2337 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2338 assert(dag->hasVRegLiveness() &&
2339 "(PreRA)GenericScheduler needs vreg liveness");
2340 DAG = static_cast<ScheduleDAGMILive*>(dag);
2341 SchedModel = DAG->getSchedModel();
2344 Rem.init(DAG, SchedModel);
2345 Top.init(DAG, SchedModel, &Rem);
2346 Bot.init(DAG, SchedModel, &Rem);
2348 // Initialize resource counts.
2350 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2351 // are disabled, then these HazardRecs will be disabled.
2352 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2353 const TargetMachine &TM = DAG->MF.getTarget();
2354 if (!Top.HazardRec) {
2356 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2358 if (!Bot.HazardRec) {
2360 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2364 /// Initialize the per-region scheduling policy.
2365 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2366 MachineBasicBlock::iterator End,
2367 unsigned NumRegionInstrs) {
2368 const TargetMachine &TM = Context->MF->getTarget();
2369 const TargetLowering *TLI = TM.getTargetLowering();
2371 // Avoid setting up the register pressure tracker for small regions to save
2372 // compile time. As a rough heuristic, only track pressure when the number of
2373 // schedulable instructions exceeds half the integer register file.
2374 RegionPolicy.ShouldTrackPressure = true;
2375 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2376 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2377 if (TLI->isTypeLegal(LegalIntVT)) {
2378 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2379 TLI->getRegClassFor(LegalIntVT));
2380 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2384 // For generic targets, we default to bottom-up, because it's simpler and more
2385 // compile-time optimizations have been implemented in that direction.
2386 RegionPolicy.OnlyBottomUp = true;
2388 // Allow the subtarget to override default policy.
2389 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2390 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2392 // After subtarget overrides, apply command line options.
2393 if (!EnableRegPressure)
2394 RegionPolicy.ShouldTrackPressure = false;
2396 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2397 // e.g. -misched-bottomup=false allows scheduling in both directions.
2398 assert((!ForceTopDown || !ForceBottomUp) &&
2399 "-misched-topdown incompatible with -misched-bottomup");
2400 if (ForceBottomUp.getNumOccurrences() > 0) {
2401 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2402 if (RegionPolicy.OnlyBottomUp)
2403 RegionPolicy.OnlyTopDown = false;
2405 if (ForceTopDown.getNumOccurrences() > 0) {
2406 RegionPolicy.OnlyTopDown = ForceTopDown;
2407 if (RegionPolicy.OnlyTopDown)
2408 RegionPolicy.OnlyBottomUp = false;
2412 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2413 /// critical path by more cycles than it takes to drain the instruction buffer.
2414 /// We estimate an upper bounds on in-flight instructions as:
2416 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2417 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2418 /// InFlightResources = InFlightIterations * LoopResources
2420 /// TODO: Check execution resources in addition to IssueCount.
2421 void GenericScheduler::checkAcyclicLatency() {
2422 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2425 // Scaled number of cycles per loop iteration.
2426 unsigned IterCount =
2427 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2429 // Scaled acyclic critical path.
2430 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2431 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2432 unsigned InFlightCount =
2433 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2434 unsigned BufferLimit =
2435 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2437 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2439 DEBUG(dbgs() << "IssueCycles="
2440 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2441 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2442 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2443 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2444 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2445 if (Rem.IsAcyclicLatencyLimited)
2446 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2449 void GenericScheduler::registerRoots() {
2450 Rem.CriticalPath = DAG->ExitSU.getDepth();
2452 // Some roots may not feed into ExitSU. Check all of them in case.
2453 for (std::vector<SUnit*>::const_iterator
2454 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2455 if ((*I)->getDepth() > Rem.CriticalPath)
2456 Rem.CriticalPath = (*I)->getDepth();
2458 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2460 if (EnableCyclicPath) {
2461 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2462 checkAcyclicLatency();
2466 static bool tryPressure(const PressureChange &TryP,
2467 const PressureChange &CandP,
2468 GenericSchedulerBase::SchedCandidate &TryCand,
2469 GenericSchedulerBase::SchedCandidate &Cand,
2470 GenericSchedulerBase::CandReason Reason) {
2471 int TryRank = TryP.getPSetOrMax();
2472 int CandRank = CandP.getPSetOrMax();
2473 // If both candidates affect the same set, go with the smallest increase.
2474 if (TryRank == CandRank) {
2475 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2478 // If one candidate decreases and the other increases, go with it.
2479 // Invalid candidates have UnitInc==0.
2480 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2484 // If the candidates are decreasing pressure, reverse priority.
2485 if (TryP.getUnitInc() < 0)
2486 std::swap(TryRank, CandRank);
2487 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2490 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2491 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2494 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2495 /// their physreg def/use.
2497 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2498 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2499 /// with the operation that produces or consumes the physreg. We'll do this when
2500 /// regalloc has support for parallel copies.
2501 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2502 const MachineInstr *MI = SU->getInstr();
2506 unsigned ScheduledOper = isTop ? 1 : 0;
2507 unsigned UnscheduledOper = isTop ? 0 : 1;
2508 // If we have already scheduled the physreg produce/consumer, immediately
2509 // schedule the copy.
2510 if (TargetRegisterInfo::isPhysicalRegister(
2511 MI->getOperand(ScheduledOper).getReg()))
2513 // If the physreg is at the boundary, defer it. Otherwise schedule it
2514 // immediately to free the dependent. We can hoist the copy later.
2515 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2516 if (TargetRegisterInfo::isPhysicalRegister(
2517 MI->getOperand(UnscheduledOper).getReg()))
2518 return AtBoundary ? -1 : 1;
2522 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2523 /// hierarchical. This may be more efficient than a graduated cost model because
2524 /// we don't need to evaluate all aspects of the model for each node in the
2525 /// queue. But it's really done to make the heuristics easier to debug and
2526 /// statistically analyze.
2528 /// \param Cand provides the policy and current best candidate.
2529 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2530 /// \param Zone describes the scheduled zone that we are extending.
2531 /// \param RPTracker describes reg pressure within the scheduled zone.
2532 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2533 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2534 SchedCandidate &TryCand,
2535 SchedBoundary &Zone,
2536 const RegPressureTracker &RPTracker,
2537 RegPressureTracker &TempTracker) {
2539 if (DAG->isTrackingPressure()) {
2540 // Always initialize TryCand's RPDelta.
2542 TempTracker.getMaxDownwardPressureDelta(
2543 TryCand.SU->getInstr(),
2545 DAG->getRegionCriticalPSets(),
2546 DAG->getRegPressure().MaxSetPressure);
2549 if (VerifyScheduling) {
2550 TempTracker.getMaxUpwardPressureDelta(
2551 TryCand.SU->getInstr(),
2552 &DAG->getPressureDiff(TryCand.SU),
2554 DAG->getRegionCriticalPSets(),
2555 DAG->getRegPressure().MaxSetPressure);
2558 RPTracker.getUpwardPressureDelta(
2559 TryCand.SU->getInstr(),
2560 DAG->getPressureDiff(TryCand.SU),
2562 DAG->getRegionCriticalPSets(),
2563 DAG->getRegPressure().MaxSetPressure);
2567 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2568 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2569 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2570 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
2572 // Initialize the candidate if needed.
2573 if (!Cand.isValid()) {
2574 TryCand.Reason = NodeOrder;
2578 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2579 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2580 TryCand, Cand, PhysRegCopy))
2583 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2584 // invalid; convert it to INT_MAX to give it lowest priority.
2585 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2586 Cand.RPDelta.Excess,
2587 TryCand, Cand, RegExcess))
2590 // Avoid increasing the max critical pressure in the scheduled region.
2591 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2592 Cand.RPDelta.CriticalMax,
2593 TryCand, Cand, RegCritical))
2596 // For loops that are acyclic path limited, aggressively schedule for latency.
2597 // This can result in very long dependence chains scheduled in sequence, so
2598 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
2599 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
2600 && tryLatency(TryCand, Cand, Zone))
2603 // Prioritize instructions that read unbuffered resources by stall cycles.
2604 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2605 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2608 // Keep clustered nodes together to encourage downstream peephole
2609 // optimizations which may reduce resource requirements.
2611 // This is a best effort to set things up for a post-RA pass. Optimizations
2612 // like generating loads of multiple registers should ideally be done within
2613 // the scheduler pass by combining the loads during DAG postprocessing.
2614 const SUnit *NextClusterSU =
2615 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2616 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2617 TryCand, Cand, Cluster))
2620 // Weak edges are for clustering and other constraints.
2621 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2622 getWeakLeft(Cand.SU, Zone.isTop()),
2623 TryCand, Cand, Weak)) {
2626 // Avoid increasing the max pressure of the entire region.
2627 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2628 Cand.RPDelta.CurrentMax,
2629 TryCand, Cand, RegMax))
2632 // Avoid critical resource consumption and balance the schedule.
2633 TryCand.initResourceDelta(DAG, SchedModel);
2634 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2635 TryCand, Cand, ResourceReduce))
2637 if (tryGreater(TryCand.ResDelta.DemandedResources,
2638 Cand.ResDelta.DemandedResources,
2639 TryCand, Cand, ResourceDemand))
2642 // Avoid serializing long latency dependence chains.
2643 // For acyclic path limited loops, latency was already checked above.
2644 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2645 && tryLatency(TryCand, Cand, Zone)) {
2649 // Prefer immediate defs/users of the last scheduled instruction. This is a
2650 // local pressure avoidance strategy that also makes the machine code
2652 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
2653 TryCand, Cand, NextDefUse))
2656 // Fall through to original instruction order.
2657 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2658 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2659 TryCand.Reason = NodeOrder;
2663 /// Pick the best candidate from the queue.
2665 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2666 /// DAG building. To adjust for the current scheduling location we need to
2667 /// maintain the number of vreg uses remaining to be top-scheduled.
2668 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2669 const RegPressureTracker &RPTracker,
2670 SchedCandidate &Cand) {
2671 ReadyQueue &Q = Zone.Available;
2675 // getMaxPressureDelta temporarily modifies the tracker.
2676 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2678 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2680 SchedCandidate TryCand(Cand.Policy);
2682 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2683 if (TryCand.Reason != NoCand) {
2684 // Initialize resource delta if needed in case future heuristics query it.
2685 if (TryCand.ResDelta == SchedResourceDelta())
2686 TryCand.initResourceDelta(DAG, SchedModel);
2687 Cand.setBest(TryCand);
2688 DEBUG(traceCandidate(Cand));
2693 /// Pick the best candidate node from either the top or bottom queue.
2694 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2695 // Schedule as far as possible in the direction of no choice. This is most
2696 // efficient, but also provides the best heuristics for CriticalPSets.
2697 if (SUnit *SU = Bot.pickOnlyChoice()) {
2699 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2702 if (SUnit *SU = Top.pickOnlyChoice()) {
2704 DEBUG(dbgs() << "Pick Top NOCAND\n");
2707 CandPolicy NoPolicy;
2708 SchedCandidate BotCand(NoPolicy);
2709 SchedCandidate TopCand(NoPolicy);
2710 // Set the bottom-up policy based on the state of the current bottom zone and
2711 // the instructions outside the zone, including the top zone.
2712 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
2713 // Set the top-down policy based on the state of the current top zone and
2714 // the instructions outside the zone, including the bottom zone.
2715 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
2717 // Prefer bottom scheduling when heuristics are silent.
2718 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2719 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2721 // If either Q has a single candidate that provides the least increase in
2722 // Excess pressure, we can immediately schedule from that Q.
2724 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2725 // affects picking from either Q. If scheduling in one direction must
2726 // increase pressure for one of the excess PSets, then schedule in that
2727 // direction first to provide more freedom in the other direction.
2728 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2729 || (BotCand.Reason == RegCritical
2730 && !BotCand.isRepeat(RegCritical)))
2733 tracePick(BotCand, IsTopNode);
2736 // Check if the top Q has a better candidate.
2737 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2738 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2740 // Choose the queue with the most important (lowest enum) reason.
2741 if (TopCand.Reason < BotCand.Reason) {
2743 tracePick(TopCand, IsTopNode);
2746 // Otherwise prefer the bottom candidate, in node order if all else failed.
2748 tracePick(BotCand, IsTopNode);
2752 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2753 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2754 if (DAG->top() == DAG->bottom()) {
2755 assert(Top.Available.empty() && Top.Pending.empty() &&
2756 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2761 if (RegionPolicy.OnlyTopDown) {
2762 SU = Top.pickOnlyChoice();
2764 CandPolicy NoPolicy;
2765 SchedCandidate TopCand(NoPolicy);
2766 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2767 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2768 tracePick(TopCand, true);
2773 else if (RegionPolicy.OnlyBottomUp) {
2774 SU = Bot.pickOnlyChoice();
2776 CandPolicy NoPolicy;
2777 SchedCandidate BotCand(NoPolicy);
2778 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2779 assert(BotCand.Reason != NoCand && "failed to find a candidate");
2780 tracePick(BotCand, false);
2786 SU = pickNodeBidirectional(IsTopNode);
2788 } while (SU->isScheduled);
2790 if (SU->isTopReady())
2791 Top.removeReady(SU);
2792 if (SU->isBottomReady())
2793 Bot.removeReady(SU);
2795 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2799 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2801 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2804 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2806 // Find already scheduled copies with a single physreg dependence and move
2807 // them just above the scheduled instruction.
2808 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2810 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2812 SUnit *DepSU = I->getSUnit();
2813 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2815 MachineInstr *Copy = DepSU->getInstr();
2816 if (!Copy->isCopy())
2818 DEBUG(dbgs() << " Rescheduling physreg copy ";
2819 I->getSUnit()->dump(DAG));
2820 DAG->moveInstruction(Copy, InsertPos);
2824 /// Update the scheduler's state after scheduling a node. This is the same node
2825 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
2826 /// update it's state based on the current cycle before MachineSchedStrategy
2829 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2830 /// them here. See comments in biasPhysRegCopy.
2831 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2833 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2835 if (SU->hasPhysRegUses)
2836 reschedulePhysRegCopies(SU, true);
2839 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
2841 if (SU->hasPhysRegDefs)
2842 reschedulePhysRegCopies(SU, false);
2846 /// Create the standard converging machine scheduler. This will be used as the
2847 /// default scheduler if the target does not set a default.
2848 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
2849 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
2850 // Register DAG post-processors.
2852 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2853 // data and pass it to later mutations. Have a single mutation that gathers
2854 // the interesting nodes in one pass.
2855 DAG->addMutation(make_unique<CopyConstrain>(DAG->TII, DAG->TRI));
2856 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
2857 DAG->addMutation(make_unique<LoadClusterMutation>(DAG->TII, DAG->TRI));
2858 if (EnableMacroFusion)
2859 DAG->addMutation(make_unique<MacroFusion>(DAG->TII));
2863 static MachineSchedRegistry
2864 GenericSchedRegistry("converge", "Standard converging scheduler.",
2865 createGenericSchedLive);
2867 //===----------------------------------------------------------------------===//
2868 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
2869 //===----------------------------------------------------------------------===//
2871 void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
2873 SchedModel = DAG->getSchedModel();
2876 Rem.init(DAG, SchedModel);
2877 Top.init(DAG, SchedModel, &Rem);
2880 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
2881 // or are disabled, then these HazardRecs will be disabled.
2882 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2883 const TargetMachine &TM = DAG->MF.getTarget();
2884 if (!Top.HazardRec) {
2886 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2891 void PostGenericScheduler::registerRoots() {
2892 Rem.CriticalPath = DAG->ExitSU.getDepth();
2894 // Some roots may not feed into ExitSU. Check all of them in case.
2895 for (SmallVectorImpl<SUnit*>::const_iterator
2896 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
2897 if ((*I)->getDepth() > Rem.CriticalPath)
2898 Rem.CriticalPath = (*I)->getDepth();
2900 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2903 /// Apply a set of heursitics to a new candidate for PostRA scheduling.
2905 /// \param Cand provides the policy and current best candidate.
2906 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2907 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
2908 SchedCandidate &TryCand) {
2910 // Initialize the candidate if needed.
2911 if (!Cand.isValid()) {
2912 TryCand.Reason = NodeOrder;
2916 // Prioritize instructions that read unbuffered resources by stall cycles.
2917 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
2918 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2921 // Avoid critical resource consumption and balance the schedule.
2922 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2923 TryCand, Cand, ResourceReduce))
2925 if (tryGreater(TryCand.ResDelta.DemandedResources,
2926 Cand.ResDelta.DemandedResources,
2927 TryCand, Cand, ResourceDemand))
2930 // Avoid serializing long latency dependence chains.
2931 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
2935 // Fall through to original instruction order.
2936 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
2937 TryCand.Reason = NodeOrder;
2940 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
2941 ReadyQueue &Q = Top.Available;
2945 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2946 SchedCandidate TryCand(Cand.Policy);
2948 TryCand.initResourceDelta(DAG, SchedModel);
2949 tryCandidate(Cand, TryCand);
2950 if (TryCand.Reason != NoCand) {
2951 Cand.setBest(TryCand);
2952 DEBUG(traceCandidate(Cand));
2957 /// Pick the next node to schedule.
2958 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
2959 if (DAG->top() == DAG->bottom()) {
2960 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
2965 SU = Top.pickOnlyChoice();
2967 CandPolicy NoPolicy;
2968 SchedCandidate TopCand(NoPolicy);
2969 // Set the top-down policy based on the state of the current top zone and
2970 // the instructions outside the zone, including the bottom zone.
2971 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
2972 pickNodeFromQueue(TopCand);
2973 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2974 tracePick(TopCand, true);
2977 } while (SU->isScheduled);
2980 Top.removeReady(SU);
2982 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2986 /// Called after ScheduleDAGMI has scheduled an instruction and updated
2987 /// scheduled/remaining flags in the DAG nodes.
2988 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2989 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2993 /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
2994 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
2995 return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C), /*IsPostRA=*/true);
2998 //===----------------------------------------------------------------------===//
2999 // ILP Scheduler. Currently for experimental analysis of heuristics.
3000 //===----------------------------------------------------------------------===//
3003 /// \brief Order nodes by the ILP metric.
3005 const SchedDFSResult *DFSResult;
3006 const BitVector *ScheduledTrees;
3009 ILPOrder(bool MaxILP)
3010 : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
3012 /// \brief Apply a less-than relation on node priority.
3014 /// (Return true if A comes after B in the Q.)
3015 bool operator()(const SUnit *A, const SUnit *B) const {
3016 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3017 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3018 if (SchedTreeA != SchedTreeB) {
3019 // Unscheduled trees have lower priority.
3020 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3021 return ScheduledTrees->test(SchedTreeB);
3023 // Trees with shallower connections have have lower priority.
3024 if (DFSResult->getSubtreeLevel(SchedTreeA)
3025 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3026 return DFSResult->getSubtreeLevel(SchedTreeA)
3027 < DFSResult->getSubtreeLevel(SchedTreeB);
3031 return DFSResult->getILP(A) < DFSResult->getILP(B);
3033 return DFSResult->getILP(A) > DFSResult->getILP(B);
3037 /// \brief Schedule based on the ILP metric.
3038 class ILPScheduler : public MachineSchedStrategy {
3039 ScheduleDAGMILive *DAG;
3042 std::vector<SUnit*> ReadyQ;
3044 ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
3046 void initialize(ScheduleDAGMI *dag) override {
3047 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3048 DAG = static_cast<ScheduleDAGMILive*>(dag);
3049 DAG->computeDFSResult();
3050 Cmp.DFSResult = DAG->getDFSResult();
3051 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3055 void registerRoots() override {
3056 // Restore the heap in ReadyQ with the updated DFS results.
3057 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3060 /// Implement MachineSchedStrategy interface.
3061 /// -----------------------------------------
3063 /// Callback to select the highest priority node from the ready Q.
3064 SUnit *pickNode(bool &IsTopNode) override {
3065 if (ReadyQ.empty()) return nullptr;
3066 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3067 SUnit *SU = ReadyQ.back();
3070 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3071 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3072 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3073 << DAG->getDFSResult()->getSubtreeLevel(
3074 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3075 << "Scheduling " << *SU->getInstr());
3079 /// \brief Scheduler callback to notify that a new subtree is scheduled.
3080 void scheduleTree(unsigned SubtreeID) override {
3081 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3084 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3085 /// DFSResults, and resort the priority Q.
3086 void schedNode(SUnit *SU, bool IsTopNode) override {
3087 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3090 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
3092 void releaseBottomNode(SUnit *SU) override {
3093 ReadyQ.push_back(SU);
3094 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3099 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3100 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
3102 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3103 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
3105 static MachineSchedRegistry ILPMaxRegistry(
3106 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3107 static MachineSchedRegistry ILPMinRegistry(
3108 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3110 //===----------------------------------------------------------------------===//
3111 // Machine Instruction Shuffler for Correctness Testing
3112 //===----------------------------------------------------------------------===//
3116 /// Apply a less-than relation on the node order, which corresponds to the
3117 /// instruction order prior to scheduling. IsReverse implements greater-than.
3118 template<bool IsReverse>
3120 bool operator()(SUnit *A, SUnit *B) const {
3122 return A->NodeNum > B->NodeNum;
3124 return A->NodeNum < B->NodeNum;
3128 /// Reorder instructions as much as possible.
3129 class InstructionShuffler : public MachineSchedStrategy {
3133 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3134 // gives nodes with a higher number higher priority causing the latest
3135 // instructions to be scheduled first.
3136 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3138 // When scheduling bottom-up, use greater-than as the queue priority.
3139 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3142 InstructionShuffler(bool alternate, bool topdown)
3143 : IsAlternating(alternate), IsTopDown(topdown) {}
3145 void initialize(ScheduleDAGMI*) override {
3150 /// Implement MachineSchedStrategy interface.
3151 /// -----------------------------------------
3153 SUnit *pickNode(bool &IsTopNode) override {
3157 if (TopQ.empty()) return nullptr;
3160 } while (SU->isScheduled);
3165 if (BottomQ.empty()) return nullptr;
3168 } while (SU->isScheduled);
3172 IsTopDown = !IsTopDown;
3176 void schedNode(SUnit *SU, bool IsTopNode) override {}
3178 void releaseTopNode(SUnit *SU) override {
3181 void releaseBottomNode(SUnit *SU) override {
3187 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3188 bool Alternate = !ForceTopDown && !ForceBottomUp;
3189 bool TopDown = !ForceBottomUp;
3190 assert((TopDown || !ForceTopDown) &&
3191 "-misched-topdown incompatible with -misched-bottomup");
3192 return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
3194 static MachineSchedRegistry ShufflerRegistry(
3195 "shuffle", "Shuffle machine instructions alternating directions",
3196 createInstructionShuffler);
3199 //===----------------------------------------------------------------------===//
3200 // GraphWriter support for ScheduleDAGMILive.
3201 //===----------------------------------------------------------------------===//
3206 template<> struct GraphTraits<
3207 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3210 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3212 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3214 static std::string getGraphName(const ScheduleDAG *G) {
3215 return G->MF.getName();
3218 static bool renderGraphFromBottomUp() {
3222 static bool isNodeHidden(const SUnit *Node) {
3223 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
3226 static bool hasNodeAddressLabel(const SUnit *Node,
3227 const ScheduleDAG *Graph) {
3231 /// If you want to override the dot attributes printed for a particular
3232 /// edge, override this method.
3233 static std::string getEdgeAttributes(const SUnit *Node,
3235 const ScheduleDAG *Graph) {
3236 if (EI.isArtificialDep())
3237 return "color=cyan,style=dashed";
3239 return "color=blue,style=dashed";
3243 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3245 raw_string_ostream SS(Str);
3246 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3247 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3248 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3249 SS << "SU:" << SU->NodeNum;
3251 SS << " I:" << DFS->getNumInstrs(SU);
3254 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3255 return G->getGraphNodeLabel(SU);
3258 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3259 std::string Str("shape=Mrecord");
3260 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3261 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3262 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3264 Str += ",style=filled,fillcolor=\"#";
3265 Str += DOT::getColorString(DFS->getSubtreeID(N));
3274 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3275 /// rendered using 'dot'.
3277 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3279 ViewGraph(this, Name, false, Title);
3281 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3282 << "systems with Graphviz or gv!\n";
3286 /// Out-of-line implementation with no arguments is handy for gdb.
3287 void ScheduleDAGMI::viewGraph() {
3288 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());