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/MachineDominators.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterClassInfo.h"
26 #include "llvm/CodeGen/ScheduleDFS.h"
27 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GraphWriter.h"
32 #include "llvm/Support/raw_ostream.h"
38 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
39 cl::desc("Force top-down list scheduling"));
40 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
41 cl::desc("Force bottom-up list scheduling"));
45 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
46 cl::desc("Pop up a window to show MISched dags after they are processed"));
48 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
49 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
51 static bool ViewMISchedDAGs = false;
54 // Experimental heuristics
55 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
56 cl::desc("Enable load clustering."), cl::init(true));
58 // Experimental heuristics
59 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
60 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
62 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
63 cl::desc("Verify machine instrs before and after machine scheduling"));
65 // DAG subtrees must have at least this many nodes.
66 static const unsigned MinSubtreeSize = 8;
68 //===----------------------------------------------------------------------===//
69 // Machine Instruction Scheduling Pass and Registry
70 //===----------------------------------------------------------------------===//
72 MachineSchedContext::MachineSchedContext():
73 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
74 RegClassInfo = new RegisterClassInfo();
77 MachineSchedContext::~MachineSchedContext() {
82 /// MachineScheduler runs after coalescing and before register allocation.
83 class MachineScheduler : public MachineSchedContext,
84 public MachineFunctionPass {
88 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
90 virtual void releaseMemory() {}
92 virtual bool runOnMachineFunction(MachineFunction&);
94 virtual void print(raw_ostream &O, const Module* = 0) const;
96 static char ID; // Class identification, replacement for typeinfo
100 char MachineScheduler::ID = 0;
102 char &llvm::MachineSchedulerID = MachineScheduler::ID;
104 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
105 "Machine Instruction Scheduler", false, false)
106 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
107 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
108 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
109 INITIALIZE_PASS_END(MachineScheduler, "misched",
110 "Machine Instruction Scheduler", false, false)
112 MachineScheduler::MachineScheduler()
113 : MachineFunctionPass(ID) {
114 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
117 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
118 AU.setPreservesCFG();
119 AU.addRequiredID(MachineDominatorsID);
120 AU.addRequired<MachineLoopInfo>();
121 AU.addRequired<AliasAnalysis>();
122 AU.addRequired<TargetPassConfig>();
123 AU.addRequired<SlotIndexes>();
124 AU.addPreserved<SlotIndexes>();
125 AU.addRequired<LiveIntervals>();
126 AU.addPreserved<LiveIntervals>();
127 MachineFunctionPass::getAnalysisUsage(AU);
130 MachinePassRegistry MachineSchedRegistry::Registry;
132 /// A dummy default scheduler factory indicates whether the scheduler
133 /// is overridden on the command line.
134 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
138 /// MachineSchedOpt allows command line selection of the scheduler.
139 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
140 RegisterPassParser<MachineSchedRegistry> >
141 MachineSchedOpt("misched",
142 cl::init(&useDefaultMachineSched), cl::Hidden,
143 cl::desc("Machine instruction scheduler to use"));
145 static MachineSchedRegistry
146 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
147 useDefaultMachineSched);
149 /// Forward declare the standard machine scheduler. This will be used as the
150 /// default scheduler if the target does not set a default.
151 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
154 /// Decrement this iterator until reaching the top or a non-debug instr.
155 static MachineBasicBlock::iterator
156 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
157 assert(I != Beg && "reached the top of the region, cannot decrement");
159 if (!I->isDebugValue())
165 /// If this iterator is a debug value, increment until reaching the End or a
166 /// non-debug instruction.
167 static MachineBasicBlock::iterator
168 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
169 for(; I != End; ++I) {
170 if (!I->isDebugValue())
176 /// Top-level MachineScheduler pass driver.
178 /// Visit blocks in function order. Divide each block into scheduling regions
179 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
180 /// consistent with the DAG builder, which traverses the interior of the
181 /// scheduling regions bottom-up.
183 /// This design avoids exposing scheduling boundaries to the DAG builder,
184 /// simplifying the DAG builder's support for "special" target instructions.
185 /// At the same time the design allows target schedulers to operate across
186 /// scheduling boundaries, for example to bundle the boudary instructions
187 /// without reordering them. This creates complexity, because the target
188 /// scheduler must update the RegionBegin and RegionEnd positions cached by
189 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
190 /// design would be to split blocks at scheduling boundaries, but LLVM has a
191 /// general bias against block splitting purely for implementation simplicity.
192 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
193 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
195 // Initialize the context of the pass.
197 MLI = &getAnalysis<MachineLoopInfo>();
198 MDT = &getAnalysis<MachineDominatorTree>();
199 PassConfig = &getAnalysis<TargetPassConfig>();
200 AA = &getAnalysis<AliasAnalysis>();
202 LIS = &getAnalysis<LiveIntervals>();
203 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
205 if (VerifyScheduling) {
206 DEBUG(LIS->print(dbgs()));
207 MF->verify(this, "Before machine scheduling.");
209 RegClassInfo->runOnMachineFunction(*MF);
211 // Select the scheduler, or set the default.
212 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
213 if (Ctor == useDefaultMachineSched) {
214 // Get the default scheduler set by the target.
215 Ctor = MachineSchedRegistry::getDefault();
217 Ctor = createConvergingSched;
218 MachineSchedRegistry::setDefault(Ctor);
221 // Instantiate the selected scheduler.
222 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
224 // Visit all machine basic blocks.
226 // TODO: Visit blocks in global postorder or postorder within the bottom-up
227 // loop tree. Then we can optionally compute global RegPressure.
228 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
229 MBB != MBBEnd; ++MBB) {
231 Scheduler->startBlock(MBB);
233 // Break the block into scheduling regions [I, RegionEnd), and schedule each
234 // region as soon as it is discovered. RegionEnd points the scheduling
235 // boundary at the bottom of the region. The DAG does not include RegionEnd,
236 // but the region does (i.e. the next RegionEnd is above the previous
237 // RegionBegin). If the current block has no terminator then RegionEnd ==
238 // MBB->end() for the bottom region.
240 // The Scheduler may insert instructions during either schedule() or
241 // exitRegion(), even for empty regions. So the local iterators 'I' and
242 // 'RegionEnd' are invalid across these calls.
243 unsigned RemainingInstrs = MBB->size();
244 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
245 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
247 // Avoid decrementing RegionEnd for blocks with no terminator.
248 if (RegionEnd != MBB->end()
249 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
251 // Count the boundary instruction.
255 // The next region starts above the previous region. Look backward in the
256 // instruction stream until we find the nearest boundary.
257 MachineBasicBlock::iterator I = RegionEnd;
258 for(;I != MBB->begin(); --I, --RemainingInstrs) {
259 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
262 // Notify the scheduler of the region, even if we may skip scheduling
263 // it. Perhaps it still needs to be bundled.
264 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
266 // Skip empty scheduling regions (0 or 1 schedulable instructions).
267 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
268 // Close the current region. Bundle the terminator if needed.
269 // This invalidates 'RegionEnd' and 'I'.
270 Scheduler->exitRegion();
273 DEBUG(dbgs() << "********** MI Scheduling **********\n");
274 DEBUG(dbgs() << MF->getName()
275 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
276 << "\n From: " << *I << " To: ";
277 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
278 else dbgs() << "End";
279 dbgs() << " Remaining: " << RemainingInstrs << "\n");
281 // Schedule a region: possibly reorder instructions.
282 // This invalidates 'RegionEnd' and 'I'.
283 Scheduler->schedule();
285 // Close the current region.
286 Scheduler->exitRegion();
288 // Scheduling has invalidated the current iterator 'I'. Ask the
289 // scheduler for the top of it's scheduled region.
290 RegionEnd = Scheduler->begin();
292 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
293 Scheduler->finishBlock();
295 Scheduler->finalizeSchedule();
296 DEBUG(LIS->print(dbgs()));
297 if (VerifyScheduling)
298 MF->verify(this, "After machine scheduling.");
302 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
306 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
307 void ReadyQueue::dump() {
308 dbgs() << " " << Name << ": ";
309 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
310 dbgs() << Queue[i]->NodeNum << " ";
315 //===----------------------------------------------------------------------===//
316 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
318 //===----------------------------------------------------------------------===//
320 ScheduleDAGMI::~ScheduleDAGMI() {
322 DeleteContainerPointers(Mutations);
326 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
327 if (SuccSU != &ExitSU) {
328 // Do not use WillCreateCycle, it assumes SD scheduling.
329 // If Pred is reachable from Succ, then the edge creates a cycle.
330 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
332 Topo.AddPred(SuccSU, PredDep.getSUnit());
334 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
335 // Return true regardless of whether a new edge needed to be inserted.
339 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
340 /// NumPredsLeft reaches zero, release the successor node.
342 /// FIXME: Adjust SuccSU height based on MinLatency.
343 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
344 SUnit *SuccSU = SuccEdge->getSUnit();
346 if (SuccEdge->isWeak()) {
347 --SuccSU->WeakPredsLeft;
348 if (SuccEdge->isCluster())
349 NextClusterSucc = SuccSU;
353 if (SuccSU->NumPredsLeft == 0) {
354 dbgs() << "*** Scheduling failed! ***\n";
356 dbgs() << " has been released too many times!\n";
360 --SuccSU->NumPredsLeft;
361 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
362 SchedImpl->releaseTopNode(SuccSU);
365 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
366 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
367 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
369 releaseSucc(SU, &*I);
373 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
374 /// NumSuccsLeft reaches zero, release the predecessor node.
376 /// FIXME: Adjust PredSU height based on MinLatency.
377 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
378 SUnit *PredSU = PredEdge->getSUnit();
380 if (PredEdge->isWeak()) {
381 --PredSU->WeakSuccsLeft;
382 if (PredEdge->isCluster())
383 NextClusterPred = PredSU;
387 if (PredSU->NumSuccsLeft == 0) {
388 dbgs() << "*** Scheduling failed! ***\n";
390 dbgs() << " has been released too many times!\n";
394 --PredSU->NumSuccsLeft;
395 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
396 SchedImpl->releaseBottomNode(PredSU);
399 /// releasePredecessors - Call releasePred on each of SU's predecessors.
400 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
401 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
403 releasePred(SU, &*I);
407 /// This is normally called from the main scheduler loop but may also be invoked
408 /// by the scheduling strategy to perform additional code motion.
409 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
410 MachineBasicBlock::iterator InsertPos) {
411 // Advance RegionBegin if the first instruction moves down.
412 if (&*RegionBegin == MI)
415 // Update the instruction stream.
416 BB->splice(InsertPos, BB, MI);
418 // Update LiveIntervals
419 LIS->handleMove(MI, /*UpdateFlags=*/true);
421 // Recede RegionBegin if an instruction moves above the first.
422 if (RegionBegin == InsertPos)
426 bool ScheduleDAGMI::checkSchedLimit() {
428 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
429 CurrentTop = CurrentBottom;
432 ++NumInstrsScheduled;
437 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
438 /// crossing a scheduling boundary. [begin, end) includes all instructions in
439 /// the region, including the boundary itself and single-instruction regions
440 /// that don't get scheduled.
441 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
442 MachineBasicBlock::iterator begin,
443 MachineBasicBlock::iterator end,
446 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
448 // For convenience remember the end of the liveness region.
450 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
453 // Setup the register pressure trackers for the top scheduled top and bottom
454 // scheduled regions.
455 void ScheduleDAGMI::initRegPressure() {
456 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
457 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
459 // Close the RPTracker to finalize live ins.
460 RPTracker.closeRegion();
462 DEBUG(RPTracker.getPressure().dump(TRI));
464 // Initialize the live ins and live outs.
465 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
466 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
468 // Close one end of the tracker so we can call
469 // getMaxUpward/DownwardPressureDelta before advancing across any
470 // instructions. This converts currently live regs into live ins/outs.
471 TopRPTracker.closeTop();
472 BotRPTracker.closeBottom();
474 // Account for liveness generated by the region boundary.
475 if (LiveRegionEnd != RegionEnd)
476 BotRPTracker.recede();
478 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
480 // Cache the list of excess pressure sets in this region. This will also track
481 // the max pressure in the scheduled code for these sets.
482 RegionCriticalPSets.clear();
483 const std::vector<unsigned> &RegionPressure =
484 RPTracker.getPressure().MaxSetPressure;
485 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
486 unsigned Limit = TRI->getRegPressureSetLimit(i);
487 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
489 << " Actual " << RegionPressure[i] << "\n");
490 if (RegionPressure[i] > Limit)
491 RegionCriticalPSets.push_back(PressureElement(i, 0));
493 DEBUG(dbgs() << "Excess PSets: ";
494 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
495 dbgs() << TRI->getRegPressureSetName(
496 RegionCriticalPSets[i].PSetID) << " ";
500 // FIXME: When the pressure tracker deals in pressure differences then we won't
501 // iterate over all RegionCriticalPSets[i].
503 updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
504 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
505 unsigned ID = RegionCriticalPSets[i].PSetID;
506 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
507 if ((int)NewMaxPressure[ID] > MaxUnits)
508 MaxUnits = NewMaxPressure[ID];
512 /// schedule - Called back from MachineScheduler::runOnMachineFunction
513 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
514 /// only includes instructions that have DAG nodes, not scheduling boundaries.
516 /// This is a skeletal driver, with all the functionality pushed into helpers,
517 /// so that it can be easilly extended by experimental schedulers. Generally,
518 /// implementing MachineSchedStrategy should be sufficient to implement a new
519 /// scheduling algorithm. However, if a scheduler further subclasses
520 /// ScheduleDAGMI then it will want to override this virtual method in order to
521 /// update any specialized state.
522 void ScheduleDAGMI::schedule() {
523 buildDAGWithRegPressure();
525 Topo.InitDAGTopologicalSorting();
529 SmallVector<SUnit*, 8> TopRoots, BotRoots;
530 findRootsAndBiasEdges(TopRoots, BotRoots);
532 // Initialize the strategy before modifying the DAG.
533 // This may initialize a DFSResult to be used for queue priority.
534 SchedImpl->initialize(this);
536 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
537 SUnits[su].dumpAll(this));
538 if (ViewMISchedDAGs) viewGraph();
540 // Initialize ready queues now that the DAG and priority data are finalized.
541 initQueues(TopRoots, BotRoots);
543 bool IsTopNode = false;
544 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
545 assert(!SU->isScheduled && "Node already scheduled");
546 if (!checkSchedLimit())
549 scheduleMI(SU, IsTopNode);
551 updateQueues(SU, IsTopNode);
553 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
558 unsigned BBNum = begin()->getParent()->getNumber();
559 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
565 /// Build the DAG and setup three register pressure trackers.
566 void ScheduleDAGMI::buildDAGWithRegPressure() {
567 // Initialize the register pressure tracker used by buildSchedGraph.
568 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
570 // Account for liveness generate by the region boundary.
571 if (LiveRegionEnd != RegionEnd)
574 // Build the DAG, and compute current register pressure.
575 buildSchedGraph(AA, &RPTracker);
577 // Initialize top/bottom trackers after computing region pressure.
581 /// Apply each ScheduleDAGMutation step in order.
582 void ScheduleDAGMI::postprocessDAG() {
583 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
584 Mutations[i]->apply(this);
588 void ScheduleDAGMI::computeDFSResult() {
590 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
592 ScheduledTrees.clear();
593 DFSResult->resize(SUnits.size());
594 DFSResult->compute(SUnits);
595 ScheduledTrees.resize(DFSResult->getNumSubtrees());
598 void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
599 SmallVectorImpl<SUnit*> &BotRoots) {
600 for (std::vector<SUnit>::iterator
601 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
603 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
605 // Order predecessors so DFSResult follows the critical path.
606 SU->biasCriticalPath();
608 // A SUnit is ready to top schedule if it has no predecessors.
609 if (!I->NumPredsLeft)
610 TopRoots.push_back(SU);
611 // A SUnit is ready to bottom schedule if it has no successors.
612 if (!I->NumSuccsLeft)
613 BotRoots.push_back(SU);
615 ExitSU.biasCriticalPath();
618 /// Identify DAG roots and setup scheduler queues.
619 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
620 ArrayRef<SUnit*> BotRoots) {
621 NextClusterSucc = NULL;
622 NextClusterPred = NULL;
624 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
626 // Nodes with unreleased weak edges can still be roots.
627 // Release top roots in forward order.
628 for (SmallVectorImpl<SUnit*>::const_iterator
629 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
630 SchedImpl->releaseTopNode(*I);
632 // Release bottom roots in reverse order so the higher priority nodes appear
633 // first. This is more natural and slightly more efficient.
634 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
635 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
636 SchedImpl->releaseBottomNode(*I);
639 releaseSuccessors(&EntrySU);
640 releasePredecessors(&ExitSU);
642 SchedImpl->registerRoots();
644 // Advance past initial DebugValues.
645 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
646 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
647 TopRPTracker.setPos(CurrentTop);
649 CurrentBottom = RegionEnd;
652 /// Move an instruction and update register pressure.
653 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
654 // Move the instruction to its new location in the instruction stream.
655 MachineInstr *MI = SU->getInstr();
658 assert(SU->isTopReady() && "node still has unscheduled dependencies");
659 if (&*CurrentTop == MI)
660 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
662 moveInstruction(MI, CurrentTop);
663 TopRPTracker.setPos(MI);
666 // Update top scheduled pressure.
667 TopRPTracker.advance();
668 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
669 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
672 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
673 MachineBasicBlock::iterator priorII =
674 priorNonDebug(CurrentBottom, CurrentTop);
676 CurrentBottom = priorII;
678 if (&*CurrentTop == MI) {
679 CurrentTop = nextIfDebug(++CurrentTop, priorII);
680 TopRPTracker.setPos(CurrentTop);
682 moveInstruction(MI, CurrentBottom);
685 // Update bottom scheduled pressure.
686 BotRPTracker.recede();
687 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
688 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
692 /// Update scheduler queues after scheduling an instruction.
693 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
694 // Release dependent instructions for scheduling.
696 releaseSuccessors(SU);
698 releasePredecessors(SU);
700 SU->isScheduled = true;
703 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
704 if (!ScheduledTrees.test(SubtreeID)) {
705 ScheduledTrees.set(SubtreeID);
706 DFSResult->scheduleTree(SubtreeID);
707 SchedImpl->scheduleTree(SubtreeID);
711 // Notify the scheduling strategy after updating the DAG.
712 SchedImpl->schedNode(SU, IsTopNode);
715 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
716 void ScheduleDAGMI::placeDebugValues() {
717 // If first instruction was a DBG_VALUE then put it back.
719 BB->splice(RegionBegin, BB, FirstDbgValue);
720 RegionBegin = FirstDbgValue;
723 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
724 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
725 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
726 MachineInstr *DbgValue = P.first;
727 MachineBasicBlock::iterator OrigPrevMI = P.second;
728 if (&*RegionBegin == DbgValue)
730 BB->splice(++OrigPrevMI, BB, DbgValue);
731 if (OrigPrevMI == llvm::prior(RegionEnd))
732 RegionEnd = DbgValue;
735 FirstDbgValue = NULL;
738 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
739 void ScheduleDAGMI::dumpSchedule() const {
740 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
741 if (SUnit *SU = getSUnit(&(*MI)))
744 dbgs() << "Missing SUnit\n";
749 //===----------------------------------------------------------------------===//
750 // LoadClusterMutation - DAG post-processing to cluster loads.
751 //===----------------------------------------------------------------------===//
754 /// \brief Post-process the DAG to create cluster edges between neighboring
756 class LoadClusterMutation : public ScheduleDAGMutation {
761 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
762 : SU(su), BaseReg(reg), Offset(ofs) {}
764 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
765 const LoadClusterMutation::LoadInfo &RHS);
767 const TargetInstrInfo *TII;
768 const TargetRegisterInfo *TRI;
770 LoadClusterMutation(const TargetInstrInfo *tii,
771 const TargetRegisterInfo *tri)
772 : TII(tii), TRI(tri) {}
774 virtual void apply(ScheduleDAGMI *DAG);
776 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
780 bool LoadClusterMutation::LoadInfoLess(
781 const LoadClusterMutation::LoadInfo &LHS,
782 const LoadClusterMutation::LoadInfo &RHS) {
783 if (LHS.BaseReg != RHS.BaseReg)
784 return LHS.BaseReg < RHS.BaseReg;
785 return LHS.Offset < RHS.Offset;
788 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
789 ScheduleDAGMI *DAG) {
790 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
791 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
792 SUnit *SU = Loads[Idx];
795 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
796 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
798 if (LoadRecords.size() < 2)
800 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
801 unsigned ClusterLength = 1;
802 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
803 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
808 SUnit *SUa = LoadRecords[Idx].SU;
809 SUnit *SUb = LoadRecords[Idx+1].SU;
810 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
811 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
813 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
814 << SUb->NodeNum << ")\n");
815 // Copy successor edges from SUa to SUb. Interleaving computation
816 // dependent on SUa can prevent load combining due to register reuse.
817 // Predecessor edges do not need to be copied from SUb to SUa since nearby
818 // loads should have effectively the same inputs.
819 for (SUnit::const_succ_iterator
820 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
821 if (SI->getSUnit() == SUb)
823 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
824 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
833 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
834 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
835 // Map DAG NodeNum to store chain ID.
836 DenseMap<unsigned, unsigned> StoreChainIDs;
837 // Map each store chain to a set of dependent loads.
838 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
839 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
840 SUnit *SU = &DAG->SUnits[Idx];
841 if (!SU->getInstr()->mayLoad())
843 unsigned ChainPredID = DAG->SUnits.size();
844 for (SUnit::const_pred_iterator
845 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
847 ChainPredID = PI->getSUnit()->NodeNum;
851 // Check if this chain-like pred has been seen
852 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
853 unsigned NumChains = StoreChainDependents.size();
854 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
855 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
857 StoreChainDependents.resize(NumChains + 1);
858 StoreChainDependents[Result.first->second].push_back(SU);
860 // Iterate over the store chains.
861 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
862 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
865 //===----------------------------------------------------------------------===//
866 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
867 //===----------------------------------------------------------------------===//
870 /// \brief Post-process the DAG to create cluster edges between instructions
871 /// that may be fused by the processor into a single operation.
872 class MacroFusion : public ScheduleDAGMutation {
873 const TargetInstrInfo *TII;
875 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
877 virtual void apply(ScheduleDAGMI *DAG);
881 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
882 /// fused operations.
883 void MacroFusion::apply(ScheduleDAGMI *DAG) {
884 // For now, assume targets can only fuse with the branch.
885 MachineInstr *Branch = DAG->ExitSU.getInstr();
889 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
890 SUnit *SU = &DAG->SUnits[--Idx];
891 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
894 // Create a single weak edge from SU to ExitSU. The only effect is to cause
895 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
896 // need to copy predecessor edges from ExitSU to SU, since top-down
897 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
898 // of SU, we could create an artificial edge from the deepest root, but it
899 // hasn't been needed yet.
900 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
902 assert(Success && "No DAG nodes should be reachable from ExitSU");
904 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
909 //===----------------------------------------------------------------------===//
910 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
911 //===----------------------------------------------------------------------===//
914 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
916 class ConvergingScheduler : public MachineSchedStrategy {
918 /// Represent the type of SchedCandidate found within a single queue.
919 /// pickNodeBidirectional depends on these listed by decreasing priority.
921 NoCand, PhysRegCopy, SingleExcess, SingleCritical, Cluster,
922 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
923 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
927 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
930 /// Policy for scheduling the next instruction in the candidate's zone.
933 unsigned ReduceResIdx;
934 unsigned DemandResIdx;
936 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
939 /// Status of an instruction's critical resource consumption.
940 struct SchedResourceDelta {
941 // Count critical resources in the scheduled region required by SU.
942 unsigned CritResources;
944 // Count critical resources from another region consumed by SU.
945 unsigned DemandedResources;
947 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
949 bool operator==(const SchedResourceDelta &RHS) const {
950 return CritResources == RHS.CritResources
951 && DemandedResources == RHS.DemandedResources;
953 bool operator!=(const SchedResourceDelta &RHS) const {
954 return !operator==(RHS);
958 /// Store the state used by ConvergingScheduler heuristics, required for the
959 /// lifetime of one invocation of pickNode().
960 struct SchedCandidate {
963 // The best SUnit candidate.
966 // The reason for this candidate.
969 // Register pressure values for the best candidate.
970 RegPressureDelta RPDelta;
972 // Critical resource consumption of the best candidate.
973 SchedResourceDelta ResDelta;
975 SchedCandidate(const CandPolicy &policy)
976 : Policy(policy), SU(NULL), Reason(NoCand) {}
978 bool isValid() const { return SU; }
980 // Copy the status of another candidate without changing policy.
981 void setBest(SchedCandidate &Best) {
982 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
984 Reason = Best.Reason;
985 RPDelta = Best.RPDelta;
986 ResDelta = Best.ResDelta;
989 void initResourceDelta(const ScheduleDAGMI *DAG,
990 const TargetSchedModel *SchedModel);
993 /// Summarize the unscheduled region.
994 struct SchedRemainder {
995 // Critical path through the DAG in expected latency.
996 unsigned CriticalPath;
998 // Unscheduled resources
999 SmallVector<unsigned, 16> RemainingCounts;
1000 // Critical resource for the unscheduled zone.
1001 unsigned CritResIdx;
1002 // Number of micro-ops left to schedule.
1003 unsigned RemainingMicroOps;
1007 RemainingCounts.clear();
1009 RemainingMicroOps = 0;
1012 SchedRemainder() { reset(); }
1014 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
1016 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
1017 if (!SchedModel->hasInstrSchedModel())
1021 RemainingMicroOps * SchedModel->getMicroOpFactor(),
1022 RemainingCounts[CritResIdx]);
1026 /// Each Scheduling boundary is associated with ready queues. It tracks the
1027 /// current cycle in the direction of movement, and maintains the state
1028 /// of "hazards" and other interlocks at the current cycle.
1029 struct SchedBoundary {
1031 const TargetSchedModel *SchedModel;
1032 SchedRemainder *Rem;
1034 ReadyQueue Available;
1038 // For heuristics, keep a list of the nodes that immediately depend on the
1039 // most recently scheduled node.
1040 SmallPtrSet<const SUnit*, 8> NextSUs;
1042 ScheduleHazardRecognizer *HazardRec;
1045 unsigned IssueCount;
1047 /// MinReadyCycle - Cycle of the soonest available instruction.
1048 unsigned MinReadyCycle;
1050 // The expected latency of the critical path in this scheduled zone.
1051 unsigned ExpectedLatency;
1053 // Resources used in the scheduled zone beyond this boundary.
1054 SmallVector<unsigned, 16> ResourceCounts;
1056 // Cache the critical resources ID in this scheduled zone.
1057 unsigned CritResIdx;
1059 // Is the scheduled region resource limited vs. latency limited.
1060 bool IsResourceLimited;
1062 unsigned ExpectedCount;
1065 // Remember the greatest min operand latency.
1066 unsigned MaxMinLatency;
1070 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1075 CheckPending = false;
1080 MinReadyCycle = UINT_MAX;
1081 ExpectedLatency = 0;
1082 ResourceCounts.resize(1);
1083 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1085 IsResourceLimited = false;
1090 // Reserve a zero-count for invalid CritResIdx.
1091 ResourceCounts.resize(1);
1094 /// Pending queues extend the ready queues with the same ID and the
1095 /// PendingFlag set.
1096 SchedBoundary(unsigned ID, const Twine &Name):
1097 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1098 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1103 ~SchedBoundary() { delete HazardRec; }
1105 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1106 SchedRemainder *rem);
1108 bool isTop() const {
1109 return Available.getID() == ConvergingScheduler::TopQID;
1112 unsigned getUnscheduledLatency(SUnit *SU) const {
1114 return SU->getHeight();
1115 return SU->getDepth() + SU->Latency;
1118 unsigned getCriticalCount() const {
1119 return ResourceCounts[CritResIdx];
1122 bool checkHazard(SUnit *SU);
1124 void setLatencyPolicy(CandPolicy &Policy);
1126 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1130 void countResource(unsigned PIdx, unsigned Cycles);
1132 void bumpNode(SUnit *SU);
1134 void releasePending();
1136 void removeReady(SUnit *SU);
1138 SUnit *pickOnlyChoice();
1143 const TargetSchedModel *SchedModel;
1144 const TargetRegisterInfo *TRI;
1146 // State of the top and bottom scheduled instruction boundaries.
1152 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1159 ConvergingScheduler():
1160 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1162 virtual void initialize(ScheduleDAGMI *dag);
1164 virtual SUnit *pickNode(bool &IsTopNode);
1166 virtual void schedNode(SUnit *SU, bool IsTopNode);
1168 virtual void releaseTopNode(SUnit *SU);
1170 virtual void releaseBottomNode(SUnit *SU);
1172 virtual void registerRoots();
1176 ConvergingScheduler::SchedBoundary &CriticalZone,
1177 ConvergingScheduler::SchedCandidate &CriticalCand,
1178 ConvergingScheduler::SchedBoundary &OppositeZone,
1179 ConvergingScheduler::SchedCandidate &OppositeCand);
1181 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1182 ConvergingScheduler::SchedCandidate &BotCand);
1184 void tryCandidate(SchedCandidate &Cand,
1185 SchedCandidate &TryCand,
1186 SchedBoundary &Zone,
1187 const RegPressureTracker &RPTracker,
1188 RegPressureTracker &TempTracker);
1190 SUnit *pickNodeBidirectional(bool &IsTopNode);
1192 void pickNodeFromQueue(SchedBoundary &Zone,
1193 const RegPressureTracker &RPTracker,
1194 SchedCandidate &Candidate);
1196 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
1199 void traceCandidate(const SchedCandidate &Cand);
1204 void ConvergingScheduler::SchedRemainder::
1205 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1207 if (!SchedModel->hasInstrSchedModel())
1209 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1210 for (std::vector<SUnit>::iterator
1211 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1212 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1213 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1214 for (TargetSchedModel::ProcResIter
1215 PI = SchedModel->getWriteProcResBegin(SC),
1216 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1217 unsigned PIdx = PI->ProcResourceIdx;
1218 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1219 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1222 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1223 PIdx != PEnd; ++PIdx) {
1224 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1225 >= (int)SchedModel->getLatencyFactor()) {
1231 void ConvergingScheduler::SchedBoundary::
1232 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1235 SchedModel = smodel;
1237 if (SchedModel->hasInstrSchedModel())
1238 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1241 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1243 SchedModel = DAG->getSchedModel();
1246 Rem.init(DAG, SchedModel);
1247 Top.init(DAG, SchedModel, &Rem);
1248 Bot.init(DAG, SchedModel, &Rem);
1250 // Initialize resource counts.
1252 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1253 // are disabled, then these HazardRecs will be disabled.
1254 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1255 const TargetMachine &TM = DAG->MF.getTarget();
1256 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1257 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1259 assert((!ForceTopDown || !ForceBottomUp) &&
1260 "-misched-topdown incompatible with -misched-bottomup");
1263 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1264 if (SU->isScheduled)
1267 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1269 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1270 unsigned MinLatency = I->getMinLatency();
1272 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
1274 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1275 SU->TopReadyCycle = PredReadyCycle + MinLatency;
1277 Top.releaseNode(SU, SU->TopReadyCycle);
1280 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1281 if (SU->isScheduled)
1284 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1286 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1290 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1291 unsigned MinLatency = I->getMinLatency();
1293 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
1295 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1296 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
1298 Bot.releaseNode(SU, SU->BotReadyCycle);
1301 void ConvergingScheduler::registerRoots() {
1302 Rem.CriticalPath = DAG->ExitSU.getDepth();
1303 // Some roots may not feed into ExitSU. Check all of them in case.
1304 for (std::vector<SUnit*>::const_iterator
1305 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1306 if ((*I)->getDepth() > Rem.CriticalPath)
1307 Rem.CriticalPath = (*I)->getDepth();
1309 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1312 /// Does this SU have a hazard within the current instruction group.
1314 /// The scheduler supports two modes of hazard recognition. The first is the
1315 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1316 /// supports highly complicated in-order reservation tables
1317 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1319 /// The second is a streamlined mechanism that checks for hazards based on
1320 /// simple counters that the scheduler itself maintains. It explicitly checks
1321 /// for instruction dispatch limitations, including the number of micro-ops that
1322 /// can dispatch per cycle.
1324 /// TODO: Also check whether the SU must start a new group.
1325 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1326 if (HazardRec->isEnabled())
1327 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1329 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1330 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1331 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1332 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1338 /// Compute the remaining latency to determine whether ILP should be increased.
1339 void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1340 // FIXME: compile time. In all, we visit four queues here one we should only
1341 // need to visit the one that was last popped if we cache the result.
1342 unsigned RemLatency = 0;
1343 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1345 unsigned L = getUnscheduledLatency(*I);
1346 DEBUG(dbgs() << " " << Available.getName()
1347 << " RemLatency SU(" << (*I)->NodeNum << ") " << L << '\n');
1351 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1353 unsigned L = getUnscheduledLatency(*I);
1357 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1358 DEBUG(dbgs() << " " << Available.getName()
1359 << " ExpectedLatency " << ExpectedLatency
1360 << " CP Limit " << CriticalPathLimit << '\n');
1361 if (RemLatency + ExpectedLatency >= CriticalPathLimit
1362 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1363 Policy.ReduceLatency = true;
1364 DEBUG(dbgs() << " Increase ILP: " << Available.getName() << '\n');
1368 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1369 unsigned ReadyCycle) {
1371 if (ReadyCycle < MinReadyCycle)
1372 MinReadyCycle = ReadyCycle;
1374 // Check for interlocks first. For the purpose of other heuristics, an
1375 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1376 if (ReadyCycle > CurrCycle || checkHazard(SU))
1381 // Record this node as an immediate dependent of the scheduled node.
1385 /// Move the boundary of scheduled code by one cycle.
1386 void ConvergingScheduler::SchedBoundary::bumpCycle() {
1387 unsigned Width = SchedModel->getIssueWidth();
1388 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
1390 unsigned NextCycle = CurrCycle + 1;
1391 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1392 if (MinReadyCycle > NextCycle) {
1394 NextCycle = MinReadyCycle;
1397 if (!HazardRec->isEnabled()) {
1398 // Bypass HazardRec virtual calls.
1399 CurrCycle = NextCycle;
1402 // Bypass getHazardType calls in case of long latency.
1403 for (; CurrCycle != NextCycle; ++CurrCycle) {
1405 HazardRec->AdvanceCycle();
1407 HazardRec->RecedeCycle();
1410 CheckPending = true;
1411 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1413 DEBUG(dbgs() << " " << Available.getName()
1414 << " Cycle: " << CurrCycle << '\n');
1417 /// Add the given processor resource to this scheduled zone.
1418 void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1420 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1421 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1422 << " +(" << Cycles << "x" << Factor
1423 << ") / " << SchedModel->getLatencyFactor() << '\n');
1425 unsigned Count = Factor * Cycles;
1426 ResourceCounts[PIdx] += Count;
1427 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1428 Rem->RemainingCounts[PIdx] -= Count;
1430 // Check if this resource exceeds the current critical resource by a full
1431 // cycle. If so, it becomes the critical resource.
1432 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1433 >= (int)SchedModel->getLatencyFactor()) {
1435 DEBUG(dbgs() << " *** Critical resource "
1436 << SchedModel->getProcResource(PIdx)->Name << " x"
1437 << ResourceCounts[PIdx] << '\n');
1441 /// Move the boundary of scheduled code by one SUnit.
1442 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1443 // Update the reservation table.
1444 if (HazardRec->isEnabled()) {
1445 if (!isTop() && SU->isCall) {
1446 // Calls are scheduled with their preceding instructions. For bottom-up
1447 // scheduling, clear the pipeline state before emitting.
1450 HazardRec->EmitInstruction(SU);
1452 // Update resource counts and critical resource.
1453 if (SchedModel->hasInstrSchedModel()) {
1454 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1455 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1456 for (TargetSchedModel::ProcResIter
1457 PI = SchedModel->getWriteProcResBegin(SC),
1458 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1459 countResource(PI->ProcResourceIdx, PI->Cycles);
1463 if (SU->getDepth() > ExpectedLatency)
1464 ExpectedLatency = SU->getDepth();
1467 if (SU->getHeight() > ExpectedLatency)
1468 ExpectedLatency = SU->getHeight();
1471 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1473 // Check the instruction group dispatch limit.
1474 // TODO: Check if this SU must end a dispatch group.
1475 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
1477 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1478 // issue width. However, we commonly reach the maximum. In this case
1479 // opportunistically bump the cycle to avoid uselessly checking everything in
1480 // the readyQ. Furthermore, a single instruction may produce more than one
1481 // cycle's worth of micro-ops.
1482 if (IssueCount >= SchedModel->getIssueWidth()) {
1483 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
1488 /// Release pending ready nodes in to the available queue. This makes them
1489 /// visible to heuristics.
1490 void ConvergingScheduler::SchedBoundary::releasePending() {
1491 // If the available queue is empty, it is safe to reset MinReadyCycle.
1492 if (Available.empty())
1493 MinReadyCycle = UINT_MAX;
1495 // Check to see if any of the pending instructions are ready to issue. If
1496 // so, add them to the available queue.
1497 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1498 SUnit *SU = *(Pending.begin()+i);
1499 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1501 if (ReadyCycle < MinReadyCycle)
1502 MinReadyCycle = ReadyCycle;
1504 if (ReadyCycle > CurrCycle)
1507 if (checkHazard(SU))
1511 Pending.remove(Pending.begin()+i);
1514 DEBUG(if (!Pending.empty()) Pending.dump());
1515 CheckPending = false;
1518 /// Remove SU from the ready set for this boundary.
1519 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1520 if (Available.isInQueue(SU))
1521 Available.remove(Available.find(SU));
1523 assert(Pending.isInQueue(SU) && "bad ready count");
1524 Pending.remove(Pending.find(SU));
1528 /// If this queue only has one ready candidate, return it. As a side effect,
1529 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1530 /// one node is ready. If multiple instructions are ready, return NULL.
1531 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1535 if (IssueCount > 0) {
1536 // Defer any ready instrs that now have a hazard.
1537 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1538 if (checkHazard(*I)) {
1540 I = Available.remove(I);
1546 for (unsigned i = 0; Available.empty(); ++i) {
1547 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1548 "permanent hazard"); (void)i;
1552 if (Available.size() == 1)
1553 return *Available.begin();
1557 /// Record the candidate policy for opposite zones with different critical
1560 /// If the CriticalZone is latency limited, don't force a policy for the
1561 /// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
1562 void ConvergingScheduler::balanceZones(
1563 ConvergingScheduler::SchedBoundary &CriticalZone,
1564 ConvergingScheduler::SchedCandidate &CriticalCand,
1565 ConvergingScheduler::SchedBoundary &OppositeZone,
1566 ConvergingScheduler::SchedCandidate &OppositeCand) {
1568 if (!CriticalZone.IsResourceLimited)
1570 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
1572 SchedRemainder *Rem = CriticalZone.Rem;
1574 // If the critical zone is overconsuming a resource relative to the
1575 // remainder, try to reduce it.
1576 unsigned RemainingCritCount =
1577 Rem->RemainingCounts[CriticalZone.CritResIdx];
1578 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
1579 > (int)SchedModel->getLatencyFactor()) {
1580 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1581 DEBUG(dbgs() << " Balance " << CriticalZone.Available.getName()
1583 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1586 // If the other zone is underconsuming a resource relative to the full zone,
1587 // try to increase it.
1588 unsigned OppositeCount =
1589 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1590 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1591 > (int)SchedModel->getLatencyFactor()) {
1592 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1593 DEBUG(dbgs() << " Balance " << OppositeZone.Available.getName()
1595 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1600 /// Determine if the scheduled zones exceed resource limits or critical path and
1601 /// set each candidate's ReduceHeight policy accordingly.
1602 void ConvergingScheduler::checkResourceLimits(
1603 ConvergingScheduler::SchedCandidate &TopCand,
1604 ConvergingScheduler::SchedCandidate &BotCand) {
1606 // Set ReduceLatency to true if needed.
1607 Bot.setLatencyPolicy(BotCand.Policy);
1608 Top.setLatencyPolicy(TopCand.Policy);
1610 // Handle resource-limited regions.
1611 if (Top.IsResourceLimited && Bot.IsResourceLimited
1612 && Top.CritResIdx == Bot.CritResIdx) {
1613 // If the scheduled critical resource in both zones is no longer the
1614 // critical remaining resource, attempt to reduce resource height both ways.
1615 if (Top.CritResIdx != Rem.CritResIdx) {
1616 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1617 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1618 DEBUG(dbgs() << " Reduce scheduled "
1619 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1623 // Handle latency-limited regions.
1624 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1625 // If the total scheduled expected latency exceeds the region's critical
1626 // path then reduce latency both ways.
1628 // Just because a zone is not resource limited does not mean it is latency
1629 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1630 // to exceed expected latency.
1631 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1632 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1633 TopCand.Policy.ReduceLatency = true;
1634 BotCand.Policy.ReduceLatency = true;
1635 DEBUG(dbgs() << " Reduce scheduled latency " << Top.ExpectedLatency
1636 << " + " << Bot.ExpectedLatency << '\n');
1640 // The critical resource is different in each zone, so request balancing.
1642 // Compute the cost of each zone.
1643 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1644 Top.ExpectedCount = std::max(
1645 Top.getCriticalCount(),
1646 Top.ExpectedCount * SchedModel->getLatencyFactor());
1647 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1648 Bot.ExpectedCount = std::max(
1649 Bot.getCriticalCount(),
1650 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1652 balanceZones(Top, TopCand, Bot, BotCand);
1653 balanceZones(Bot, BotCand, Top, TopCand);
1656 void ConvergingScheduler::SchedCandidate::
1657 initResourceDelta(const ScheduleDAGMI *DAG,
1658 const TargetSchedModel *SchedModel) {
1659 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1662 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1663 for (TargetSchedModel::ProcResIter
1664 PI = SchedModel->getWriteProcResBegin(SC),
1665 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1666 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1667 ResDelta.CritResources += PI->Cycles;
1668 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1669 ResDelta.DemandedResources += PI->Cycles;
1673 /// Return true if this heuristic determines order.
1674 static bool tryLess(int TryVal, int CandVal,
1675 ConvergingScheduler::SchedCandidate &TryCand,
1676 ConvergingScheduler::SchedCandidate &Cand,
1677 ConvergingScheduler::CandReason Reason) {
1678 if (TryVal < CandVal) {
1679 TryCand.Reason = Reason;
1682 if (TryVal > CandVal) {
1683 if (Cand.Reason > Reason)
1684 Cand.Reason = Reason;
1690 static bool tryGreater(int TryVal, int CandVal,
1691 ConvergingScheduler::SchedCandidate &TryCand,
1692 ConvergingScheduler::SchedCandidate &Cand,
1693 ConvergingScheduler::CandReason Reason) {
1694 if (TryVal > CandVal) {
1695 TryCand.Reason = Reason;
1698 if (TryVal < CandVal) {
1699 if (Cand.Reason > Reason)
1700 Cand.Reason = Reason;
1706 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1707 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1710 /// Minimize physical register live ranges. Regalloc wants them adjacent to
1711 /// their physreg def/use.
1713 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
1714 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
1715 /// with the operation that produces or consumes the physreg. We'll do this when
1716 /// regalloc has support for parallel copies.
1717 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
1718 const MachineInstr *MI = SU->getInstr();
1722 unsigned ScheduledOper = isTop ? 1 : 0;
1723 unsigned UnscheduledOper = isTop ? 0 : 1;
1724 // If we have already scheduled the physreg produce/consumer, immediately
1725 // schedule the copy.
1726 if (TargetRegisterInfo::isPhysicalRegister(
1727 MI->getOperand(ScheduledOper).getReg()))
1729 // If the physreg is at the boundary, defer it. Otherwise schedule it
1730 // immediately to free the dependent. We can hoist the copy later.
1731 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
1732 if (TargetRegisterInfo::isPhysicalRegister(
1733 MI->getOperand(UnscheduledOper).getReg()))
1734 return AtBoundary ? -1 : 1;
1738 /// Apply a set of heursitics to a new candidate. Heuristics are currently
1739 /// hierarchical. This may be more efficient than a graduated cost model because
1740 /// we don't need to evaluate all aspects of the model for each node in the
1741 /// queue. But it's really done to make the heuristics easier to debug and
1742 /// statistically analyze.
1744 /// \param Cand provides the policy and current best candidate.
1745 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1746 /// \param Zone describes the scheduled zone that we are extending.
1747 /// \param RPTracker describes reg pressure within the scheduled zone.
1748 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
1749 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1750 SchedCandidate &TryCand,
1751 SchedBoundary &Zone,
1752 const RegPressureTracker &RPTracker,
1753 RegPressureTracker &TempTracker) {
1755 // Always initialize TryCand's RPDelta.
1756 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1757 DAG->getRegionCriticalPSets(),
1758 DAG->getRegPressure().MaxSetPressure);
1760 // Initialize the candidate if needed.
1761 if (!Cand.isValid()) {
1762 TryCand.Reason = NodeOrder;
1766 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
1767 biasPhysRegCopy(Cand.SU, Zone.isTop()),
1768 TryCand, Cand, PhysRegCopy))
1771 // Avoid exceeding the target's limit.
1772 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1773 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1775 if (Cand.Reason == SingleExcess)
1776 Cand.Reason = MultiPressure;
1778 // Avoid increasing the max critical pressure in the scheduled region.
1779 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1780 Cand.RPDelta.CriticalMax.UnitIncrease,
1781 TryCand, Cand, SingleCritical))
1783 if (Cand.Reason == SingleCritical)
1784 Cand.Reason = MultiPressure;
1786 // Keep clustered nodes together to encourage downstream peephole
1787 // optimizations which may reduce resource requirements.
1789 // This is a best effort to set things up for a post-RA pass. Optimizations
1790 // like generating loads of multiple registers should ideally be done within
1791 // the scheduler pass by combining the loads during DAG postprocessing.
1792 const SUnit *NextClusterSU =
1793 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1794 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1795 TryCand, Cand, Cluster))
1797 // Currently, weak edges are for clustering, so we hard-code that reason.
1798 // However, deferring the current TryCand will not change Cand's reason.
1799 CandReason OrigReason = Cand.Reason;
1800 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1801 getWeakLeft(Cand.SU, Zone.isTop()),
1802 TryCand, Cand, Cluster)) {
1803 Cand.Reason = OrigReason;
1806 // Avoid critical resource consumption and balance the schedule.
1807 TryCand.initResourceDelta(DAG, SchedModel);
1808 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1809 TryCand, Cand, ResourceReduce))
1811 if (tryGreater(TryCand.ResDelta.DemandedResources,
1812 Cand.ResDelta.DemandedResources,
1813 TryCand, Cand, ResourceDemand))
1816 // Avoid serializing long latency dependence chains.
1817 if (Cand.Policy.ReduceLatency) {
1819 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1820 > Zone.ExpectedCount) {
1821 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1822 TryCand, Cand, TopDepthReduce))
1825 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1826 TryCand, Cand, TopPathReduce))
1830 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1831 > Zone.ExpectedCount) {
1832 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1833 TryCand, Cand, BotHeightReduce))
1836 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1837 TryCand, Cand, BotPathReduce))
1842 // Avoid increasing the max pressure of the entire region.
1843 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1844 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1846 if (Cand.Reason == SingleMax)
1847 Cand.Reason = MultiPressure;
1849 // Prefer immediate defs/users of the last scheduled instruction. This is a
1850 // nice pressure avoidance strategy that also conserves the processor's
1851 // register renaming resources and keeps the machine code readable.
1852 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1853 TryCand, Cand, NextDefUse))
1856 // Fall through to original instruction order.
1857 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1858 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1859 TryCand.Reason = NodeOrder;
1863 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1864 /// more desirable than RHS from scheduling standpoint.
1865 static bool compareRPDelta(const RegPressureDelta &LHS,
1866 const RegPressureDelta &RHS) {
1867 // Compare each component of pressure in decreasing order of importance
1868 // without checking if any are valid. Invalid PressureElements are assumed to
1869 // have UnitIncrease==0, so are neutral.
1871 // Avoid increasing the max critical pressure in the scheduled region.
1872 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1873 DEBUG(dbgs() << " RP excess top - bot: "
1874 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
1875 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1877 // Avoid increasing the max critical pressure in the scheduled region.
1878 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1879 DEBUG(dbgs() << " RP critical top - bot: "
1880 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1882 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1884 // Avoid increasing the max pressure of the entire region.
1885 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1886 DEBUG(dbgs() << " RP current top - bot: "
1887 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1889 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1895 const char *ConvergingScheduler::getReasonStr(
1896 ConvergingScheduler::CandReason Reason) {
1898 case NoCand: return "NOCAND ";
1899 case PhysRegCopy: return "PREG-COPY";
1900 case SingleExcess: return "REG-EXCESS";
1901 case SingleCritical: return "REG-CRIT ";
1902 case Cluster: return "CLUSTER ";
1903 case SingleMax: return "REG-MAX ";
1904 case MultiPressure: return "REG-MULTI ";
1905 case ResourceReduce: return "RES-REDUCE";
1906 case ResourceDemand: return "RES-DEMAND";
1907 case TopDepthReduce: return "TOP-DEPTH ";
1908 case TopPathReduce: return "TOP-PATH ";
1909 case BotHeightReduce:return "BOT-HEIGHT";
1910 case BotPathReduce: return "BOT-PATH ";
1911 case NextDefUse: return "DEF-USE ";
1912 case NodeOrder: return "ORDER ";
1914 llvm_unreachable("Unknown reason!");
1917 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
1919 unsigned ResIdx = 0;
1920 unsigned Latency = 0;
1921 switch (Cand.Reason) {
1925 P = Cand.RPDelta.Excess;
1927 case SingleCritical:
1928 P = Cand.RPDelta.CriticalMax;
1931 P = Cand.RPDelta.CurrentMax;
1933 case ResourceReduce:
1934 ResIdx = Cand.Policy.ReduceResIdx;
1936 case ResourceDemand:
1937 ResIdx = Cand.Policy.DemandResIdx;
1939 case TopDepthReduce:
1940 Latency = Cand.SU->getDepth();
1943 Latency = Cand.SU->getHeight();
1945 case BotHeightReduce:
1946 Latency = Cand.SU->getHeight();
1949 Latency = Cand.SU->getDepth();
1952 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
1954 dbgs() << " " << TRI->getRegPressureSetName(P.PSetID)
1955 << ":" << P.UnitIncrease << " ";
1959 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
1963 dbgs() << " " << Latency << " cycles ";
1970 /// Pick the best candidate from the top queue.
1972 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1973 /// DAG building. To adjust for the current scheduling location we need to
1974 /// maintain the number of vreg uses remaining to be top-scheduled.
1975 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1976 const RegPressureTracker &RPTracker,
1977 SchedCandidate &Cand) {
1978 ReadyQueue &Q = Zone.Available;
1982 // getMaxPressureDelta temporarily modifies the tracker.
1983 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1985 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
1987 SchedCandidate TryCand(Cand.Policy);
1989 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1990 if (TryCand.Reason != NoCand) {
1991 // Initialize resource delta if needed in case future heuristics query it.
1992 if (TryCand.ResDelta == SchedResourceDelta())
1993 TryCand.initResourceDelta(DAG, SchedModel);
1994 Cand.setBest(TryCand);
1995 DEBUG(traceCandidate(Cand));
2000 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
2002 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2003 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
2006 /// Pick the best candidate node from either the top or bottom queue.
2007 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
2008 // Schedule as far as possible in the direction of no choice. This is most
2009 // efficient, but also provides the best heuristics for CriticalPSets.
2010 if (SUnit *SU = Bot.pickOnlyChoice()) {
2012 DEBUG(dbgs() << "Pick Top NOCAND\n");
2015 if (SUnit *SU = Top.pickOnlyChoice()) {
2017 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2020 CandPolicy NoPolicy;
2021 SchedCandidate BotCand(NoPolicy);
2022 SchedCandidate TopCand(NoPolicy);
2023 checkResourceLimits(TopCand, BotCand);
2025 // Prefer bottom scheduling when heuristics are silent.
2026 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2027 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2029 // If either Q has a single candidate that provides the least increase in
2030 // Excess pressure, we can immediately schedule from that Q.
2032 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2033 // affects picking from either Q. If scheduling in one direction must
2034 // increase pressure for one of the excess PSets, then schedule in that
2035 // direction first to provide more freedom in the other direction.
2036 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
2038 tracePick(BotCand, IsTopNode);
2041 // Check if the top Q has a better candidate.
2042 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2043 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2045 // If either Q has a single candidate that minimizes pressure above the
2046 // original region's pressure pick it.
2047 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
2048 if (TopCand.Reason < BotCand.Reason) {
2050 tracePick(TopCand, IsTopNode);
2054 tracePick(BotCand, IsTopNode);
2057 // Check for a salient pressure difference and pick the best from either side.
2058 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
2060 tracePick(TopCand, IsTopNode);
2063 // Otherwise prefer the bottom candidate, in node order if all else failed.
2064 if (TopCand.Reason < BotCand.Reason) {
2066 tracePick(TopCand, IsTopNode);
2070 tracePick(BotCand, IsTopNode);
2074 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2075 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2076 if (DAG->top() == DAG->bottom()) {
2077 assert(Top.Available.empty() && Top.Pending.empty() &&
2078 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2084 SU = Top.pickOnlyChoice();
2086 CandPolicy NoPolicy;
2087 SchedCandidate TopCand(NoPolicy);
2088 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2089 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2094 else if (ForceBottomUp) {
2095 SU = Bot.pickOnlyChoice();
2097 CandPolicy NoPolicy;
2098 SchedCandidate BotCand(NoPolicy);
2099 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2100 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2106 SU = pickNodeBidirectional(IsTopNode);
2108 } while (SU->isScheduled);
2110 if (SU->isTopReady())
2111 Top.removeReady(SU);
2112 if (SU->isBottomReady())
2113 Bot.removeReady(SU);
2115 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2119 void ConvergingScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2121 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2124 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2126 // Find already scheduled copies with a single physreg dependence and move
2127 // them just above the scheduled instruction.
2128 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2130 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2132 SUnit *DepSU = I->getSUnit();
2133 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2135 MachineInstr *Copy = DepSU->getInstr();
2136 if (!Copy->isCopy())
2138 DEBUG(dbgs() << " Rescheduling physreg copy ";
2139 I->getSUnit()->dump(DAG));
2140 DAG->moveInstruction(Copy, InsertPos);
2144 /// Update the scheduler's state after scheduling a node. This is the same node
2145 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2146 /// it's state based on the current cycle before MachineSchedStrategy does.
2148 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2149 /// them here. See comments in biasPhysRegCopy.
2150 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2152 SU->TopReadyCycle = Top.CurrCycle;
2154 if (SU->hasPhysRegUses)
2155 reschedulePhysRegCopies(SU, true);
2158 SU->BotReadyCycle = Bot.CurrCycle;
2160 if (SU->hasPhysRegDefs)
2161 reschedulePhysRegCopies(SU, false);
2165 /// Create the standard converging machine scheduler. This will be used as the
2166 /// default scheduler if the target does not set a default.
2167 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2168 assert((!ForceTopDown || !ForceBottomUp) &&
2169 "-misched-topdown incompatible with -misched-bottomup");
2170 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2171 // Register DAG post-processors.
2172 if (EnableLoadCluster)
2173 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2174 if (EnableMacroFusion)
2175 DAG->addMutation(new MacroFusion(DAG->TII));
2178 static MachineSchedRegistry
2179 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2180 createConvergingSched);
2182 //===----------------------------------------------------------------------===//
2183 // ILP Scheduler. Currently for experimental analysis of heuristics.
2184 //===----------------------------------------------------------------------===//
2187 /// \brief Order nodes by the ILP metric.
2189 const SchedDFSResult *DFSResult;
2190 const BitVector *ScheduledTrees;
2193 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2195 /// \brief Apply a less-than relation on node priority.
2197 /// (Return true if A comes after B in the Q.)
2198 bool operator()(const SUnit *A, const SUnit *B) const {
2199 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2200 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2201 if (SchedTreeA != SchedTreeB) {
2202 // Unscheduled trees have lower priority.
2203 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2204 return ScheduledTrees->test(SchedTreeB);
2206 // Trees with shallower connections have have lower priority.
2207 if (DFSResult->getSubtreeLevel(SchedTreeA)
2208 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2209 return DFSResult->getSubtreeLevel(SchedTreeA)
2210 < DFSResult->getSubtreeLevel(SchedTreeB);
2214 return DFSResult->getILP(A) < DFSResult->getILP(B);
2216 return DFSResult->getILP(A) > DFSResult->getILP(B);
2220 /// \brief Schedule based on the ILP metric.
2221 class ILPScheduler : public MachineSchedStrategy {
2222 /// In case all subtrees are eventually connected to a common root through
2223 /// data dependence (e.g. reduction), place an upper limit on their size.
2225 /// FIXME: A subtree limit is generally good, but in the situation commented
2226 /// above, where multiple similar subtrees feed a common root, we should
2227 /// only split at a point where the resulting subtrees will be balanced.
2228 /// (a motivating test case must be found).
2229 static const unsigned SubtreeLimit = 16;
2234 std::vector<SUnit*> ReadyQ;
2236 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2238 virtual void initialize(ScheduleDAGMI *dag) {
2240 DAG->computeDFSResult();
2241 Cmp.DFSResult = DAG->getDFSResult();
2242 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
2246 virtual void registerRoots() {
2247 // Restore the heap in ReadyQ with the updated DFS results.
2248 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2251 /// Implement MachineSchedStrategy interface.
2252 /// -----------------------------------------
2254 /// Callback to select the highest priority node from the ready Q.
2255 virtual SUnit *pickNode(bool &IsTopNode) {
2256 if (ReadyQ.empty()) return NULL;
2257 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2258 SUnit *SU = ReadyQ.back();
2261 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
2262 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2263 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2264 << DAG->getDFSResult()->getSubtreeLevel(
2265 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
2266 << "Scheduling " << *SU->getInstr());
2270 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2271 virtual void scheduleTree(unsigned SubtreeID) {
2272 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2275 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2276 /// DFSResults, and resort the priority Q.
2277 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2278 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2281 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2283 virtual void releaseBottomNode(SUnit *SU) {
2284 ReadyQ.push_back(SU);
2285 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2290 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2291 return new ScheduleDAGMI(C, new ILPScheduler(true));
2293 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2294 return new ScheduleDAGMI(C, new ILPScheduler(false));
2296 static MachineSchedRegistry ILPMaxRegistry(
2297 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2298 static MachineSchedRegistry ILPMinRegistry(
2299 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2301 //===----------------------------------------------------------------------===//
2302 // Machine Instruction Shuffler for Correctness Testing
2303 //===----------------------------------------------------------------------===//
2307 /// Apply a less-than relation on the node order, which corresponds to the
2308 /// instruction order prior to scheduling. IsReverse implements greater-than.
2309 template<bool IsReverse>
2311 bool operator()(SUnit *A, SUnit *B) const {
2313 return A->NodeNum > B->NodeNum;
2315 return A->NodeNum < B->NodeNum;
2319 /// Reorder instructions as much as possible.
2320 class InstructionShuffler : public MachineSchedStrategy {
2324 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2325 // gives nodes with a higher number higher priority causing the latest
2326 // instructions to be scheduled first.
2327 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2329 // When scheduling bottom-up, use greater-than as the queue priority.
2330 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2333 InstructionShuffler(bool alternate, bool topdown)
2334 : IsAlternating(alternate), IsTopDown(topdown) {}
2336 virtual void initialize(ScheduleDAGMI *) {
2341 /// Implement MachineSchedStrategy interface.
2342 /// -----------------------------------------
2344 virtual SUnit *pickNode(bool &IsTopNode) {
2348 if (TopQ.empty()) return NULL;
2351 } while (SU->isScheduled);
2356 if (BottomQ.empty()) return NULL;
2359 } while (SU->isScheduled);
2363 IsTopDown = !IsTopDown;
2367 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2369 virtual void releaseTopNode(SUnit *SU) {
2372 virtual void releaseBottomNode(SUnit *SU) {
2378 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2379 bool Alternate = !ForceTopDown && !ForceBottomUp;
2380 bool TopDown = !ForceBottomUp;
2381 assert((TopDown || !ForceTopDown) &&
2382 "-misched-topdown incompatible with -misched-bottomup");
2383 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2385 static MachineSchedRegistry ShufflerRegistry(
2386 "shuffle", "Shuffle machine instructions alternating directions",
2387 createInstructionShuffler);
2390 //===----------------------------------------------------------------------===//
2391 // GraphWriter support for ScheduleDAGMI.
2392 //===----------------------------------------------------------------------===//
2397 template<> struct GraphTraits<
2398 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2401 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2403 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2405 static std::string getGraphName(const ScheduleDAG *G) {
2406 return G->MF.getName();
2409 static bool renderGraphFromBottomUp() {
2413 static bool isNodeHidden(const SUnit *Node) {
2414 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2417 static bool hasNodeAddressLabel(const SUnit *Node,
2418 const ScheduleDAG *Graph) {
2422 /// If you want to override the dot attributes printed for a particular
2423 /// edge, override this method.
2424 static std::string getEdgeAttributes(const SUnit *Node,
2426 const ScheduleDAG *Graph) {
2427 if (EI.isArtificialDep())
2428 return "color=cyan,style=dashed";
2430 return "color=blue,style=dashed";
2434 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2436 raw_string_ostream SS(Str);
2437 SS << "SU(" << SU->NodeNum << ')';
2440 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2441 return G->getGraphNodeLabel(SU);
2444 static std::string getNodeAttributes(const SUnit *N,
2445 const ScheduleDAG *Graph) {
2446 std::string Str("shape=Mrecord");
2447 const SchedDFSResult *DFS =
2448 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2450 Str += ",style=filled,fillcolor=\"#";
2451 Str += DOT::getColorString(DFS->getSubtreeID(N));
2460 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2461 /// rendered using 'dot'.
2463 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2465 ViewGraph(this, Name, false, Title);
2467 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2468 << "systems with Graphviz or gv!\n";
2472 /// Out-of-line implementation with no arguments is handy for gdb.
2473 void ScheduleDAGMI::viewGraph() {
2474 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());