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() << "\n From: " << *I << " To: ";
267 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
268 else dbgs() << "End";
269 dbgs() << " Remaining: " << RemainingInstrs << "\n");
271 // Schedule a region: possibly reorder instructions.
272 // This invalidates 'RegionEnd' and 'I'.
273 Scheduler->schedule();
275 // Close the current region.
276 Scheduler->exitRegion();
278 // Scheduling has invalidated the current iterator 'I'. Ask the
279 // scheduler for the top of it's scheduled region.
280 RegionEnd = Scheduler->begin();
282 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
283 Scheduler->finishBlock();
285 Scheduler->finalizeSchedule();
286 DEBUG(LIS->print(dbgs()));
290 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
294 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
295 void ReadyQueue::dump() {
296 dbgs() << Name << ": ";
297 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
298 dbgs() << Queue[i]->NodeNum << " ";
303 //===----------------------------------------------------------------------===//
304 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
306 //===----------------------------------------------------------------------===//
308 ScheduleDAGMI::~ScheduleDAGMI() {
310 DeleteContainerPointers(Mutations);
314 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
315 if (SuccSU != &ExitSU) {
316 // Do not use WillCreateCycle, it assumes SD scheduling.
317 // If Pred is reachable from Succ, then the edge creates a cycle.
318 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
320 Topo.AddPred(SuccSU, PredDep.getSUnit());
322 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
323 // Return true regardless of whether a new edge needed to be inserted.
327 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
328 /// NumPredsLeft reaches zero, release the successor node.
330 /// FIXME: Adjust SuccSU height based on MinLatency.
331 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
332 SUnit *SuccSU = SuccEdge->getSUnit();
334 if (SuccEdge->isWeak()) {
335 --SuccSU->WeakPredsLeft;
336 if (SuccEdge->isCluster())
337 NextClusterSucc = SuccSU;
341 if (SuccSU->NumPredsLeft == 0) {
342 dbgs() << "*** Scheduling failed! ***\n";
344 dbgs() << " has been released too many times!\n";
348 --SuccSU->NumPredsLeft;
349 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
350 SchedImpl->releaseTopNode(SuccSU);
353 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
354 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
355 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
357 releaseSucc(SU, &*I);
361 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
362 /// NumSuccsLeft reaches zero, release the predecessor node.
364 /// FIXME: Adjust PredSU height based on MinLatency.
365 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
366 SUnit *PredSU = PredEdge->getSUnit();
368 if (PredEdge->isWeak()) {
369 --PredSU->WeakSuccsLeft;
370 if (PredEdge->isCluster())
371 NextClusterPred = PredSU;
375 if (PredSU->NumSuccsLeft == 0) {
376 dbgs() << "*** Scheduling failed! ***\n";
378 dbgs() << " has been released too many times!\n";
382 --PredSU->NumSuccsLeft;
383 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
384 SchedImpl->releaseBottomNode(PredSU);
387 /// releasePredecessors - Call releasePred on each of SU's predecessors.
388 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
389 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
391 releasePred(SU, &*I);
395 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
396 MachineBasicBlock::iterator InsertPos) {
397 // Advance RegionBegin if the first instruction moves down.
398 if (&*RegionBegin == MI)
401 // Update the instruction stream.
402 BB->splice(InsertPos, BB, MI);
404 // Update LiveIntervals
405 LIS->handleMove(MI, /*UpdateFlags=*/true);
407 // Recede RegionBegin if an instruction moves above the first.
408 if (RegionBegin == InsertPos)
412 bool ScheduleDAGMI::checkSchedLimit() {
414 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
415 CurrentTop = CurrentBottom;
418 ++NumInstrsScheduled;
423 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
424 /// crossing a scheduling boundary. [begin, end) includes all instructions in
425 /// the region, including the boundary itself and single-instruction regions
426 /// that don't get scheduled.
427 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
428 MachineBasicBlock::iterator begin,
429 MachineBasicBlock::iterator end,
432 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
434 // For convenience remember the end of the liveness region.
436 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
439 // Setup the register pressure trackers for the top scheduled top and bottom
440 // scheduled regions.
441 void ScheduleDAGMI::initRegPressure() {
442 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
443 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
445 // Close the RPTracker to finalize live ins.
446 RPTracker.closeRegion();
448 DEBUG(RPTracker.getPressure().dump(TRI));
450 // Initialize the live ins and live outs.
451 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
452 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
454 // Close one end of the tracker so we can call
455 // getMaxUpward/DownwardPressureDelta before advancing across any
456 // instructions. This converts currently live regs into live ins/outs.
457 TopRPTracker.closeTop();
458 BotRPTracker.closeBottom();
460 // Account for liveness generated by the region boundary.
461 if (LiveRegionEnd != RegionEnd)
462 BotRPTracker.recede();
464 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
466 // Cache the list of excess pressure sets in this region. This will also track
467 // the max pressure in the scheduled code for these sets.
468 RegionCriticalPSets.clear();
469 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
470 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
471 unsigned Limit = TRI->getRegPressureSetLimit(i);
472 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
474 << " Actual " << RegionPressure[i] << "\n");
475 if (RegionPressure[i] > Limit)
476 RegionCriticalPSets.push_back(PressureElement(i, 0));
478 DEBUG(dbgs() << "Excess PSets: ";
479 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
480 dbgs() << TRI->getRegPressureSetName(
481 RegionCriticalPSets[i].PSetID) << " ";
485 // FIXME: When the pressure tracker deals in pressure differences then we won't
486 // iterate over all RegionCriticalPSets[i].
488 updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
489 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
490 unsigned ID = RegionCriticalPSets[i].PSetID;
491 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
492 if ((int)NewMaxPressure[ID] > MaxUnits)
493 MaxUnits = NewMaxPressure[ID];
497 /// schedule - Called back from MachineScheduler::runOnMachineFunction
498 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
499 /// only includes instructions that have DAG nodes, not scheduling boundaries.
501 /// This is a skeletal driver, with all the functionality pushed into helpers,
502 /// so that it can be easilly extended by experimental schedulers. Generally,
503 /// implementing MachineSchedStrategy should be sufficient to implement a new
504 /// scheduling algorithm. However, if a scheduler further subclasses
505 /// ScheduleDAGMI then it will want to override this virtual method in order to
506 /// update any specialized state.
507 void ScheduleDAGMI::schedule() {
508 buildDAGWithRegPressure();
510 Topo.InitDAGTopologicalSorting();
514 SmallVector<SUnit*, 8> TopRoots, BotRoots;
515 findRootsAndBiasEdges(TopRoots, BotRoots);
517 // Initialize the strategy before modifying the DAG.
518 // This may initialize a DFSResult to be used for queue priority.
519 SchedImpl->initialize(this);
521 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
522 SUnits[su].dumpAll(this));
523 if (ViewMISchedDAGs) viewGraph();
525 // Initialize ready queues now that the DAG and priority data are finalized.
526 initQueues(TopRoots, BotRoots);
528 bool IsTopNode = false;
529 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
530 assert(!SU->isScheduled && "Node already scheduled");
531 if (!checkSchedLimit())
534 scheduleMI(SU, IsTopNode);
536 updateQueues(SU, IsTopNode);
538 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
543 unsigned BBNum = begin()->getParent()->getNumber();
544 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
550 /// Build the DAG and setup three register pressure trackers.
551 void ScheduleDAGMI::buildDAGWithRegPressure() {
552 // Initialize the register pressure tracker used by buildSchedGraph.
553 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
555 // Account for liveness generate by the region boundary.
556 if (LiveRegionEnd != RegionEnd)
559 // Build the DAG, and compute current register pressure.
560 buildSchedGraph(AA, &RPTracker);
562 // Initialize top/bottom trackers after computing region pressure.
566 /// Apply each ScheduleDAGMutation step in order.
567 void ScheduleDAGMI::postprocessDAG() {
568 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
569 Mutations[i]->apply(this);
573 void ScheduleDAGMI::computeDFSResult() {
575 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
577 ScheduledTrees.clear();
578 DFSResult->resize(SUnits.size());
579 DFSResult->compute(SUnits);
580 ScheduledTrees.resize(DFSResult->getNumSubtrees());
583 void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
584 SmallVectorImpl<SUnit*> &BotRoots) {
585 for (std::vector<SUnit>::iterator
586 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
589 // Order predecessors so DFSResult follows the critical path.
590 SU->biasCriticalPath();
592 // A SUnit is ready to top schedule if it has no predecessors.
593 if (!I->NumPredsLeft && SU != &EntrySU)
594 TopRoots.push_back(SU);
595 // A SUnit is ready to bottom schedule if it has no successors.
596 if (!I->NumSuccsLeft && SU != &ExitSU)
597 BotRoots.push_back(SU);
601 /// Identify DAG roots and setup scheduler queues.
602 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
603 ArrayRef<SUnit*> BotRoots) {
604 NextClusterSucc = NULL;
605 NextClusterPred = NULL;
607 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
609 // Nodes with unreleased weak edges can still be roots.
610 // Release top roots in forward order.
611 for (SmallVectorImpl<SUnit*>::const_iterator
612 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
613 SchedImpl->releaseTopNode(*I);
615 // Release bottom roots in reverse order so the higher priority nodes appear
616 // first. This is more natural and slightly more efficient.
617 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
618 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
619 SchedImpl->releaseBottomNode(*I);
622 releaseSuccessors(&EntrySU);
623 releasePredecessors(&ExitSU);
625 SchedImpl->registerRoots();
627 // Advance past initial DebugValues.
628 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
629 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
630 TopRPTracker.setPos(CurrentTop);
632 CurrentBottom = RegionEnd;
635 /// Move an instruction and update register pressure.
636 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
637 // Move the instruction to its new location in the instruction stream.
638 MachineInstr *MI = SU->getInstr();
641 assert(SU->isTopReady() && "node still has unscheduled dependencies");
642 if (&*CurrentTop == MI)
643 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
645 moveInstruction(MI, CurrentTop);
646 TopRPTracker.setPos(MI);
649 // Update top scheduled pressure.
650 TopRPTracker.advance();
651 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
652 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
655 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
656 MachineBasicBlock::iterator priorII =
657 priorNonDebug(CurrentBottom, CurrentTop);
659 CurrentBottom = priorII;
661 if (&*CurrentTop == MI) {
662 CurrentTop = nextIfDebug(++CurrentTop, priorII);
663 TopRPTracker.setPos(CurrentTop);
665 moveInstruction(MI, CurrentBottom);
668 // Update bottom scheduled pressure.
669 BotRPTracker.recede();
670 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
671 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
675 /// Update scheduler queues after scheduling an instruction.
676 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
677 // Release dependent instructions for scheduling.
679 releaseSuccessors(SU);
681 releasePredecessors(SU);
683 SU->isScheduled = true;
686 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
687 if (!ScheduledTrees.test(SubtreeID)) {
688 ScheduledTrees.set(SubtreeID);
689 DFSResult->scheduleTree(SubtreeID);
690 SchedImpl->scheduleTree(SubtreeID);
694 // Notify the scheduling strategy after updating the DAG.
695 SchedImpl->schedNode(SU, IsTopNode);
698 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
699 void ScheduleDAGMI::placeDebugValues() {
700 // If first instruction was a DBG_VALUE then put it back.
702 BB->splice(RegionBegin, BB, FirstDbgValue);
703 RegionBegin = FirstDbgValue;
706 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
707 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
708 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
709 MachineInstr *DbgValue = P.first;
710 MachineBasicBlock::iterator OrigPrevMI = P.second;
711 if (&*RegionBegin == DbgValue)
713 BB->splice(++OrigPrevMI, BB, DbgValue);
714 if (OrigPrevMI == llvm::prior(RegionEnd))
715 RegionEnd = DbgValue;
718 FirstDbgValue = NULL;
721 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
722 void ScheduleDAGMI::dumpSchedule() const {
723 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
724 if (SUnit *SU = getSUnit(&(*MI)))
727 dbgs() << "Missing SUnit\n";
732 //===----------------------------------------------------------------------===//
733 // LoadClusterMutation - DAG post-processing to cluster loads.
734 //===----------------------------------------------------------------------===//
737 /// \brief Post-process the DAG to create cluster edges between neighboring
739 class LoadClusterMutation : public ScheduleDAGMutation {
744 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
745 : SU(su), BaseReg(reg), Offset(ofs) {}
747 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
748 const LoadClusterMutation::LoadInfo &RHS);
750 const TargetInstrInfo *TII;
751 const TargetRegisterInfo *TRI;
753 LoadClusterMutation(const TargetInstrInfo *tii,
754 const TargetRegisterInfo *tri)
755 : TII(tii), TRI(tri) {}
757 virtual void apply(ScheduleDAGMI *DAG);
759 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
763 bool LoadClusterMutation::LoadInfoLess(
764 const LoadClusterMutation::LoadInfo &LHS,
765 const LoadClusterMutation::LoadInfo &RHS) {
766 if (LHS.BaseReg != RHS.BaseReg)
767 return LHS.BaseReg < RHS.BaseReg;
768 return LHS.Offset < RHS.Offset;
771 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
772 ScheduleDAGMI *DAG) {
773 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
774 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
775 SUnit *SU = Loads[Idx];
778 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
779 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
781 if (LoadRecords.size() < 2)
783 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
784 unsigned ClusterLength = 1;
785 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
786 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
791 SUnit *SUa = LoadRecords[Idx].SU;
792 SUnit *SUb = LoadRecords[Idx+1].SU;
793 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
794 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
796 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
797 << SUb->NodeNum << ")\n");
798 // Copy successor edges from SUa to SUb. Interleaving computation
799 // dependent on SUa can prevent load combining due to register reuse.
800 // Predecessor edges do not need to be copied from SUb to SUa since nearby
801 // loads should have effectively the same inputs.
802 for (SUnit::const_succ_iterator
803 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
804 if (SI->getSUnit() == SUb)
806 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
807 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
816 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
817 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
818 // Map DAG NodeNum to store chain ID.
819 DenseMap<unsigned, unsigned> StoreChainIDs;
820 // Map each store chain to a set of dependent loads.
821 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
822 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
823 SUnit *SU = &DAG->SUnits[Idx];
824 if (!SU->getInstr()->mayLoad())
826 unsigned ChainPredID = DAG->SUnits.size();
827 for (SUnit::const_pred_iterator
828 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
830 ChainPredID = PI->getSUnit()->NodeNum;
834 // Check if this chain-like pred has been seen
835 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
836 unsigned NumChains = StoreChainDependents.size();
837 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
838 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
840 StoreChainDependents.resize(NumChains + 1);
841 StoreChainDependents[Result.first->second].push_back(SU);
843 // Iterate over the store chains.
844 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
845 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
848 //===----------------------------------------------------------------------===//
849 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
850 //===----------------------------------------------------------------------===//
853 /// \brief Post-process the DAG to create cluster edges between instructions
854 /// that may be fused by the processor into a single operation.
855 class MacroFusion : public ScheduleDAGMutation {
856 const TargetInstrInfo *TII;
858 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
860 virtual void apply(ScheduleDAGMI *DAG);
864 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
865 /// fused operations.
866 void MacroFusion::apply(ScheduleDAGMI *DAG) {
867 // For now, assume targets can only fuse with the branch.
868 MachineInstr *Branch = DAG->ExitSU.getInstr();
872 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
873 SUnit *SU = &DAG->SUnits[--Idx];
874 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
877 // Create a single weak edge from SU to ExitSU. The only effect is to cause
878 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
879 // need to copy predecessor edges from ExitSU to SU, since top-down
880 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
881 // of SU, we could create an artificial edge from the deepest root, but it
882 // hasn't been needed yet.
883 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
885 assert(Success && "No DAG nodes should be reachable from ExitSU");
887 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
892 //===----------------------------------------------------------------------===//
893 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
894 //===----------------------------------------------------------------------===//
897 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
899 class ConvergingScheduler : public MachineSchedStrategy {
901 /// Represent the type of SchedCandidate found within a single queue.
902 /// pickNodeBidirectional depends on these listed by decreasing priority.
904 NoCand, SingleExcess, SingleCritical, Cluster,
905 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
906 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
910 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
913 /// Policy for scheduling the next instruction in the candidate's zone.
916 unsigned ReduceResIdx;
917 unsigned DemandResIdx;
919 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
922 /// Status of an instruction's critical resource consumption.
923 struct SchedResourceDelta {
924 // Count critical resources in the scheduled region required by SU.
925 unsigned CritResources;
927 // Count critical resources from another region consumed by SU.
928 unsigned DemandedResources;
930 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
932 bool operator==(const SchedResourceDelta &RHS) const {
933 return CritResources == RHS.CritResources
934 && DemandedResources == RHS.DemandedResources;
936 bool operator!=(const SchedResourceDelta &RHS) const {
937 return !operator==(RHS);
941 /// Store the state used by ConvergingScheduler heuristics, required for the
942 /// lifetime of one invocation of pickNode().
943 struct SchedCandidate {
946 // The best SUnit candidate.
949 // The reason for this candidate.
952 // Register pressure values for the best candidate.
953 RegPressureDelta RPDelta;
955 // Critical resource consumption of the best candidate.
956 SchedResourceDelta ResDelta;
958 SchedCandidate(const CandPolicy &policy)
959 : Policy(policy), SU(NULL), Reason(NoCand) {}
961 bool isValid() const { return SU; }
963 // Copy the status of another candidate without changing policy.
964 void setBest(SchedCandidate &Best) {
965 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
967 Reason = Best.Reason;
968 RPDelta = Best.RPDelta;
969 ResDelta = Best.ResDelta;
972 void initResourceDelta(const ScheduleDAGMI *DAG,
973 const TargetSchedModel *SchedModel);
976 /// Summarize the unscheduled region.
977 struct SchedRemainder {
978 // Critical path through the DAG in expected latency.
979 unsigned CriticalPath;
981 // Unscheduled resources
982 SmallVector<unsigned, 16> RemainingCounts;
983 // Critical resource for the unscheduled zone.
985 // Number of micro-ops left to schedule.
986 unsigned RemainingMicroOps;
990 RemainingCounts.clear();
992 RemainingMicroOps = 0;
995 SchedRemainder() { reset(); }
997 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
999 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
1000 if (!SchedModel->hasInstrSchedModel())
1004 RemainingMicroOps * SchedModel->getMicroOpFactor(),
1005 RemainingCounts[CritResIdx]);
1009 /// Each Scheduling boundary is associated with ready queues. It tracks the
1010 /// current cycle in the direction of movement, and maintains the state
1011 /// of "hazards" and other interlocks at the current cycle.
1012 struct SchedBoundary {
1014 const TargetSchedModel *SchedModel;
1015 SchedRemainder *Rem;
1017 ReadyQueue Available;
1021 // For heuristics, keep a list of the nodes that immediately depend on the
1022 // most recently scheduled node.
1023 SmallPtrSet<const SUnit*, 8> NextSUs;
1025 ScheduleHazardRecognizer *HazardRec;
1028 unsigned IssueCount;
1030 /// MinReadyCycle - Cycle of the soonest available instruction.
1031 unsigned MinReadyCycle;
1033 // The expected latency of the critical path in this scheduled zone.
1034 unsigned ExpectedLatency;
1036 // Resources used in the scheduled zone beyond this boundary.
1037 SmallVector<unsigned, 16> ResourceCounts;
1039 // Cache the critical resources ID in this scheduled zone.
1040 unsigned CritResIdx;
1042 // Is the scheduled region resource limited vs. latency limited.
1043 bool IsResourceLimited;
1045 unsigned ExpectedCount;
1048 // Remember the greatest min operand latency.
1049 unsigned MaxMinLatency;
1055 CheckPending = false;
1060 MinReadyCycle = UINT_MAX;
1061 ExpectedLatency = 0;
1062 ResourceCounts.resize(1);
1063 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1065 IsResourceLimited = false;
1070 // Reserve a zero-count for invalid CritResIdx.
1071 ResourceCounts.resize(1);
1074 /// Pending queues extend the ready queues with the same ID and the
1075 /// PendingFlag set.
1076 SchedBoundary(unsigned ID, const Twine &Name):
1077 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1078 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1082 ~SchedBoundary() { delete HazardRec; }
1084 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1085 SchedRemainder *rem);
1087 bool isTop() const {
1088 return Available.getID() == ConvergingScheduler::TopQID;
1091 unsigned getUnscheduledLatency(SUnit *SU) const {
1093 return SU->getHeight();
1094 return SU->getDepth() + SU->Latency;
1097 unsigned getCriticalCount() const {
1098 return ResourceCounts[CritResIdx];
1101 bool checkHazard(SUnit *SU);
1103 void setLatencyPolicy(CandPolicy &Policy);
1105 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1109 void countResource(unsigned PIdx, unsigned Cycles);
1111 void bumpNode(SUnit *SU);
1113 void releasePending();
1115 void removeReady(SUnit *SU);
1117 SUnit *pickOnlyChoice();
1122 const TargetSchedModel *SchedModel;
1123 const TargetRegisterInfo *TRI;
1125 // State of the top and bottom scheduled instruction boundaries.
1131 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1138 ConvergingScheduler():
1139 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1141 virtual void initialize(ScheduleDAGMI *dag);
1143 virtual SUnit *pickNode(bool &IsTopNode);
1145 virtual void schedNode(SUnit *SU, bool IsTopNode);
1147 virtual void releaseTopNode(SUnit *SU);
1149 virtual void releaseBottomNode(SUnit *SU);
1151 virtual void registerRoots();
1155 ConvergingScheduler::SchedBoundary &CriticalZone,
1156 ConvergingScheduler::SchedCandidate &CriticalCand,
1157 ConvergingScheduler::SchedBoundary &OppositeZone,
1158 ConvergingScheduler::SchedCandidate &OppositeCand);
1160 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1161 ConvergingScheduler::SchedCandidate &BotCand);
1163 void tryCandidate(SchedCandidate &Cand,
1164 SchedCandidate &TryCand,
1165 SchedBoundary &Zone,
1166 const RegPressureTracker &RPTracker,
1167 RegPressureTracker &TempTracker);
1169 SUnit *pickNodeBidirectional(bool &IsTopNode);
1171 void pickNodeFromQueue(SchedBoundary &Zone,
1172 const RegPressureTracker &RPTracker,
1173 SchedCandidate &Candidate);
1176 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
1181 void ConvergingScheduler::SchedRemainder::
1182 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1184 if (!SchedModel->hasInstrSchedModel())
1186 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1187 for (std::vector<SUnit>::iterator
1188 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1189 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1190 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1191 for (TargetSchedModel::ProcResIter
1192 PI = SchedModel->getWriteProcResBegin(SC),
1193 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1194 unsigned PIdx = PI->ProcResourceIdx;
1195 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1196 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1199 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1200 PIdx != PEnd; ++PIdx) {
1201 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1202 >= (int)SchedModel->getLatencyFactor()) {
1208 void ConvergingScheduler::SchedBoundary::
1209 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1212 SchedModel = smodel;
1214 if (SchedModel->hasInstrSchedModel())
1215 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1218 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1220 SchedModel = DAG->getSchedModel();
1222 Rem.init(DAG, SchedModel);
1223 Top.init(DAG, SchedModel, &Rem);
1224 Bot.init(DAG, SchedModel, &Rem);
1226 DAG->computeDFSResult();
1228 // Initialize resource counts.
1230 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1231 // are disabled, then these HazardRecs will be disabled.
1232 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1233 const TargetMachine &TM = DAG->MF.getTarget();
1234 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1235 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1237 assert((!ForceTopDown || !ForceBottomUp) &&
1238 "-misched-topdown incompatible with -misched-bottomup");
1241 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1242 if (SU->isScheduled)
1245 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1247 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1248 unsigned MinLatency = I->getMinLatency();
1250 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
1252 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1253 SU->TopReadyCycle = PredReadyCycle + MinLatency;
1255 Top.releaseNode(SU, SU->TopReadyCycle);
1258 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1259 if (SU->isScheduled)
1262 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1264 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1268 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1269 unsigned MinLatency = I->getMinLatency();
1271 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
1273 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1274 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
1276 Bot.releaseNode(SU, SU->BotReadyCycle);
1279 void ConvergingScheduler::registerRoots() {
1280 Rem.CriticalPath = DAG->ExitSU.getDepth();
1281 // Some roots may not feed into ExitSU. Check all of them in case.
1282 for (std::vector<SUnit*>::const_iterator
1283 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1284 if ((*I)->getDepth() > Rem.CriticalPath)
1285 Rem.CriticalPath = (*I)->getDepth();
1287 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1290 /// Does this SU have a hazard within the current instruction group.
1292 /// The scheduler supports two modes of hazard recognition. The first is the
1293 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1294 /// supports highly complicated in-order reservation tables
1295 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1297 /// The second is a streamlined mechanism that checks for hazards based on
1298 /// simple counters that the scheduler itself maintains. It explicitly checks
1299 /// for instruction dispatch limitations, including the number of micro-ops that
1300 /// can dispatch per cycle.
1302 /// TODO: Also check whether the SU must start a new group.
1303 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1304 if (HazardRec->isEnabled())
1305 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1307 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1308 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1309 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1310 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1316 /// Compute the remaining latency to determine whether ILP should be increased.
1317 void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1318 // FIXME: compile time. In all, we visit four queues here one we should only
1319 // need to visit the one that was last popped if we cache the result.
1320 unsigned RemLatency = 0;
1321 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1323 unsigned L = getUnscheduledLatency(*I);
1327 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1329 unsigned L = getUnscheduledLatency(*I);
1333 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1334 if (RemLatency + ExpectedLatency >= CriticalPathLimit
1335 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1336 Policy.ReduceLatency = true;
1337 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
1341 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1342 unsigned ReadyCycle) {
1344 if (ReadyCycle < MinReadyCycle)
1345 MinReadyCycle = ReadyCycle;
1347 // Check for interlocks first. For the purpose of other heuristics, an
1348 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1349 if (ReadyCycle > CurrCycle || checkHazard(SU))
1354 // Record this node as an immediate dependent of the scheduled node.
1358 /// Move the boundary of scheduled code by one cycle.
1359 void ConvergingScheduler::SchedBoundary::bumpCycle() {
1360 unsigned Width = SchedModel->getIssueWidth();
1361 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
1363 unsigned NextCycle = CurrCycle + 1;
1364 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1365 if (MinReadyCycle > NextCycle) {
1367 NextCycle = MinReadyCycle;
1370 if (!HazardRec->isEnabled()) {
1371 // Bypass HazardRec virtual calls.
1372 CurrCycle = NextCycle;
1375 // Bypass getHazardType calls in case of long latency.
1376 for (; CurrCycle != NextCycle; ++CurrCycle) {
1378 HazardRec->AdvanceCycle();
1380 HazardRec->RecedeCycle();
1383 CheckPending = true;
1384 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1386 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
1387 << CurrCycle << '\n');
1390 /// Add the given processor resource to this scheduled zone.
1391 void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1393 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1394 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1395 << " +(" << Cycles << "x" << Factor
1396 << ") / " << SchedModel->getLatencyFactor() << '\n');
1398 unsigned Count = Factor * Cycles;
1399 ResourceCounts[PIdx] += Count;
1400 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1401 Rem->RemainingCounts[PIdx] -= Count;
1403 // Check if this resource exceeds the current critical resource by a full
1404 // cycle. If so, it becomes the critical resource.
1405 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1406 >= (int)SchedModel->getLatencyFactor()) {
1408 DEBUG(dbgs() << " *** Critical resource "
1409 << SchedModel->getProcResource(PIdx)->Name << " x"
1410 << ResourceCounts[PIdx] << '\n');
1414 /// Move the boundary of scheduled code by one SUnit.
1415 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1416 // Update the reservation table.
1417 if (HazardRec->isEnabled()) {
1418 if (!isTop() && SU->isCall) {
1419 // Calls are scheduled with their preceding instructions. For bottom-up
1420 // scheduling, clear the pipeline state before emitting.
1423 HazardRec->EmitInstruction(SU);
1425 // Update resource counts and critical resource.
1426 if (SchedModel->hasInstrSchedModel()) {
1427 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1428 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1429 for (TargetSchedModel::ProcResIter
1430 PI = SchedModel->getWriteProcResBegin(SC),
1431 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1432 countResource(PI->ProcResourceIdx, PI->Cycles);
1436 if (SU->getDepth() > ExpectedLatency)
1437 ExpectedLatency = SU->getDepth();
1440 if (SU->getHeight() > ExpectedLatency)
1441 ExpectedLatency = SU->getHeight();
1444 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1446 // Check the instruction group dispatch limit.
1447 // TODO: Check if this SU must end a dispatch group.
1448 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
1450 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1451 // issue width. However, we commonly reach the maximum. In this case
1452 // opportunistically bump the cycle to avoid uselessly checking everything in
1453 // the readyQ. Furthermore, a single instruction may produce more than one
1454 // cycle's worth of micro-ops.
1455 if (IssueCount >= SchedModel->getIssueWidth()) {
1456 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
1461 /// Release pending ready nodes in to the available queue. This makes them
1462 /// visible to heuristics.
1463 void ConvergingScheduler::SchedBoundary::releasePending() {
1464 // If the available queue is empty, it is safe to reset MinReadyCycle.
1465 if (Available.empty())
1466 MinReadyCycle = UINT_MAX;
1468 // Check to see if any of the pending instructions are ready to issue. If
1469 // so, add them to the available queue.
1470 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1471 SUnit *SU = *(Pending.begin()+i);
1472 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1474 if (ReadyCycle < MinReadyCycle)
1475 MinReadyCycle = ReadyCycle;
1477 if (ReadyCycle > CurrCycle)
1480 if (checkHazard(SU))
1484 Pending.remove(Pending.begin()+i);
1487 DEBUG(if (!Pending.empty()) Pending.dump());
1488 CheckPending = false;
1491 /// Remove SU from the ready set for this boundary.
1492 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1493 if (Available.isInQueue(SU))
1494 Available.remove(Available.find(SU));
1496 assert(Pending.isInQueue(SU) && "bad ready count");
1497 Pending.remove(Pending.find(SU));
1501 /// If this queue only has one ready candidate, return it. As a side effect,
1502 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1503 /// one node is ready. If multiple instructions are ready, return NULL.
1504 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1508 if (IssueCount > 0) {
1509 // Defer any ready instrs that now have a hazard.
1510 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1511 if (checkHazard(*I)) {
1513 I = Available.remove(I);
1519 for (unsigned i = 0; Available.empty(); ++i) {
1520 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1521 "permanent hazard"); (void)i;
1525 if (Available.size() == 1)
1526 return *Available.begin();
1530 /// Record the candidate policy for opposite zones with different critical
1533 /// If the CriticalZone is latency limited, don't force a policy for the
1534 /// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
1535 void ConvergingScheduler::balanceZones(
1536 ConvergingScheduler::SchedBoundary &CriticalZone,
1537 ConvergingScheduler::SchedCandidate &CriticalCand,
1538 ConvergingScheduler::SchedBoundary &OppositeZone,
1539 ConvergingScheduler::SchedCandidate &OppositeCand) {
1541 if (!CriticalZone.IsResourceLimited)
1543 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
1545 SchedRemainder *Rem = CriticalZone.Rem;
1547 // If the critical zone is overconsuming a resource relative to the
1548 // remainder, try to reduce it.
1549 unsigned RemainingCritCount =
1550 Rem->RemainingCounts[CriticalZone.CritResIdx];
1551 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
1552 > (int)SchedModel->getLatencyFactor()) {
1553 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1554 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1555 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1558 // If the other zone is underconsuming a resource relative to the full zone,
1559 // try to increase it.
1560 unsigned OppositeCount =
1561 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1562 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1563 > (int)SchedModel->getLatencyFactor()) {
1564 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1565 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1566 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1571 /// Determine if the scheduled zones exceed resource limits or critical path and
1572 /// set each candidate's ReduceHeight policy accordingly.
1573 void ConvergingScheduler::checkResourceLimits(
1574 ConvergingScheduler::SchedCandidate &TopCand,
1575 ConvergingScheduler::SchedCandidate &BotCand) {
1577 // Set ReduceLatency to true if needed.
1578 Bot.setLatencyPolicy(BotCand.Policy);
1579 Top.setLatencyPolicy(TopCand.Policy);
1581 // Handle resource-limited regions.
1582 if (Top.IsResourceLimited && Bot.IsResourceLimited
1583 && Top.CritResIdx == Bot.CritResIdx) {
1584 // If the scheduled critical resource in both zones is no longer the
1585 // critical remaining resource, attempt to reduce resource height both ways.
1586 if (Top.CritResIdx != Rem.CritResIdx) {
1587 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1588 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1589 DEBUG(dbgs() << "Reduce scheduled "
1590 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1594 // Handle latency-limited regions.
1595 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1596 // If the total scheduled expected latency exceeds the region's critical
1597 // path then reduce latency both ways.
1599 // Just because a zone is not resource limited does not mean it is latency
1600 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1601 // to exceed expected latency.
1602 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1603 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1604 TopCand.Policy.ReduceLatency = true;
1605 BotCand.Policy.ReduceLatency = true;
1606 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1607 << " + " << Bot.ExpectedLatency << '\n');
1611 // The critical resource is different in each zone, so request balancing.
1613 // Compute the cost of each zone.
1614 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1615 Top.ExpectedCount = std::max(
1616 Top.getCriticalCount(),
1617 Top.ExpectedCount * SchedModel->getLatencyFactor());
1618 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1619 Bot.ExpectedCount = std::max(
1620 Bot.getCriticalCount(),
1621 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1623 balanceZones(Top, TopCand, Bot, BotCand);
1624 balanceZones(Bot, BotCand, Top, TopCand);
1627 void ConvergingScheduler::SchedCandidate::
1628 initResourceDelta(const ScheduleDAGMI *DAG,
1629 const TargetSchedModel *SchedModel) {
1630 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1633 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1634 for (TargetSchedModel::ProcResIter
1635 PI = SchedModel->getWriteProcResBegin(SC),
1636 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1637 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1638 ResDelta.CritResources += PI->Cycles;
1639 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1640 ResDelta.DemandedResources += PI->Cycles;
1644 /// Return true if this heuristic determines order.
1645 static bool tryLess(unsigned TryVal, unsigned CandVal,
1646 ConvergingScheduler::SchedCandidate &TryCand,
1647 ConvergingScheduler::SchedCandidate &Cand,
1648 ConvergingScheduler::CandReason Reason) {
1649 if (TryVal < CandVal) {
1650 TryCand.Reason = Reason;
1653 if (TryVal > CandVal) {
1654 if (Cand.Reason > Reason)
1655 Cand.Reason = Reason;
1661 static bool tryGreater(unsigned TryVal, unsigned CandVal,
1662 ConvergingScheduler::SchedCandidate &TryCand,
1663 ConvergingScheduler::SchedCandidate &Cand,
1664 ConvergingScheduler::CandReason Reason) {
1665 if (TryVal > CandVal) {
1666 TryCand.Reason = Reason;
1669 if (TryVal < CandVal) {
1670 if (Cand.Reason > Reason)
1671 Cand.Reason = Reason;
1677 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1678 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1681 /// Apply a set of heursitics to a new candidate. Heuristics are currently
1682 /// hierarchical. This may be more efficient than a graduated cost model because
1683 /// we don't need to evaluate all aspects of the model for each node in the
1684 /// queue. But it's really done to make the heuristics easier to debug and
1685 /// statistically analyze.
1687 /// \param Cand provides the policy and current best candidate.
1688 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1689 /// \param Zone describes the scheduled zone that we are extending.
1690 /// \param RPTracker describes reg pressure within the scheduled zone.
1691 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
1692 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1693 SchedCandidate &TryCand,
1694 SchedBoundary &Zone,
1695 const RegPressureTracker &RPTracker,
1696 RegPressureTracker &TempTracker) {
1698 // Always initialize TryCand's RPDelta.
1699 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1700 DAG->getRegionCriticalPSets(),
1701 DAG->getRegPressure().MaxSetPressure);
1703 // Initialize the candidate if needed.
1704 if (!Cand.isValid()) {
1705 TryCand.Reason = NodeOrder;
1708 // Avoid exceeding the target's limit.
1709 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1710 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1712 if (Cand.Reason == SingleExcess)
1713 Cand.Reason = MultiPressure;
1715 // Avoid increasing the max critical pressure in the scheduled region.
1716 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1717 Cand.RPDelta.CriticalMax.UnitIncrease,
1718 TryCand, Cand, SingleCritical))
1720 if (Cand.Reason == SingleCritical)
1721 Cand.Reason = MultiPressure;
1723 // Keep clustered nodes together to encourage downstream peephole
1724 // optimizations which may reduce resource requirements.
1726 // This is a best effort to set things up for a post-RA pass. Optimizations
1727 // like generating loads of multiple registers should ideally be done within
1728 // the scheduler pass by combining the loads during DAG postprocessing.
1729 const SUnit *NextClusterSU =
1730 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1731 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1732 TryCand, Cand, Cluster))
1734 // Currently, weak edges are for clustering, so we hard-code that reason.
1735 // However, deferring the current TryCand will not change Cand's reason.
1736 CandReason OrigReason = Cand.Reason;
1737 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1738 getWeakLeft(Cand.SU, Zone.isTop()),
1739 TryCand, Cand, Cluster)) {
1740 Cand.Reason = OrigReason;
1743 // Avoid critical resource consumption and balance the schedule.
1744 TryCand.initResourceDelta(DAG, SchedModel);
1745 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1746 TryCand, Cand, ResourceReduce))
1748 if (tryGreater(TryCand.ResDelta.DemandedResources,
1749 Cand.ResDelta.DemandedResources,
1750 TryCand, Cand, ResourceDemand))
1753 // Avoid serializing long latency dependence chains.
1754 if (Cand.Policy.ReduceLatency) {
1756 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1757 > Zone.ExpectedCount) {
1758 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1759 TryCand, Cand, TopDepthReduce))
1762 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1763 TryCand, Cand, TopPathReduce))
1767 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1768 > Zone.ExpectedCount) {
1769 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1770 TryCand, Cand, BotHeightReduce))
1773 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1774 TryCand, Cand, BotPathReduce))
1779 // Avoid increasing the max pressure of the entire region.
1780 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1781 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1783 if (Cand.Reason == SingleMax)
1784 Cand.Reason = MultiPressure;
1786 // Prefer immediate defs/users of the last scheduled instruction. This is a
1787 // nice pressure avoidance strategy that also conserves the processor's
1788 // register renaming resources and keeps the machine code readable.
1789 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1790 TryCand, Cand, NextDefUse))
1793 // Fall through to original instruction order.
1794 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1795 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1796 TryCand.Reason = NodeOrder;
1800 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1801 /// more desirable than RHS from scheduling standpoint.
1802 static bool compareRPDelta(const RegPressureDelta &LHS,
1803 const RegPressureDelta &RHS) {
1804 // Compare each component of pressure in decreasing order of importance
1805 // without checking if any are valid. Invalid PressureElements are assumed to
1806 // have UnitIncrease==0, so are neutral.
1808 // Avoid increasing the max critical pressure in the scheduled region.
1809 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1810 DEBUG(dbgs() << "RP excess top - bot: "
1811 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
1812 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1814 // Avoid increasing the max critical pressure in the scheduled region.
1815 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1816 DEBUG(dbgs() << "RP critical top - bot: "
1817 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1819 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1821 // Avoid increasing the max pressure of the entire region.
1822 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1823 DEBUG(dbgs() << "RP current top - bot: "
1824 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1826 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1832 const char *ConvergingScheduler::getReasonStr(
1833 ConvergingScheduler::CandReason Reason) {
1835 case NoCand: return "NOCAND ";
1836 case SingleExcess: return "REG-EXCESS";
1837 case SingleCritical: return "REG-CRIT ";
1838 case Cluster: return "CLUSTER ";
1839 case SingleMax: return "REG-MAX ";
1840 case MultiPressure: return "REG-MULTI ";
1841 case ResourceReduce: return "RES-REDUCE";
1842 case ResourceDemand: return "RES-DEMAND";
1843 case TopDepthReduce: return "TOP-DEPTH ";
1844 case TopPathReduce: return "TOP-PATH ";
1845 case BotHeightReduce:return "BOT-HEIGHT";
1846 case BotPathReduce: return "BOT-PATH ";
1847 case NextDefUse: return "DEF-USE ";
1848 case NodeOrder: return "ORDER ";
1850 llvm_unreachable("Unknown reason!");
1853 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1854 const SchedBoundary &Zone) {
1855 const char *Label = getReasonStr(Cand.Reason);
1857 unsigned ResIdx = 0;
1858 unsigned Latency = 0;
1859 switch (Cand.Reason) {
1863 P = Cand.RPDelta.Excess;
1865 case SingleCritical:
1866 P = Cand.RPDelta.CriticalMax;
1869 P = Cand.RPDelta.CurrentMax;
1871 case ResourceReduce:
1872 ResIdx = Cand.Policy.ReduceResIdx;
1874 case ResourceDemand:
1875 ResIdx = Cand.Policy.DemandResIdx;
1877 case TopDepthReduce:
1878 Latency = Cand.SU->getDepth();
1881 Latency = Cand.SU->getHeight();
1883 case BotHeightReduce:
1884 Latency = Cand.SU->getHeight();
1887 Latency = Cand.SU->getDepth();
1890 dbgs() << Label << " " << Zone.Available.getName() << " ";
1892 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1897 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1901 dbgs() << Latency << " cycles ";
1908 /// Pick the best candidate from the top queue.
1910 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1911 /// DAG building. To adjust for the current scheduling location we need to
1912 /// maintain the number of vreg uses remaining to be top-scheduled.
1913 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1914 const RegPressureTracker &RPTracker,
1915 SchedCandidate &Cand) {
1916 ReadyQueue &Q = Zone.Available;
1920 // getMaxPressureDelta temporarily modifies the tracker.
1921 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1923 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
1925 SchedCandidate TryCand(Cand.Policy);
1927 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1928 if (TryCand.Reason != NoCand) {
1929 // Initialize resource delta if needed in case future heuristics query it.
1930 if (TryCand.ResDelta == SchedResourceDelta())
1931 TryCand.initResourceDelta(DAG, SchedModel);
1932 Cand.setBest(TryCand);
1933 DEBUG(traceCandidate(Cand, Zone));
1938 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1940 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1941 << " SU(" << Cand.SU->NodeNum << ") "
1942 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
1945 /// Pick the best candidate node from either the top or bottom queue.
1946 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
1947 // Schedule as far as possible in the direction of no choice. This is most
1948 // efficient, but also provides the best heuristics for CriticalPSets.
1949 if (SUnit *SU = Bot.pickOnlyChoice()) {
1953 if (SUnit *SU = Top.pickOnlyChoice()) {
1957 CandPolicy NoPolicy;
1958 SchedCandidate BotCand(NoPolicy);
1959 SchedCandidate TopCand(NoPolicy);
1960 checkResourceLimits(TopCand, BotCand);
1962 // Prefer bottom scheduling when heuristics are silent.
1963 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1964 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
1966 // If either Q has a single candidate that provides the least increase in
1967 // Excess pressure, we can immediately schedule from that Q.
1969 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1970 // affects picking from either Q. If scheduling in one direction must
1971 // increase pressure for one of the excess PSets, then schedule in that
1972 // direction first to provide more freedom in the other direction.
1973 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
1975 tracePick(BotCand, IsTopNode);
1978 // Check if the top Q has a better candidate.
1979 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1980 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1982 // If either Q has a single candidate that minimizes pressure above the
1983 // original region's pressure pick it.
1984 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1985 if (TopCand.Reason < BotCand.Reason) {
1987 tracePick(TopCand, IsTopNode);
1991 tracePick(BotCand, IsTopNode);
1994 // Check for a salient pressure difference and pick the best from either side.
1995 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
1997 tracePick(TopCand, IsTopNode);
2000 // Otherwise prefer the bottom candidate, in node order if all else failed.
2001 if (TopCand.Reason < BotCand.Reason) {
2003 tracePick(TopCand, IsTopNode);
2007 tracePick(BotCand, IsTopNode);
2011 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2012 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2013 if (DAG->top() == DAG->bottom()) {
2014 assert(Top.Available.empty() && Top.Pending.empty() &&
2015 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2021 SU = Top.pickOnlyChoice();
2023 CandPolicy NoPolicy;
2024 SchedCandidate TopCand(NoPolicy);
2025 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2026 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2031 else if (ForceBottomUp) {
2032 SU = Bot.pickOnlyChoice();
2034 CandPolicy NoPolicy;
2035 SchedCandidate BotCand(NoPolicy);
2036 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2037 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2043 SU = pickNodeBidirectional(IsTopNode);
2045 } while (SU->isScheduled);
2047 if (SU->isTopReady())
2048 Top.removeReady(SU);
2049 if (SU->isBottomReady())
2050 Bot.removeReady(SU);
2052 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2053 << " Scheduling Instruction in cycle "
2054 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2059 /// Update the scheduler's state after scheduling a node. This is the same node
2060 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2061 /// it's state based on the current cycle before MachineSchedStrategy does.
2062 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2064 SU->TopReadyCycle = Top.CurrCycle;
2068 SU->BotReadyCycle = Bot.CurrCycle;
2073 /// Create the standard converging machine scheduler. This will be used as the
2074 /// default scheduler if the target does not set a default.
2075 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2076 assert((!ForceTopDown || !ForceBottomUp) &&
2077 "-misched-topdown incompatible with -misched-bottomup");
2078 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2079 // Register DAG post-processors.
2080 if (EnableLoadCluster)
2081 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2082 if (EnableMacroFusion)
2083 DAG->addMutation(new MacroFusion(DAG->TII));
2086 static MachineSchedRegistry
2087 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2088 createConvergingSched);
2090 //===----------------------------------------------------------------------===//
2091 // ILP Scheduler. Currently for experimental analysis of heuristics.
2092 //===----------------------------------------------------------------------===//
2095 /// \brief Order nodes by the ILP metric.
2097 const SchedDFSResult *DFSResult;
2098 const BitVector *ScheduledTrees;
2101 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2103 /// \brief Apply a less-than relation on node priority.
2105 /// (Return true if A comes after B in the Q.)
2106 bool operator()(const SUnit *A, const SUnit *B) const {
2107 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2108 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2109 if (SchedTreeA != SchedTreeB) {
2110 // Unscheduled trees have lower priority.
2111 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2112 return ScheduledTrees->test(SchedTreeB);
2114 // Trees with shallower connections have have lower priority.
2115 if (DFSResult->getSubtreeLevel(SchedTreeA)
2116 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2117 return DFSResult->getSubtreeLevel(SchedTreeA)
2118 < DFSResult->getSubtreeLevel(SchedTreeB);
2122 return DFSResult->getILP(A) < DFSResult->getILP(B);
2124 return DFSResult->getILP(A) > DFSResult->getILP(B);
2128 /// \brief Schedule based on the ILP metric.
2129 class ILPScheduler : public MachineSchedStrategy {
2130 /// In case all subtrees are eventually connected to a common root through
2131 /// data dependence (e.g. reduction), place an upper limit on their size.
2133 /// FIXME: A subtree limit is generally good, but in the situation commented
2134 /// above, where multiple similar subtrees feed a common root, we should
2135 /// only split at a point where the resulting subtrees will be balanced.
2136 /// (a motivating test case must be found).
2137 static const unsigned SubtreeLimit = 16;
2142 std::vector<SUnit*> ReadyQ;
2144 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2146 virtual void initialize(ScheduleDAGMI *dag) {
2148 DAG->computeDFSResult();
2149 Cmp.DFSResult = DAG->getDFSResult();
2150 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
2154 virtual void registerRoots() {
2155 // Restore the heap in ReadyQ with the updated DFS results.
2156 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2159 /// Implement MachineSchedStrategy interface.
2160 /// -----------------------------------------
2162 /// Callback to select the highest priority node from the ready Q.
2163 virtual SUnit *pickNode(bool &IsTopNode) {
2164 if (ReadyQ.empty()) return NULL;
2165 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2166 SUnit *SU = ReadyQ.back();
2169 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2171 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2172 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2173 << DAG->getDFSResult()->getSubtreeLevel(
2174 DAG->getDFSResult()->getSubtreeID(SU)) << '\n');
2178 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2179 virtual void scheduleTree(unsigned SubtreeID) {
2180 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2183 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2184 /// DFSResults, and resort the priority Q.
2185 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2186 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2189 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2191 virtual void releaseBottomNode(SUnit *SU) {
2192 ReadyQ.push_back(SU);
2193 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2198 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2199 return new ScheduleDAGMI(C, new ILPScheduler(true));
2201 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2202 return new ScheduleDAGMI(C, new ILPScheduler(false));
2204 static MachineSchedRegistry ILPMaxRegistry(
2205 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2206 static MachineSchedRegistry ILPMinRegistry(
2207 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2209 //===----------------------------------------------------------------------===//
2210 // Machine Instruction Shuffler for Correctness Testing
2211 //===----------------------------------------------------------------------===//
2215 /// Apply a less-than relation on the node order, which corresponds to the
2216 /// instruction order prior to scheduling. IsReverse implements greater-than.
2217 template<bool IsReverse>
2219 bool operator()(SUnit *A, SUnit *B) const {
2221 return A->NodeNum > B->NodeNum;
2223 return A->NodeNum < B->NodeNum;
2227 /// Reorder instructions as much as possible.
2228 class InstructionShuffler : public MachineSchedStrategy {
2232 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2233 // gives nodes with a higher number higher priority causing the latest
2234 // instructions to be scheduled first.
2235 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2237 // When scheduling bottom-up, use greater-than as the queue priority.
2238 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2241 InstructionShuffler(bool alternate, bool topdown)
2242 : IsAlternating(alternate), IsTopDown(topdown) {}
2244 virtual void initialize(ScheduleDAGMI *) {
2249 /// Implement MachineSchedStrategy interface.
2250 /// -----------------------------------------
2252 virtual SUnit *pickNode(bool &IsTopNode) {
2256 if (TopQ.empty()) return NULL;
2259 } while (SU->isScheduled);
2264 if (BottomQ.empty()) return NULL;
2267 } while (SU->isScheduled);
2271 IsTopDown = !IsTopDown;
2275 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2277 virtual void releaseTopNode(SUnit *SU) {
2280 virtual void releaseBottomNode(SUnit *SU) {
2286 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2287 bool Alternate = !ForceTopDown && !ForceBottomUp;
2288 bool TopDown = !ForceBottomUp;
2289 assert((TopDown || !ForceTopDown) &&
2290 "-misched-topdown incompatible with -misched-bottomup");
2291 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2293 static MachineSchedRegistry ShufflerRegistry(
2294 "shuffle", "Shuffle machine instructions alternating directions",
2295 createInstructionShuffler);
2298 //===----------------------------------------------------------------------===//
2299 // GraphWriter support for ScheduleDAGMI.
2300 //===----------------------------------------------------------------------===//
2305 template<> struct GraphTraits<
2306 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2309 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2311 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2313 static std::string getGraphName(const ScheduleDAG *G) {
2314 return G->MF.getName();
2317 static bool renderGraphFromBottomUp() {
2321 static bool isNodeHidden(const SUnit *Node) {
2322 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2325 static bool hasNodeAddressLabel(const SUnit *Node,
2326 const ScheduleDAG *Graph) {
2330 /// If you want to override the dot attributes printed for a particular
2331 /// edge, override this method.
2332 static std::string getEdgeAttributes(const SUnit *Node,
2334 const ScheduleDAG *Graph) {
2335 if (EI.isArtificialDep())
2336 return "color=cyan,style=dashed";
2338 return "color=blue,style=dashed";
2342 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2344 raw_string_ostream SS(Str);
2345 SS << "SU(" << SU->NodeNum << ')';
2348 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2349 return G->getGraphNodeLabel(SU);
2352 static std::string getNodeAttributes(const SUnit *N,
2353 const ScheduleDAG *Graph) {
2354 std::string Str("shape=Mrecord");
2355 const SchedDFSResult *DFS =
2356 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2358 Str += ",style=filled,fillcolor=\"#";
2359 Str += DOT::getColorString(DFS->getSubtreeID(N));
2368 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2369 /// rendered using 'dot'.
2371 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2373 ViewGraph(this, Name, false, Title);
2375 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2376 << "systems with Graphviz or gv!\n";
2380 /// Out-of-line implementation with no arguments is handy for gdb.
2381 void ScheduleDAGMI::viewGraph() {
2382 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());