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 #define DEBUG_TYPE "misched"
17 #include "llvm/CodeGen/MachineScheduler.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/PriorityQueue.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.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"
36 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
37 cl::desc("Force top-down list scheduling"));
38 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
39 cl::desc("Force bottom-up list scheduling"));
43 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
44 cl::desc("Pop up a window to show MISched dags after they are processed"));
46 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
47 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
49 static bool ViewMISchedDAGs = false;
52 // Experimental heuristics
53 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
54 cl::desc("Enable load clustering."), cl::init(true));
56 // Experimental heuristics
57 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
58 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
60 // DAG subtrees must have at least this many nodes.
61 static const unsigned MinSubtreeSize = 8;
63 //===----------------------------------------------------------------------===//
64 // Machine Instruction Scheduling Pass and Registry
65 //===----------------------------------------------------------------------===//
67 MachineSchedContext::MachineSchedContext():
68 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
69 RegClassInfo = new RegisterClassInfo();
72 MachineSchedContext::~MachineSchedContext() {
77 /// MachineScheduler runs after coalescing and before register allocation.
78 class MachineScheduler : public MachineSchedContext,
79 public MachineFunctionPass {
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
85 virtual void releaseMemory() {}
87 virtual bool runOnMachineFunction(MachineFunction&);
89 virtual void print(raw_ostream &O, const Module* = 0) const;
91 static char ID; // Class identification, replacement for typeinfo
95 char MachineScheduler::ID = 0;
97 char &llvm::MachineSchedulerID = MachineScheduler::ID;
99 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
100 "Machine Instruction Scheduler", false, false)
101 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
102 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
103 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
104 INITIALIZE_PASS_END(MachineScheduler, "misched",
105 "Machine Instruction Scheduler", false, false)
107 MachineScheduler::MachineScheduler()
108 : MachineFunctionPass(ID) {
109 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
112 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.setPreservesCFG();
114 AU.addRequiredID(MachineDominatorsID);
115 AU.addRequired<MachineLoopInfo>();
116 AU.addRequired<AliasAnalysis>();
117 AU.addRequired<TargetPassConfig>();
118 AU.addRequired<SlotIndexes>();
119 AU.addPreserved<SlotIndexes>();
120 AU.addRequired<LiveIntervals>();
121 AU.addPreserved<LiveIntervals>();
122 MachineFunctionPass::getAnalysisUsage(AU);
125 MachinePassRegistry MachineSchedRegistry::Registry;
127 /// A dummy default scheduler factory indicates whether the scheduler
128 /// is overridden on the command line.
129 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
133 /// MachineSchedOpt allows command line selection of the scheduler.
134 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
135 RegisterPassParser<MachineSchedRegistry> >
136 MachineSchedOpt("misched",
137 cl::init(&useDefaultMachineSched), cl::Hidden,
138 cl::desc("Machine instruction scheduler to use"));
140 static MachineSchedRegistry
141 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
142 useDefaultMachineSched);
144 /// Forward declare the standard machine scheduler. This will be used as the
145 /// default scheduler if the target does not set a default.
146 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
149 /// Decrement this iterator until reaching the top or a non-debug instr.
150 static MachineBasicBlock::iterator
151 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
152 assert(I != Beg && "reached the top of the region, cannot decrement");
154 if (!I->isDebugValue())
160 /// If this iterator is a debug value, increment until reaching the End or a
161 /// non-debug instruction.
162 static MachineBasicBlock::iterator
163 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
164 for(; I != End; ++I) {
165 if (!I->isDebugValue())
171 /// Top-level MachineScheduler pass driver.
173 /// Visit blocks in function order. Divide each block into scheduling regions
174 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
175 /// consistent with the DAG builder, which traverses the interior of the
176 /// scheduling regions bottom-up.
178 /// This design avoids exposing scheduling boundaries to the DAG builder,
179 /// simplifying the DAG builder's support for "special" target instructions.
180 /// At the same time the design allows target schedulers to operate across
181 /// scheduling boundaries, for example to bundle the boudary instructions
182 /// without reordering them. This creates complexity, because the target
183 /// scheduler must update the RegionBegin and RegionEnd positions cached by
184 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
185 /// design would be to split blocks at scheduling boundaries, but LLVM has a
186 /// general bias against block splitting purely for implementation simplicity.
187 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
188 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
190 // Initialize the context of the pass.
192 MLI = &getAnalysis<MachineLoopInfo>();
193 MDT = &getAnalysis<MachineDominatorTree>();
194 PassConfig = &getAnalysis<TargetPassConfig>();
195 AA = &getAnalysis<AliasAnalysis>();
197 LIS = &getAnalysis<LiveIntervals>();
198 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
200 RegClassInfo->runOnMachineFunction(*MF);
202 // Select the scheduler, or set the default.
203 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
204 if (Ctor == useDefaultMachineSched) {
205 // Get the default scheduler set by the target.
206 Ctor = MachineSchedRegistry::getDefault();
208 Ctor = createConvergingSched;
209 MachineSchedRegistry::setDefault(Ctor);
212 // Instantiate the selected scheduler.
213 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
215 // Visit all machine basic blocks.
217 // TODO: Visit blocks in global postorder or postorder within the bottom-up
218 // loop tree. Then we can optionally compute global RegPressure.
219 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
220 MBB != MBBEnd; ++MBB) {
222 Scheduler->startBlock(MBB);
224 // Break the block into scheduling regions [I, RegionEnd), and schedule each
225 // region as soon as it is discovered. RegionEnd points the scheduling
226 // boundary at the bottom of the region. The DAG does not include RegionEnd,
227 // but the region does (i.e. the next RegionEnd is above the previous
228 // RegionBegin). If the current block has no terminator then RegionEnd ==
229 // MBB->end() for the bottom region.
231 // The Scheduler may insert instructions during either schedule() or
232 // exitRegion(), even for empty regions. So the local iterators 'I' and
233 // 'RegionEnd' are invalid across these calls.
234 unsigned RemainingInstrs = MBB->size();
235 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
236 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
238 // Avoid decrementing RegionEnd for blocks with no terminator.
239 if (RegionEnd != MBB->end()
240 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
242 // Count the boundary instruction.
246 // The next region starts above the previous region. Look backward in the
247 // instruction stream until we find the nearest boundary.
248 MachineBasicBlock::iterator I = RegionEnd;
249 for(;I != MBB->begin(); --I, --RemainingInstrs) {
250 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
253 // Notify the scheduler of the region, even if we may skip scheduling
254 // it. Perhaps it still needs to be bundled.
255 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
257 // Skip empty scheduling regions (0 or 1 schedulable instructions).
258 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
259 // Close the current region. Bundle the terminator if needed.
260 // This invalidates 'RegionEnd' and 'I'.
261 Scheduler->exitRegion();
264 DEBUG(dbgs() << "********** MI Scheduling **********\n");
265 DEBUG(dbgs() << MF->getName()
266 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
267 << "\n From: " << *I << " To: ";
268 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
269 else dbgs() << "End";
270 dbgs() << " Remaining: " << RemainingInstrs << "\n");
272 // Schedule a region: possibly reorder instructions.
273 // This invalidates 'RegionEnd' and 'I'.
274 Scheduler->schedule();
276 // Close the current region.
277 Scheduler->exitRegion();
279 // Scheduling has invalidated the current iterator 'I'. Ask the
280 // scheduler for the top of it's scheduled region.
281 RegionEnd = Scheduler->begin();
283 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
284 Scheduler->finishBlock();
286 Scheduler->finalizeSchedule();
287 DEBUG(LIS->print(dbgs()));
291 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
295 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
296 void ReadyQueue::dump() {
297 dbgs() << Name << ": ";
298 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
299 dbgs() << Queue[i]->NodeNum << " ";
304 //===----------------------------------------------------------------------===//
305 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
307 //===----------------------------------------------------------------------===//
309 ScheduleDAGMI::~ScheduleDAGMI() {
311 DeleteContainerPointers(Mutations);
315 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
316 if (SuccSU != &ExitSU) {
317 // Do not use WillCreateCycle, it assumes SD scheduling.
318 // If Pred is reachable from Succ, then the edge creates a cycle.
319 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
321 Topo.AddPred(SuccSU, PredDep.getSUnit());
323 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
324 // Return true regardless of whether a new edge needed to be inserted.
328 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
329 /// NumPredsLeft reaches zero, release the successor node.
331 /// FIXME: Adjust SuccSU height based on MinLatency.
332 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
333 SUnit *SuccSU = SuccEdge->getSUnit();
335 if (SuccEdge->isWeak()) {
336 --SuccSU->WeakPredsLeft;
337 if (SuccEdge->isCluster())
338 NextClusterSucc = SuccSU;
342 if (SuccSU->NumPredsLeft == 0) {
343 dbgs() << "*** Scheduling failed! ***\n";
345 dbgs() << " has been released too many times!\n";
349 --SuccSU->NumPredsLeft;
350 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
351 SchedImpl->releaseTopNode(SuccSU);
354 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
355 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
356 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
358 releaseSucc(SU, &*I);
362 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
363 /// NumSuccsLeft reaches zero, release the predecessor node.
365 /// FIXME: Adjust PredSU height based on MinLatency.
366 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
367 SUnit *PredSU = PredEdge->getSUnit();
369 if (PredEdge->isWeak()) {
370 --PredSU->WeakSuccsLeft;
371 if (PredEdge->isCluster())
372 NextClusterPred = PredSU;
376 if (PredSU->NumSuccsLeft == 0) {
377 dbgs() << "*** Scheduling failed! ***\n";
379 dbgs() << " has been released too many times!\n";
383 --PredSU->NumSuccsLeft;
384 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
385 SchedImpl->releaseBottomNode(PredSU);
388 /// releasePredecessors - Call releasePred on each of SU's predecessors.
389 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
390 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
392 releasePred(SU, &*I);
396 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
397 MachineBasicBlock::iterator InsertPos) {
398 // Advance RegionBegin if the first instruction moves down.
399 if (&*RegionBegin == MI)
402 // Update the instruction stream.
403 BB->splice(InsertPos, BB, MI);
405 // Update LiveIntervals
406 LIS->handleMove(MI, /*UpdateFlags=*/true);
408 // Recede RegionBegin if an instruction moves above the first.
409 if (RegionBegin == InsertPos)
413 bool ScheduleDAGMI::checkSchedLimit() {
415 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
416 CurrentTop = CurrentBottom;
419 ++NumInstrsScheduled;
424 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
425 /// crossing a scheduling boundary. [begin, end) includes all instructions in
426 /// the region, including the boundary itself and single-instruction regions
427 /// that don't get scheduled.
428 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
429 MachineBasicBlock::iterator begin,
430 MachineBasicBlock::iterator end,
433 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
435 // For convenience remember the end of the liveness region.
437 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
440 // Setup the register pressure trackers for the top scheduled top and bottom
441 // scheduled regions.
442 void ScheduleDAGMI::initRegPressure() {
443 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
444 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
446 // Close the RPTracker to finalize live ins.
447 RPTracker.closeRegion();
449 DEBUG(RPTracker.getPressure().dump(TRI));
451 // Initialize the live ins and live outs.
452 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
453 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
455 // Close one end of the tracker so we can call
456 // getMaxUpward/DownwardPressureDelta before advancing across any
457 // instructions. This converts currently live regs into live ins/outs.
458 TopRPTracker.closeTop();
459 BotRPTracker.closeBottom();
461 // Account for liveness generated by the region boundary.
462 if (LiveRegionEnd != RegionEnd)
463 BotRPTracker.recede();
465 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
467 // Cache the list of excess pressure sets in this region. This will also track
468 // the max pressure in the scheduled code for these sets.
469 RegionCriticalPSets.clear();
470 const std::vector<unsigned> &RegionPressure =
471 RPTracker.getPressure().MaxSetPressure;
472 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
473 unsigned Limit = TRI->getRegPressureSetLimit(i);
474 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
476 << " Actual " << RegionPressure[i] << "\n");
477 if (RegionPressure[i] > Limit)
478 RegionCriticalPSets.push_back(PressureElement(i, 0));
480 DEBUG(dbgs() << "Excess PSets: ";
481 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
482 dbgs() << TRI->getRegPressureSetName(
483 RegionCriticalPSets[i].PSetID) << " ";
487 // FIXME: When the pressure tracker deals in pressure differences then we won't
488 // iterate over all RegionCriticalPSets[i].
490 updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
491 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
492 unsigned ID = RegionCriticalPSets[i].PSetID;
493 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
494 if ((int)NewMaxPressure[ID] > MaxUnits)
495 MaxUnits = NewMaxPressure[ID];
499 /// schedule - Called back from MachineScheduler::runOnMachineFunction
500 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
501 /// only includes instructions that have DAG nodes, not scheduling boundaries.
503 /// This is a skeletal driver, with all the functionality pushed into helpers,
504 /// so that it can be easilly extended by experimental schedulers. Generally,
505 /// implementing MachineSchedStrategy should be sufficient to implement a new
506 /// scheduling algorithm. However, if a scheduler further subclasses
507 /// ScheduleDAGMI then it will want to override this virtual method in order to
508 /// update any specialized state.
509 void ScheduleDAGMI::schedule() {
510 buildDAGWithRegPressure();
512 Topo.InitDAGTopologicalSorting();
516 SmallVector<SUnit*, 8> TopRoots, BotRoots;
517 findRootsAndBiasEdges(TopRoots, BotRoots);
519 // Initialize the strategy before modifying the DAG.
520 // This may initialize a DFSResult to be used for queue priority.
521 SchedImpl->initialize(this);
523 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
524 SUnits[su].dumpAll(this));
525 if (ViewMISchedDAGs) viewGraph();
527 // Initialize ready queues now that the DAG and priority data are finalized.
528 initQueues(TopRoots, BotRoots);
530 bool IsTopNode = false;
531 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
532 assert(!SU->isScheduled && "Node already scheduled");
533 if (!checkSchedLimit())
536 scheduleMI(SU, IsTopNode);
538 updateQueues(SU, IsTopNode);
540 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
545 unsigned BBNum = begin()->getParent()->getNumber();
546 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
552 /// Build the DAG and setup three register pressure trackers.
553 void ScheduleDAGMI::buildDAGWithRegPressure() {
554 // Initialize the register pressure tracker used by buildSchedGraph.
555 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
557 // Account for liveness generate by the region boundary.
558 if (LiveRegionEnd != RegionEnd)
561 // Build the DAG, and compute current register pressure.
562 buildSchedGraph(AA, &RPTracker);
564 // Initialize top/bottom trackers after computing region pressure.
568 /// Apply each ScheduleDAGMutation step in order.
569 void ScheduleDAGMI::postprocessDAG() {
570 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
571 Mutations[i]->apply(this);
575 void ScheduleDAGMI::computeDFSResult() {
577 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
579 ScheduledTrees.clear();
580 DFSResult->resize(SUnits.size());
581 DFSResult->compute(SUnits);
582 ScheduledTrees.resize(DFSResult->getNumSubtrees());
585 void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
586 SmallVectorImpl<SUnit*> &BotRoots) {
587 for (std::vector<SUnit>::iterator
588 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
590 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
592 // Order predecessors so DFSResult follows the critical path.
593 SU->biasCriticalPath();
595 // A SUnit is ready to top schedule if it has no predecessors.
596 if (!I->NumPredsLeft)
597 TopRoots.push_back(SU);
598 // A SUnit is ready to bottom schedule if it has no successors.
599 if (!I->NumSuccsLeft)
600 BotRoots.push_back(SU);
602 ExitSU.biasCriticalPath();
605 /// Identify DAG roots and setup scheduler queues.
606 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
607 ArrayRef<SUnit*> BotRoots) {
608 NextClusterSucc = NULL;
609 NextClusterPred = NULL;
611 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
613 // Nodes with unreleased weak edges can still be roots.
614 // Release top roots in forward order.
615 for (SmallVectorImpl<SUnit*>::const_iterator
616 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
617 SchedImpl->releaseTopNode(*I);
619 // Release bottom roots in reverse order so the higher priority nodes appear
620 // first. This is more natural and slightly more efficient.
621 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
622 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
623 SchedImpl->releaseBottomNode(*I);
626 releaseSuccessors(&EntrySU);
627 releasePredecessors(&ExitSU);
629 SchedImpl->registerRoots();
631 // Advance past initial DebugValues.
632 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
633 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
634 TopRPTracker.setPos(CurrentTop);
636 CurrentBottom = RegionEnd;
639 /// Move an instruction and update register pressure.
640 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
641 // Move the instruction to its new location in the instruction stream.
642 MachineInstr *MI = SU->getInstr();
645 assert(SU->isTopReady() && "node still has unscheduled dependencies");
646 if (&*CurrentTop == MI)
647 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
649 moveInstruction(MI, CurrentTop);
650 TopRPTracker.setPos(MI);
653 // Update top scheduled pressure.
654 TopRPTracker.advance();
655 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
656 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
659 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
660 MachineBasicBlock::iterator priorII =
661 priorNonDebug(CurrentBottom, CurrentTop);
663 CurrentBottom = priorII;
665 if (&*CurrentTop == MI) {
666 CurrentTop = nextIfDebug(++CurrentTop, priorII);
667 TopRPTracker.setPos(CurrentTop);
669 moveInstruction(MI, CurrentBottom);
672 // Update bottom scheduled pressure.
673 BotRPTracker.recede();
674 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
675 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
679 /// Update scheduler queues after scheduling an instruction.
680 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
681 // Release dependent instructions for scheduling.
683 releaseSuccessors(SU);
685 releasePredecessors(SU);
687 SU->isScheduled = true;
690 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
691 if (!ScheduledTrees.test(SubtreeID)) {
692 ScheduledTrees.set(SubtreeID);
693 DFSResult->scheduleTree(SubtreeID);
694 SchedImpl->scheduleTree(SubtreeID);
698 // Notify the scheduling strategy after updating the DAG.
699 SchedImpl->schedNode(SU, IsTopNode);
702 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
703 void ScheduleDAGMI::placeDebugValues() {
704 // If first instruction was a DBG_VALUE then put it back.
706 BB->splice(RegionBegin, BB, FirstDbgValue);
707 RegionBegin = FirstDbgValue;
710 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
711 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
712 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
713 MachineInstr *DbgValue = P.first;
714 MachineBasicBlock::iterator OrigPrevMI = P.second;
715 if (&*RegionBegin == DbgValue)
717 BB->splice(++OrigPrevMI, BB, DbgValue);
718 if (OrigPrevMI == llvm::prior(RegionEnd))
719 RegionEnd = DbgValue;
722 FirstDbgValue = NULL;
725 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
726 void ScheduleDAGMI::dumpSchedule() const {
727 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
728 if (SUnit *SU = getSUnit(&(*MI)))
731 dbgs() << "Missing SUnit\n";
736 //===----------------------------------------------------------------------===//
737 // LoadClusterMutation - DAG post-processing to cluster loads.
738 //===----------------------------------------------------------------------===//
741 /// \brief Post-process the DAG to create cluster edges between neighboring
743 class LoadClusterMutation : public ScheduleDAGMutation {
748 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
749 : SU(su), BaseReg(reg), Offset(ofs) {}
751 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
752 const LoadClusterMutation::LoadInfo &RHS);
754 const TargetInstrInfo *TII;
755 const TargetRegisterInfo *TRI;
757 LoadClusterMutation(const TargetInstrInfo *tii,
758 const TargetRegisterInfo *tri)
759 : TII(tii), TRI(tri) {}
761 virtual void apply(ScheduleDAGMI *DAG);
763 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
767 bool LoadClusterMutation::LoadInfoLess(
768 const LoadClusterMutation::LoadInfo &LHS,
769 const LoadClusterMutation::LoadInfo &RHS) {
770 if (LHS.BaseReg != RHS.BaseReg)
771 return LHS.BaseReg < RHS.BaseReg;
772 return LHS.Offset < RHS.Offset;
775 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
776 ScheduleDAGMI *DAG) {
777 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
778 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
779 SUnit *SU = Loads[Idx];
782 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
783 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
785 if (LoadRecords.size() < 2)
787 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
788 unsigned ClusterLength = 1;
789 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
790 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
795 SUnit *SUa = LoadRecords[Idx].SU;
796 SUnit *SUb = LoadRecords[Idx+1].SU;
797 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
798 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
800 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
801 << SUb->NodeNum << ")\n");
802 // Copy successor edges from SUa to SUb. Interleaving computation
803 // dependent on SUa can prevent load combining due to register reuse.
804 // Predecessor edges do not need to be copied from SUb to SUa since nearby
805 // loads should have effectively the same inputs.
806 for (SUnit::const_succ_iterator
807 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
808 if (SI->getSUnit() == SUb)
810 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
811 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
820 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
821 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
822 // Map DAG NodeNum to store chain ID.
823 DenseMap<unsigned, unsigned> StoreChainIDs;
824 // Map each store chain to a set of dependent loads.
825 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
826 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
827 SUnit *SU = &DAG->SUnits[Idx];
828 if (!SU->getInstr()->mayLoad())
830 unsigned ChainPredID = DAG->SUnits.size();
831 for (SUnit::const_pred_iterator
832 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
834 ChainPredID = PI->getSUnit()->NodeNum;
838 // Check if this chain-like pred has been seen
839 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
840 unsigned NumChains = StoreChainDependents.size();
841 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
842 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
844 StoreChainDependents.resize(NumChains + 1);
845 StoreChainDependents[Result.first->second].push_back(SU);
847 // Iterate over the store chains.
848 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
849 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
852 //===----------------------------------------------------------------------===//
853 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
854 //===----------------------------------------------------------------------===//
857 /// \brief Post-process the DAG to create cluster edges between instructions
858 /// that may be fused by the processor into a single operation.
859 class MacroFusion : public ScheduleDAGMutation {
860 const TargetInstrInfo *TII;
862 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
864 virtual void apply(ScheduleDAGMI *DAG);
868 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
869 /// fused operations.
870 void MacroFusion::apply(ScheduleDAGMI *DAG) {
871 // For now, assume targets can only fuse with the branch.
872 MachineInstr *Branch = DAG->ExitSU.getInstr();
876 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
877 SUnit *SU = &DAG->SUnits[--Idx];
878 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
881 // Create a single weak edge from SU to ExitSU. The only effect is to cause
882 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
883 // need to copy predecessor edges from ExitSU to SU, since top-down
884 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
885 // of SU, we could create an artificial edge from the deepest root, but it
886 // hasn't been needed yet.
887 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
889 assert(Success && "No DAG nodes should be reachable from ExitSU");
891 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
896 //===----------------------------------------------------------------------===//
897 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
898 //===----------------------------------------------------------------------===//
901 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
903 class ConvergingScheduler : public MachineSchedStrategy {
905 /// Represent the type of SchedCandidate found within a single queue.
906 /// pickNodeBidirectional depends on these listed by decreasing priority.
908 NoCand, SingleExcess, SingleCritical, Cluster,
909 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
910 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
914 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
917 /// Policy for scheduling the next instruction in the candidate's zone.
920 unsigned ReduceResIdx;
921 unsigned DemandResIdx;
923 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
926 /// Status of an instruction's critical resource consumption.
927 struct SchedResourceDelta {
928 // Count critical resources in the scheduled region required by SU.
929 unsigned CritResources;
931 // Count critical resources from another region consumed by SU.
932 unsigned DemandedResources;
934 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
936 bool operator==(const SchedResourceDelta &RHS) const {
937 return CritResources == RHS.CritResources
938 && DemandedResources == RHS.DemandedResources;
940 bool operator!=(const SchedResourceDelta &RHS) const {
941 return !operator==(RHS);
945 /// Store the state used by ConvergingScheduler heuristics, required for the
946 /// lifetime of one invocation of pickNode().
947 struct SchedCandidate {
950 // The best SUnit candidate.
953 // The reason for this candidate.
956 // Register pressure values for the best candidate.
957 RegPressureDelta RPDelta;
959 // Critical resource consumption of the best candidate.
960 SchedResourceDelta ResDelta;
962 SchedCandidate(const CandPolicy &policy)
963 : Policy(policy), SU(NULL), Reason(NoCand) {}
965 bool isValid() const { return SU; }
967 // Copy the status of another candidate without changing policy.
968 void setBest(SchedCandidate &Best) {
969 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
971 Reason = Best.Reason;
972 RPDelta = Best.RPDelta;
973 ResDelta = Best.ResDelta;
976 void initResourceDelta(const ScheduleDAGMI *DAG,
977 const TargetSchedModel *SchedModel);
980 /// Summarize the unscheduled region.
981 struct SchedRemainder {
982 // Critical path through the DAG in expected latency.
983 unsigned CriticalPath;
985 // Unscheduled resources
986 SmallVector<unsigned, 16> RemainingCounts;
987 // Critical resource for the unscheduled zone.
989 // Number of micro-ops left to schedule.
990 unsigned RemainingMicroOps;
994 RemainingCounts.clear();
996 RemainingMicroOps = 0;
999 SchedRemainder() { reset(); }
1001 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
1003 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
1004 if (!SchedModel->hasInstrSchedModel())
1008 RemainingMicroOps * SchedModel->getMicroOpFactor(),
1009 RemainingCounts[CritResIdx]);
1013 /// Each Scheduling boundary is associated with ready queues. It tracks the
1014 /// current cycle in the direction of movement, and maintains the state
1015 /// of "hazards" and other interlocks at the current cycle.
1016 struct SchedBoundary {
1018 const TargetSchedModel *SchedModel;
1019 SchedRemainder *Rem;
1021 ReadyQueue Available;
1025 // For heuristics, keep a list of the nodes that immediately depend on the
1026 // most recently scheduled node.
1027 SmallPtrSet<const SUnit*, 8> NextSUs;
1029 ScheduleHazardRecognizer *HazardRec;
1032 unsigned IssueCount;
1034 /// MinReadyCycle - Cycle of the soonest available instruction.
1035 unsigned MinReadyCycle;
1037 // The expected latency of the critical path in this scheduled zone.
1038 unsigned ExpectedLatency;
1040 // Resources used in the scheduled zone beyond this boundary.
1041 SmallVector<unsigned, 16> ResourceCounts;
1043 // Cache the critical resources ID in this scheduled zone.
1044 unsigned CritResIdx;
1046 // Is the scheduled region resource limited vs. latency limited.
1047 bool IsResourceLimited;
1049 unsigned ExpectedCount;
1052 // Remember the greatest min operand latency.
1053 unsigned MaxMinLatency;
1059 CheckPending = false;
1064 MinReadyCycle = UINT_MAX;
1065 ExpectedLatency = 0;
1066 ResourceCounts.resize(1);
1067 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1069 IsResourceLimited = false;
1074 // Reserve a zero-count for invalid CritResIdx.
1075 ResourceCounts.resize(1);
1078 /// Pending queues extend the ready queues with the same ID and the
1079 /// PendingFlag set.
1080 SchedBoundary(unsigned ID, const Twine &Name):
1081 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1082 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1086 ~SchedBoundary() { delete HazardRec; }
1088 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1089 SchedRemainder *rem);
1091 bool isTop() const {
1092 return Available.getID() == ConvergingScheduler::TopQID;
1095 unsigned getUnscheduledLatency(SUnit *SU) const {
1097 return SU->getHeight();
1098 return SU->getDepth() + SU->Latency;
1101 unsigned getCriticalCount() const {
1102 return ResourceCounts[CritResIdx];
1105 bool checkHazard(SUnit *SU);
1107 void setLatencyPolicy(CandPolicy &Policy);
1109 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1113 void countResource(unsigned PIdx, unsigned Cycles);
1115 void bumpNode(SUnit *SU);
1117 void releasePending();
1119 void removeReady(SUnit *SU);
1121 SUnit *pickOnlyChoice();
1126 const TargetSchedModel *SchedModel;
1127 const TargetRegisterInfo *TRI;
1129 // State of the top and bottom scheduled instruction boundaries.
1135 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1142 ConvergingScheduler():
1143 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1145 virtual void initialize(ScheduleDAGMI *dag);
1147 virtual SUnit *pickNode(bool &IsTopNode);
1149 virtual void schedNode(SUnit *SU, bool IsTopNode);
1151 virtual void releaseTopNode(SUnit *SU);
1153 virtual void releaseBottomNode(SUnit *SU);
1155 virtual void registerRoots();
1159 ConvergingScheduler::SchedBoundary &CriticalZone,
1160 ConvergingScheduler::SchedCandidate &CriticalCand,
1161 ConvergingScheduler::SchedBoundary &OppositeZone,
1162 ConvergingScheduler::SchedCandidate &OppositeCand);
1164 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1165 ConvergingScheduler::SchedCandidate &BotCand);
1167 void tryCandidate(SchedCandidate &Cand,
1168 SchedCandidate &TryCand,
1169 SchedBoundary &Zone,
1170 const RegPressureTracker &RPTracker,
1171 RegPressureTracker &TempTracker);
1173 SUnit *pickNodeBidirectional(bool &IsTopNode);
1175 void pickNodeFromQueue(SchedBoundary &Zone,
1176 const RegPressureTracker &RPTracker,
1177 SchedCandidate &Candidate);
1180 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
1185 void ConvergingScheduler::SchedRemainder::
1186 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1188 if (!SchedModel->hasInstrSchedModel())
1190 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1191 for (std::vector<SUnit>::iterator
1192 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1193 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1194 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1195 for (TargetSchedModel::ProcResIter
1196 PI = SchedModel->getWriteProcResBegin(SC),
1197 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1198 unsigned PIdx = PI->ProcResourceIdx;
1199 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1200 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1203 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1204 PIdx != PEnd; ++PIdx) {
1205 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1206 >= (int)SchedModel->getLatencyFactor()) {
1212 void ConvergingScheduler::SchedBoundary::
1213 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1216 SchedModel = smodel;
1218 if (SchedModel->hasInstrSchedModel())
1219 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1222 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1224 SchedModel = DAG->getSchedModel();
1226 Rem.init(DAG, SchedModel);
1227 Top.init(DAG, SchedModel, &Rem);
1228 Bot.init(DAG, SchedModel, &Rem);
1230 DAG->computeDFSResult();
1232 // Initialize resource counts.
1234 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1235 // are disabled, then these HazardRecs will be disabled.
1236 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1237 const TargetMachine &TM = DAG->MF.getTarget();
1238 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1239 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1241 assert((!ForceTopDown || !ForceBottomUp) &&
1242 "-misched-topdown incompatible with -misched-bottomup");
1245 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1246 if (SU->isScheduled)
1249 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1251 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1252 unsigned MinLatency = I->getMinLatency();
1254 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
1256 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1257 SU->TopReadyCycle = PredReadyCycle + MinLatency;
1259 Top.releaseNode(SU, SU->TopReadyCycle);
1262 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1263 if (SU->isScheduled)
1266 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1268 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1272 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1273 unsigned MinLatency = I->getMinLatency();
1275 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
1277 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1278 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
1280 Bot.releaseNode(SU, SU->BotReadyCycle);
1283 void ConvergingScheduler::registerRoots() {
1284 Rem.CriticalPath = DAG->ExitSU.getDepth();
1285 // Some roots may not feed into ExitSU. Check all of them in case.
1286 for (std::vector<SUnit*>::const_iterator
1287 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1288 if ((*I)->getDepth() > Rem.CriticalPath)
1289 Rem.CriticalPath = (*I)->getDepth();
1291 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1294 /// Does this SU have a hazard within the current instruction group.
1296 /// The scheduler supports two modes of hazard recognition. The first is the
1297 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1298 /// supports highly complicated in-order reservation tables
1299 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1301 /// The second is a streamlined mechanism that checks for hazards based on
1302 /// simple counters that the scheduler itself maintains. It explicitly checks
1303 /// for instruction dispatch limitations, including the number of micro-ops that
1304 /// can dispatch per cycle.
1306 /// TODO: Also check whether the SU must start a new group.
1307 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1308 if (HazardRec->isEnabled())
1309 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1311 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1312 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1313 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1314 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1320 /// Compute the remaining latency to determine whether ILP should be increased.
1321 void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1322 // FIXME: compile time. In all, we visit four queues here one we should only
1323 // need to visit the one that was last popped if we cache the result.
1324 unsigned RemLatency = 0;
1325 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1327 unsigned L = getUnscheduledLatency(*I);
1331 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1333 unsigned L = getUnscheduledLatency(*I);
1337 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1338 if (RemLatency + ExpectedLatency >= CriticalPathLimit
1339 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1340 Policy.ReduceLatency = true;
1341 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
1345 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1346 unsigned ReadyCycle) {
1348 if (ReadyCycle < MinReadyCycle)
1349 MinReadyCycle = ReadyCycle;
1351 // Check for interlocks first. For the purpose of other heuristics, an
1352 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1353 if (ReadyCycle > CurrCycle || checkHazard(SU))
1358 // Record this node as an immediate dependent of the scheduled node.
1362 /// Move the boundary of scheduled code by one cycle.
1363 void ConvergingScheduler::SchedBoundary::bumpCycle() {
1364 unsigned Width = SchedModel->getIssueWidth();
1365 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
1367 unsigned NextCycle = CurrCycle + 1;
1368 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1369 if (MinReadyCycle > NextCycle) {
1371 NextCycle = MinReadyCycle;
1374 if (!HazardRec->isEnabled()) {
1375 // Bypass HazardRec virtual calls.
1376 CurrCycle = NextCycle;
1379 // Bypass getHazardType calls in case of long latency.
1380 for (; CurrCycle != NextCycle; ++CurrCycle) {
1382 HazardRec->AdvanceCycle();
1384 HazardRec->RecedeCycle();
1387 CheckPending = true;
1388 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1390 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
1391 << CurrCycle << '\n');
1394 /// Add the given processor resource to this scheduled zone.
1395 void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1397 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1398 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1399 << " +(" << Cycles << "x" << Factor
1400 << ") / " << SchedModel->getLatencyFactor() << '\n');
1402 unsigned Count = Factor * Cycles;
1403 ResourceCounts[PIdx] += Count;
1404 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1405 Rem->RemainingCounts[PIdx] -= Count;
1407 // Check if this resource exceeds the current critical resource by a full
1408 // cycle. If so, it becomes the critical resource.
1409 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1410 >= (int)SchedModel->getLatencyFactor()) {
1412 DEBUG(dbgs() << " *** Critical resource "
1413 << SchedModel->getProcResource(PIdx)->Name << " x"
1414 << ResourceCounts[PIdx] << '\n');
1418 /// Move the boundary of scheduled code by one SUnit.
1419 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1420 // Update the reservation table.
1421 if (HazardRec->isEnabled()) {
1422 if (!isTop() && SU->isCall) {
1423 // Calls are scheduled with their preceding instructions. For bottom-up
1424 // scheduling, clear the pipeline state before emitting.
1427 HazardRec->EmitInstruction(SU);
1429 // Update resource counts and critical resource.
1430 if (SchedModel->hasInstrSchedModel()) {
1431 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1432 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1433 for (TargetSchedModel::ProcResIter
1434 PI = SchedModel->getWriteProcResBegin(SC),
1435 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1436 countResource(PI->ProcResourceIdx, PI->Cycles);
1440 if (SU->getDepth() > ExpectedLatency)
1441 ExpectedLatency = SU->getDepth();
1444 if (SU->getHeight() > ExpectedLatency)
1445 ExpectedLatency = SU->getHeight();
1448 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1450 // Check the instruction group dispatch limit.
1451 // TODO: Check if this SU must end a dispatch group.
1452 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
1454 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1455 // issue width. However, we commonly reach the maximum. In this case
1456 // opportunistically bump the cycle to avoid uselessly checking everything in
1457 // the readyQ. Furthermore, a single instruction may produce more than one
1458 // cycle's worth of micro-ops.
1459 if (IssueCount >= SchedModel->getIssueWidth()) {
1460 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
1465 /// Release pending ready nodes in to the available queue. This makes them
1466 /// visible to heuristics.
1467 void ConvergingScheduler::SchedBoundary::releasePending() {
1468 // If the available queue is empty, it is safe to reset MinReadyCycle.
1469 if (Available.empty())
1470 MinReadyCycle = UINT_MAX;
1472 // Check to see if any of the pending instructions are ready to issue. If
1473 // so, add them to the available queue.
1474 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1475 SUnit *SU = *(Pending.begin()+i);
1476 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1478 if (ReadyCycle < MinReadyCycle)
1479 MinReadyCycle = ReadyCycle;
1481 if (ReadyCycle > CurrCycle)
1484 if (checkHazard(SU))
1488 Pending.remove(Pending.begin()+i);
1491 DEBUG(if (!Pending.empty()) Pending.dump());
1492 CheckPending = false;
1495 /// Remove SU from the ready set for this boundary.
1496 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1497 if (Available.isInQueue(SU))
1498 Available.remove(Available.find(SU));
1500 assert(Pending.isInQueue(SU) && "bad ready count");
1501 Pending.remove(Pending.find(SU));
1505 /// If this queue only has one ready candidate, return it. As a side effect,
1506 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1507 /// one node is ready. If multiple instructions are ready, return NULL.
1508 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1512 if (IssueCount > 0) {
1513 // Defer any ready instrs that now have a hazard.
1514 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1515 if (checkHazard(*I)) {
1517 I = Available.remove(I);
1523 for (unsigned i = 0; Available.empty(); ++i) {
1524 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1525 "permanent hazard"); (void)i;
1529 if (Available.size() == 1)
1530 return *Available.begin();
1534 /// Record the candidate policy for opposite zones with different critical
1537 /// If the CriticalZone is latency limited, don't force a policy for the
1538 /// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
1539 void ConvergingScheduler::balanceZones(
1540 ConvergingScheduler::SchedBoundary &CriticalZone,
1541 ConvergingScheduler::SchedCandidate &CriticalCand,
1542 ConvergingScheduler::SchedBoundary &OppositeZone,
1543 ConvergingScheduler::SchedCandidate &OppositeCand) {
1545 if (!CriticalZone.IsResourceLimited)
1547 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
1549 SchedRemainder *Rem = CriticalZone.Rem;
1551 // If the critical zone is overconsuming a resource relative to the
1552 // remainder, try to reduce it.
1553 unsigned RemainingCritCount =
1554 Rem->RemainingCounts[CriticalZone.CritResIdx];
1555 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
1556 > (int)SchedModel->getLatencyFactor()) {
1557 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1558 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1559 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1562 // If the other zone is underconsuming a resource relative to the full zone,
1563 // try to increase it.
1564 unsigned OppositeCount =
1565 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1566 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1567 > (int)SchedModel->getLatencyFactor()) {
1568 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1569 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1570 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1575 /// Determine if the scheduled zones exceed resource limits or critical path and
1576 /// set each candidate's ReduceHeight policy accordingly.
1577 void ConvergingScheduler::checkResourceLimits(
1578 ConvergingScheduler::SchedCandidate &TopCand,
1579 ConvergingScheduler::SchedCandidate &BotCand) {
1581 // Set ReduceLatency to true if needed.
1582 Bot.setLatencyPolicy(BotCand.Policy);
1583 Top.setLatencyPolicy(TopCand.Policy);
1585 // Handle resource-limited regions.
1586 if (Top.IsResourceLimited && Bot.IsResourceLimited
1587 && Top.CritResIdx == Bot.CritResIdx) {
1588 // If the scheduled critical resource in both zones is no longer the
1589 // critical remaining resource, attempt to reduce resource height both ways.
1590 if (Top.CritResIdx != Rem.CritResIdx) {
1591 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1592 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1593 DEBUG(dbgs() << "Reduce scheduled "
1594 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1598 // Handle latency-limited regions.
1599 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1600 // If the total scheduled expected latency exceeds the region's critical
1601 // path then reduce latency both ways.
1603 // Just because a zone is not resource limited does not mean it is latency
1604 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1605 // to exceed expected latency.
1606 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1607 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1608 TopCand.Policy.ReduceLatency = true;
1609 BotCand.Policy.ReduceLatency = true;
1610 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1611 << " + " << Bot.ExpectedLatency << '\n');
1615 // The critical resource is different in each zone, so request balancing.
1617 // Compute the cost of each zone.
1618 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1619 Top.ExpectedCount = std::max(
1620 Top.getCriticalCount(),
1621 Top.ExpectedCount * SchedModel->getLatencyFactor());
1622 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1623 Bot.ExpectedCount = std::max(
1624 Bot.getCriticalCount(),
1625 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1627 balanceZones(Top, TopCand, Bot, BotCand);
1628 balanceZones(Bot, BotCand, Top, TopCand);
1631 void ConvergingScheduler::SchedCandidate::
1632 initResourceDelta(const ScheduleDAGMI *DAG,
1633 const TargetSchedModel *SchedModel) {
1634 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1637 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1638 for (TargetSchedModel::ProcResIter
1639 PI = SchedModel->getWriteProcResBegin(SC),
1640 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1641 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1642 ResDelta.CritResources += PI->Cycles;
1643 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1644 ResDelta.DemandedResources += PI->Cycles;
1648 /// Return true if this heuristic determines order.
1649 static bool tryLess(unsigned TryVal, unsigned CandVal,
1650 ConvergingScheduler::SchedCandidate &TryCand,
1651 ConvergingScheduler::SchedCandidate &Cand,
1652 ConvergingScheduler::CandReason Reason) {
1653 if (TryVal < CandVal) {
1654 TryCand.Reason = Reason;
1657 if (TryVal > CandVal) {
1658 if (Cand.Reason > Reason)
1659 Cand.Reason = Reason;
1665 static bool tryGreater(unsigned TryVal, unsigned CandVal,
1666 ConvergingScheduler::SchedCandidate &TryCand,
1667 ConvergingScheduler::SchedCandidate &Cand,
1668 ConvergingScheduler::CandReason Reason) {
1669 if (TryVal > CandVal) {
1670 TryCand.Reason = Reason;
1673 if (TryVal < CandVal) {
1674 if (Cand.Reason > Reason)
1675 Cand.Reason = Reason;
1681 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1682 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1685 /// Apply a set of heursitics to a new candidate. Heuristics are currently
1686 /// hierarchical. This may be more efficient than a graduated cost model because
1687 /// we don't need to evaluate all aspects of the model for each node in the
1688 /// queue. But it's really done to make the heuristics easier to debug and
1689 /// statistically analyze.
1691 /// \param Cand provides the policy and current best candidate.
1692 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1693 /// \param Zone describes the scheduled zone that we are extending.
1694 /// \param RPTracker describes reg pressure within the scheduled zone.
1695 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
1696 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1697 SchedCandidate &TryCand,
1698 SchedBoundary &Zone,
1699 const RegPressureTracker &RPTracker,
1700 RegPressureTracker &TempTracker) {
1702 // Always initialize TryCand's RPDelta.
1703 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1704 DAG->getRegionCriticalPSets(),
1705 DAG->getRegPressure().MaxSetPressure);
1707 // Initialize the candidate if needed.
1708 if (!Cand.isValid()) {
1709 TryCand.Reason = NodeOrder;
1712 // Avoid exceeding the target's limit.
1713 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1714 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1716 if (Cand.Reason == SingleExcess)
1717 Cand.Reason = MultiPressure;
1719 // Avoid increasing the max critical pressure in the scheduled region.
1720 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1721 Cand.RPDelta.CriticalMax.UnitIncrease,
1722 TryCand, Cand, SingleCritical))
1724 if (Cand.Reason == SingleCritical)
1725 Cand.Reason = MultiPressure;
1727 // Keep clustered nodes together to encourage downstream peephole
1728 // optimizations which may reduce resource requirements.
1730 // This is a best effort to set things up for a post-RA pass. Optimizations
1731 // like generating loads of multiple registers should ideally be done within
1732 // the scheduler pass by combining the loads during DAG postprocessing.
1733 const SUnit *NextClusterSU =
1734 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1735 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1736 TryCand, Cand, Cluster))
1738 // Currently, weak edges are for clustering, so we hard-code that reason.
1739 // However, deferring the current TryCand will not change Cand's reason.
1740 CandReason OrigReason = Cand.Reason;
1741 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1742 getWeakLeft(Cand.SU, Zone.isTop()),
1743 TryCand, Cand, Cluster)) {
1744 Cand.Reason = OrigReason;
1747 // Avoid critical resource consumption and balance the schedule.
1748 TryCand.initResourceDelta(DAG, SchedModel);
1749 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1750 TryCand, Cand, ResourceReduce))
1752 if (tryGreater(TryCand.ResDelta.DemandedResources,
1753 Cand.ResDelta.DemandedResources,
1754 TryCand, Cand, ResourceDemand))
1757 // Avoid serializing long latency dependence chains.
1758 if (Cand.Policy.ReduceLatency) {
1760 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1761 > Zone.ExpectedCount) {
1762 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1763 TryCand, Cand, TopDepthReduce))
1766 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1767 TryCand, Cand, TopPathReduce))
1771 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1772 > Zone.ExpectedCount) {
1773 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1774 TryCand, Cand, BotHeightReduce))
1777 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1778 TryCand, Cand, BotPathReduce))
1783 // Avoid increasing the max pressure of the entire region.
1784 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1785 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1787 if (Cand.Reason == SingleMax)
1788 Cand.Reason = MultiPressure;
1790 // Prefer immediate defs/users of the last scheduled instruction. This is a
1791 // nice pressure avoidance strategy that also conserves the processor's
1792 // register renaming resources and keeps the machine code readable.
1793 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1794 TryCand, Cand, NextDefUse))
1797 // Fall through to original instruction order.
1798 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1799 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1800 TryCand.Reason = NodeOrder;
1804 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1805 /// more desirable than RHS from scheduling standpoint.
1806 static bool compareRPDelta(const RegPressureDelta &LHS,
1807 const RegPressureDelta &RHS) {
1808 // Compare each component of pressure in decreasing order of importance
1809 // without checking if any are valid. Invalid PressureElements are assumed to
1810 // have UnitIncrease==0, so are neutral.
1812 // Avoid increasing the max critical pressure in the scheduled region.
1813 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1814 DEBUG(dbgs() << "RP excess top - bot: "
1815 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
1816 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1818 // Avoid increasing the max critical pressure in the scheduled region.
1819 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1820 DEBUG(dbgs() << "RP critical top - bot: "
1821 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1823 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1825 // Avoid increasing the max pressure of the entire region.
1826 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1827 DEBUG(dbgs() << "RP current top - bot: "
1828 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1830 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1836 const char *ConvergingScheduler::getReasonStr(
1837 ConvergingScheduler::CandReason Reason) {
1839 case NoCand: return "NOCAND ";
1840 case SingleExcess: return "REG-EXCESS";
1841 case SingleCritical: return "REG-CRIT ";
1842 case Cluster: return "CLUSTER ";
1843 case SingleMax: return "REG-MAX ";
1844 case MultiPressure: return "REG-MULTI ";
1845 case ResourceReduce: return "RES-REDUCE";
1846 case ResourceDemand: return "RES-DEMAND";
1847 case TopDepthReduce: return "TOP-DEPTH ";
1848 case TopPathReduce: return "TOP-PATH ";
1849 case BotHeightReduce:return "BOT-HEIGHT";
1850 case BotPathReduce: return "BOT-PATH ";
1851 case NextDefUse: return "DEF-USE ";
1852 case NodeOrder: return "ORDER ";
1854 llvm_unreachable("Unknown reason!");
1857 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1858 const SchedBoundary &Zone) {
1859 const char *Label = getReasonStr(Cand.Reason);
1861 unsigned ResIdx = 0;
1862 unsigned Latency = 0;
1863 switch (Cand.Reason) {
1867 P = Cand.RPDelta.Excess;
1869 case SingleCritical:
1870 P = Cand.RPDelta.CriticalMax;
1873 P = Cand.RPDelta.CurrentMax;
1875 case ResourceReduce:
1876 ResIdx = Cand.Policy.ReduceResIdx;
1878 case ResourceDemand:
1879 ResIdx = Cand.Policy.DemandResIdx;
1881 case TopDepthReduce:
1882 Latency = Cand.SU->getDepth();
1885 Latency = Cand.SU->getHeight();
1887 case BotHeightReduce:
1888 Latency = Cand.SU->getHeight();
1891 Latency = Cand.SU->getDepth();
1894 dbgs() << Label << " " << Zone.Available.getName() << " ";
1896 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1901 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1905 dbgs() << Latency << " cycles ";
1912 /// Pick the best candidate from the top queue.
1914 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1915 /// DAG building. To adjust for the current scheduling location we need to
1916 /// maintain the number of vreg uses remaining to be top-scheduled.
1917 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1918 const RegPressureTracker &RPTracker,
1919 SchedCandidate &Cand) {
1920 ReadyQueue &Q = Zone.Available;
1924 // getMaxPressureDelta temporarily modifies the tracker.
1925 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1927 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
1929 SchedCandidate TryCand(Cand.Policy);
1931 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1932 if (TryCand.Reason != NoCand) {
1933 // Initialize resource delta if needed in case future heuristics query it.
1934 if (TryCand.ResDelta == SchedResourceDelta())
1935 TryCand.initResourceDelta(DAG, SchedModel);
1936 Cand.setBest(TryCand);
1937 DEBUG(traceCandidate(Cand, Zone));
1942 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1944 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1945 << " SU(" << Cand.SU->NodeNum << ") "
1946 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
1949 /// Pick the best candidate node from either the top or bottom queue.
1950 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
1951 // Schedule as far as possible in the direction of no choice. This is most
1952 // efficient, but also provides the best heuristics for CriticalPSets.
1953 if (SUnit *SU = Bot.pickOnlyChoice()) {
1957 if (SUnit *SU = Top.pickOnlyChoice()) {
1961 CandPolicy NoPolicy;
1962 SchedCandidate BotCand(NoPolicy);
1963 SchedCandidate TopCand(NoPolicy);
1964 checkResourceLimits(TopCand, BotCand);
1966 // Prefer bottom scheduling when heuristics are silent.
1967 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1968 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
1970 // If either Q has a single candidate that provides the least increase in
1971 // Excess pressure, we can immediately schedule from that Q.
1973 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1974 // affects picking from either Q. If scheduling in one direction must
1975 // increase pressure for one of the excess PSets, then schedule in that
1976 // direction first to provide more freedom in the other direction.
1977 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
1979 tracePick(BotCand, IsTopNode);
1982 // Check if the top Q has a better candidate.
1983 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1984 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1986 // If either Q has a single candidate that minimizes pressure above the
1987 // original region's pressure pick it.
1988 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1989 if (TopCand.Reason < BotCand.Reason) {
1991 tracePick(TopCand, IsTopNode);
1995 tracePick(BotCand, IsTopNode);
1998 // Check for a salient pressure difference and pick the best from either side.
1999 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
2001 tracePick(TopCand, IsTopNode);
2004 // Otherwise prefer the bottom candidate, in node order if all else failed.
2005 if (TopCand.Reason < BotCand.Reason) {
2007 tracePick(TopCand, IsTopNode);
2011 tracePick(BotCand, IsTopNode);
2015 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2016 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2017 if (DAG->top() == DAG->bottom()) {
2018 assert(Top.Available.empty() && Top.Pending.empty() &&
2019 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2025 SU = Top.pickOnlyChoice();
2027 CandPolicy NoPolicy;
2028 SchedCandidate TopCand(NoPolicy);
2029 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2030 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2035 else if (ForceBottomUp) {
2036 SU = Bot.pickOnlyChoice();
2038 CandPolicy NoPolicy;
2039 SchedCandidate BotCand(NoPolicy);
2040 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2041 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2047 SU = pickNodeBidirectional(IsTopNode);
2049 } while (SU->isScheduled);
2051 if (SU->isTopReady())
2052 Top.removeReady(SU);
2053 if (SU->isBottomReady())
2054 Bot.removeReady(SU);
2056 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2057 << " Scheduling Instruction in cycle "
2058 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2063 /// Update the scheduler's state after scheduling a node. This is the same node
2064 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2065 /// it's state based on the current cycle before MachineSchedStrategy does.
2066 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2068 SU->TopReadyCycle = Top.CurrCycle;
2072 SU->BotReadyCycle = Bot.CurrCycle;
2077 /// Create the standard converging machine scheduler. This will be used as the
2078 /// default scheduler if the target does not set a default.
2079 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2080 assert((!ForceTopDown || !ForceBottomUp) &&
2081 "-misched-topdown incompatible with -misched-bottomup");
2082 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2083 // Register DAG post-processors.
2084 if (EnableLoadCluster)
2085 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2086 if (EnableMacroFusion)
2087 DAG->addMutation(new MacroFusion(DAG->TII));
2090 static MachineSchedRegistry
2091 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2092 createConvergingSched);
2094 //===----------------------------------------------------------------------===//
2095 // ILP Scheduler. Currently for experimental analysis of heuristics.
2096 //===----------------------------------------------------------------------===//
2099 /// \brief Order nodes by the ILP metric.
2101 const SchedDFSResult *DFSResult;
2102 const BitVector *ScheduledTrees;
2105 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2107 /// \brief Apply a less-than relation on node priority.
2109 /// (Return true if A comes after B in the Q.)
2110 bool operator()(const SUnit *A, const SUnit *B) const {
2111 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2112 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2113 if (SchedTreeA != SchedTreeB) {
2114 // Unscheduled trees have lower priority.
2115 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2116 return ScheduledTrees->test(SchedTreeB);
2118 // Trees with shallower connections have have lower priority.
2119 if (DFSResult->getSubtreeLevel(SchedTreeA)
2120 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2121 return DFSResult->getSubtreeLevel(SchedTreeA)
2122 < DFSResult->getSubtreeLevel(SchedTreeB);
2126 return DFSResult->getILP(A) < DFSResult->getILP(B);
2128 return DFSResult->getILP(A) > DFSResult->getILP(B);
2132 /// \brief Schedule based on the ILP metric.
2133 class ILPScheduler : public MachineSchedStrategy {
2134 /// In case all subtrees are eventually connected to a common root through
2135 /// data dependence (e.g. reduction), place an upper limit on their size.
2137 /// FIXME: A subtree limit is generally good, but in the situation commented
2138 /// above, where multiple similar subtrees feed a common root, we should
2139 /// only split at a point where the resulting subtrees will be balanced.
2140 /// (a motivating test case must be found).
2141 static const unsigned SubtreeLimit = 16;
2146 std::vector<SUnit*> ReadyQ;
2148 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2150 virtual void initialize(ScheduleDAGMI *dag) {
2152 DAG->computeDFSResult();
2153 Cmp.DFSResult = DAG->getDFSResult();
2154 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
2158 virtual void registerRoots() {
2159 // Restore the heap in ReadyQ with the updated DFS results.
2160 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2163 /// Implement MachineSchedStrategy interface.
2164 /// -----------------------------------------
2166 /// Callback to select the highest priority node from the ready Q.
2167 virtual SUnit *pickNode(bool &IsTopNode) {
2168 if (ReadyQ.empty()) return NULL;
2169 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2170 SUnit *SU = ReadyQ.back();
2173 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2175 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2176 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2177 << DAG->getDFSResult()->getSubtreeLevel(
2178 DAG->getDFSResult()->getSubtreeID(SU)) << '\n');
2182 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2183 virtual void scheduleTree(unsigned SubtreeID) {
2184 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2187 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2188 /// DFSResults, and resort the priority Q.
2189 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2190 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2193 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2195 virtual void releaseBottomNode(SUnit *SU) {
2196 ReadyQ.push_back(SU);
2197 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2202 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2203 return new ScheduleDAGMI(C, new ILPScheduler(true));
2205 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2206 return new ScheduleDAGMI(C, new ILPScheduler(false));
2208 static MachineSchedRegistry ILPMaxRegistry(
2209 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2210 static MachineSchedRegistry ILPMinRegistry(
2211 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2213 //===----------------------------------------------------------------------===//
2214 // Machine Instruction Shuffler for Correctness Testing
2215 //===----------------------------------------------------------------------===//
2219 /// Apply a less-than relation on the node order, which corresponds to the
2220 /// instruction order prior to scheduling. IsReverse implements greater-than.
2221 template<bool IsReverse>
2223 bool operator()(SUnit *A, SUnit *B) const {
2225 return A->NodeNum > B->NodeNum;
2227 return A->NodeNum < B->NodeNum;
2231 /// Reorder instructions as much as possible.
2232 class InstructionShuffler : public MachineSchedStrategy {
2236 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2237 // gives nodes with a higher number higher priority causing the latest
2238 // instructions to be scheduled first.
2239 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2241 // When scheduling bottom-up, use greater-than as the queue priority.
2242 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2245 InstructionShuffler(bool alternate, bool topdown)
2246 : IsAlternating(alternate), IsTopDown(topdown) {}
2248 virtual void initialize(ScheduleDAGMI *) {
2253 /// Implement MachineSchedStrategy interface.
2254 /// -----------------------------------------
2256 virtual SUnit *pickNode(bool &IsTopNode) {
2260 if (TopQ.empty()) return NULL;
2263 } while (SU->isScheduled);
2268 if (BottomQ.empty()) return NULL;
2271 } while (SU->isScheduled);
2275 IsTopDown = !IsTopDown;
2279 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2281 virtual void releaseTopNode(SUnit *SU) {
2284 virtual void releaseBottomNode(SUnit *SU) {
2290 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2291 bool Alternate = !ForceTopDown && !ForceBottomUp;
2292 bool TopDown = !ForceBottomUp;
2293 assert((TopDown || !ForceTopDown) &&
2294 "-misched-topdown incompatible with -misched-bottomup");
2295 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2297 static MachineSchedRegistry ShufflerRegistry(
2298 "shuffle", "Shuffle machine instructions alternating directions",
2299 createInstructionShuffler);
2302 //===----------------------------------------------------------------------===//
2303 // GraphWriter support for ScheduleDAGMI.
2304 //===----------------------------------------------------------------------===//
2309 template<> struct GraphTraits<
2310 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2313 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2315 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2317 static std::string getGraphName(const ScheduleDAG *G) {
2318 return G->MF.getName();
2321 static bool renderGraphFromBottomUp() {
2325 static bool isNodeHidden(const SUnit *Node) {
2326 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2329 static bool hasNodeAddressLabel(const SUnit *Node,
2330 const ScheduleDAG *Graph) {
2334 /// If you want to override the dot attributes printed for a particular
2335 /// edge, override this method.
2336 static std::string getEdgeAttributes(const SUnit *Node,
2338 const ScheduleDAG *Graph) {
2339 if (EI.isArtificialDep())
2340 return "color=cyan,style=dashed";
2342 return "color=blue,style=dashed";
2346 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2348 raw_string_ostream SS(Str);
2349 SS << "SU(" << SU->NodeNum << ')';
2352 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2353 return G->getGraphNodeLabel(SU);
2356 static std::string getNodeAttributes(const SUnit *N,
2357 const ScheduleDAG *Graph) {
2358 std::string Str("shape=Mrecord");
2359 const SchedDFSResult *DFS =
2360 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2362 Str += ",style=filled,fillcolor=\"#";
2363 Str += DOT::getColorString(DFS->getSubtreeID(N));
2372 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2373 /// rendered using 'dot'.
2375 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2377 ViewGraph(this, Name, false, Title);
2379 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2380 << "systems with Graphviz or gv!\n";
2384 /// Out-of-line implementation with no arguments is handy for gdb.
2385 void ScheduleDAGMI::viewGraph() {
2386 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());