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/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/MachineScheduler.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/RegisterClassInfo.h"
21 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/PriorityQueue.h"
35 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
42 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
45 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
48 static bool ViewMISchedDAGs = false;
51 //===----------------------------------------------------------------------===//
52 // Machine Instruction Scheduling Pass and Registry
53 //===----------------------------------------------------------------------===//
55 MachineSchedContext::MachineSchedContext():
56 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
57 RegClassInfo = new RegisterClassInfo();
60 MachineSchedContext::~MachineSchedContext() {
65 /// MachineScheduler runs after coalescing and before register allocation.
66 class MachineScheduler : public MachineSchedContext,
67 public MachineFunctionPass {
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
73 virtual void releaseMemory() {}
75 virtual bool runOnMachineFunction(MachineFunction&);
77 virtual void print(raw_ostream &O, const Module* = 0) const;
79 static char ID; // Class identification, replacement for typeinfo
83 char MachineScheduler::ID = 0;
85 char &llvm::MachineSchedulerID = MachineScheduler::ID;
87 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
88 "Machine Instruction Scheduler", false, false)
89 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
91 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
92 INITIALIZE_PASS_END(MachineScheduler, "misched",
93 "Machine Instruction Scheduler", false, false)
95 MachineScheduler::MachineScheduler()
96 : MachineFunctionPass(ID) {
97 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
100 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.setPreservesCFG();
102 AU.addRequiredID(MachineDominatorsID);
103 AU.addRequired<MachineLoopInfo>();
104 AU.addRequired<AliasAnalysis>();
105 AU.addRequired<TargetPassConfig>();
106 AU.addRequired<SlotIndexes>();
107 AU.addPreserved<SlotIndexes>();
108 AU.addRequired<LiveIntervals>();
109 AU.addPreserved<LiveIntervals>();
110 MachineFunctionPass::getAnalysisUsage(AU);
113 MachinePassRegistry MachineSchedRegistry::Registry;
115 /// A dummy default scheduler factory indicates whether the scheduler
116 /// is overridden on the command line.
117 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
121 /// MachineSchedOpt allows command line selection of the scheduler.
122 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
123 RegisterPassParser<MachineSchedRegistry> >
124 MachineSchedOpt("misched",
125 cl::init(&useDefaultMachineSched), cl::Hidden,
126 cl::desc("Machine instruction scheduler to use"));
128 static MachineSchedRegistry
129 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
130 useDefaultMachineSched);
132 /// Forward declare the standard machine scheduler. This will be used as the
133 /// default scheduler if the target does not set a default.
134 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
137 /// Decrement this iterator until reaching the top or a non-debug instr.
138 static MachineBasicBlock::iterator
139 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
140 assert(I != Beg && "reached the top of the region, cannot decrement");
142 if (!I->isDebugValue())
148 /// If this iterator is a debug value, increment until reaching the End or a
149 /// non-debug instruction.
150 static MachineBasicBlock::iterator
151 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
152 for(; I != End; ++I) {
153 if (!I->isDebugValue())
159 /// Top-level MachineScheduler pass driver.
161 /// Visit blocks in function order. Divide each block into scheduling regions
162 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
163 /// consistent with the DAG builder, which traverses the interior of the
164 /// scheduling regions bottom-up.
166 /// This design avoids exposing scheduling boundaries to the DAG builder,
167 /// simplifying the DAG builder's support for "special" target instructions.
168 /// At the same time the design allows target schedulers to operate across
169 /// scheduling boundaries, for example to bundle the boudary instructions
170 /// without reordering them. This creates complexity, because the target
171 /// scheduler must update the RegionBegin and RegionEnd positions cached by
172 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
173 /// design would be to split blocks at scheduling boundaries, but LLVM has a
174 /// general bias against block splitting purely for implementation simplicity.
175 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
176 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
178 // Initialize the context of the pass.
180 MLI = &getAnalysis<MachineLoopInfo>();
181 MDT = &getAnalysis<MachineDominatorTree>();
182 PassConfig = &getAnalysis<TargetPassConfig>();
183 AA = &getAnalysis<AliasAnalysis>();
185 LIS = &getAnalysis<LiveIntervals>();
186 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
188 RegClassInfo->runOnMachineFunction(*MF);
190 // Select the scheduler, or set the default.
191 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
192 if (Ctor == useDefaultMachineSched) {
193 // Get the default scheduler set by the target.
194 Ctor = MachineSchedRegistry::getDefault();
196 Ctor = createConvergingSched;
197 MachineSchedRegistry::setDefault(Ctor);
200 // Instantiate the selected scheduler.
201 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
203 // Visit all machine basic blocks.
205 // TODO: Visit blocks in global postorder or postorder within the bottom-up
206 // loop tree. Then we can optionally compute global RegPressure.
207 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
208 MBB != MBBEnd; ++MBB) {
210 Scheduler->startBlock(MBB);
212 // Break the block into scheduling regions [I, RegionEnd), and schedule each
213 // region as soon as it is discovered. RegionEnd points the scheduling
214 // boundary at the bottom of the region. The DAG does not include RegionEnd,
215 // but the region does (i.e. the next RegionEnd is above the previous
216 // RegionBegin). If the current block has no terminator then RegionEnd ==
217 // MBB->end() for the bottom region.
219 // The Scheduler may insert instructions during either schedule() or
220 // exitRegion(), even for empty regions. So the local iterators 'I' and
221 // 'RegionEnd' are invalid across these calls.
222 unsigned RemainingCount = MBB->size();
223 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
224 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
226 // Avoid decrementing RegionEnd for blocks with no terminator.
227 if (RegionEnd != MBB->end()
228 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
230 // Count the boundary instruction.
234 // The next region starts above the previous region. Look backward in the
235 // instruction stream until we find the nearest boundary.
236 MachineBasicBlock::iterator I = RegionEnd;
237 for(;I != MBB->begin(); --I, --RemainingCount) {
238 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
241 // Notify the scheduler of the region, even if we may skip scheduling
242 // it. Perhaps it still needs to be bundled.
243 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
245 // Skip empty scheduling regions (0 or 1 schedulable instructions).
246 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
247 // Close the current region. Bundle the terminator if needed.
248 // This invalidates 'RegionEnd' and 'I'.
249 Scheduler->exitRegion();
252 DEBUG(dbgs() << "********** MI Scheduling **********\n");
253 DEBUG(dbgs() << MF->getName()
254 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
255 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
256 else dbgs() << "End";
257 dbgs() << " Remaining: " << RemainingCount << "\n");
259 // Schedule a region: possibly reorder instructions.
260 // This invalidates 'RegionEnd' and 'I'.
261 Scheduler->schedule();
263 // Close the current region.
264 Scheduler->exitRegion();
266 // Scheduling has invalidated the current iterator 'I'. Ask the
267 // scheduler for the top of it's scheduled region.
268 RegionEnd = Scheduler->begin();
270 assert(RemainingCount == 0 && "Instruction count mismatch!");
271 Scheduler->finishBlock();
273 Scheduler->finalizeSchedule();
274 DEBUG(LIS->print(dbgs()));
278 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
282 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
283 void ReadyQueue::dump() {
284 dbgs() << Name << ": ";
285 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
286 dbgs() << Queue[i]->NodeNum << " ";
291 //===----------------------------------------------------------------------===//
292 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
294 //===----------------------------------------------------------------------===//
296 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
297 /// NumPredsLeft reaches zero, release the successor node.
299 /// FIXME: Adjust SuccSU height based on MinLatency.
300 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
301 SUnit *SuccSU = SuccEdge->getSUnit();
304 if (SuccSU->NumPredsLeft == 0) {
305 dbgs() << "*** Scheduling failed! ***\n";
307 dbgs() << " has been released too many times!\n";
311 --SuccSU->NumPredsLeft;
312 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
313 SchedImpl->releaseTopNode(SuccSU);
316 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
317 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
318 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
320 releaseSucc(SU, &*I);
324 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
325 /// NumSuccsLeft reaches zero, release the predecessor node.
327 /// FIXME: Adjust PredSU height based on MinLatency.
328 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
329 SUnit *PredSU = PredEdge->getSUnit();
332 if (PredSU->NumSuccsLeft == 0) {
333 dbgs() << "*** Scheduling failed! ***\n";
335 dbgs() << " has been released too many times!\n";
339 --PredSU->NumSuccsLeft;
340 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
341 SchedImpl->releaseBottomNode(PredSU);
344 /// releasePredecessors - Call releasePred on each of SU's predecessors.
345 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
346 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
348 releasePred(SU, &*I);
352 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
353 MachineBasicBlock::iterator InsertPos) {
354 // Advance RegionBegin if the first instruction moves down.
355 if (&*RegionBegin == MI)
358 // Update the instruction stream.
359 BB->splice(InsertPos, BB, MI);
361 // Update LiveIntervals
364 // Recede RegionBegin if an instruction moves above the first.
365 if (RegionBegin == InsertPos)
369 bool ScheduleDAGMI::checkSchedLimit() {
371 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
372 CurrentTop = CurrentBottom;
375 ++NumInstrsScheduled;
380 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
381 /// crossing a scheduling boundary. [begin, end) includes all instructions in
382 /// the region, including the boundary itself and single-instruction regions
383 /// that don't get scheduled.
384 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
385 MachineBasicBlock::iterator begin,
386 MachineBasicBlock::iterator end,
389 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
391 // For convenience remember the end of the liveness region.
393 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
396 // Setup the register pressure trackers for the top scheduled top and bottom
397 // scheduled regions.
398 void ScheduleDAGMI::initRegPressure() {
399 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
400 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
402 // Close the RPTracker to finalize live ins.
403 RPTracker.closeRegion();
405 DEBUG(RPTracker.getPressure().dump(TRI));
407 // Initialize the live ins and live outs.
408 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
409 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
411 // Close one end of the tracker so we can call
412 // getMaxUpward/DownwardPressureDelta before advancing across any
413 // instructions. This converts currently live regs into live ins/outs.
414 TopRPTracker.closeTop();
415 BotRPTracker.closeBottom();
417 // Account for liveness generated by the region boundary.
418 if (LiveRegionEnd != RegionEnd)
419 BotRPTracker.recede();
421 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
423 // Cache the list of excess pressure sets in this region. This will also track
424 // the max pressure in the scheduled code for these sets.
425 RegionCriticalPSets.clear();
426 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
427 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
428 unsigned Limit = TRI->getRegPressureSetLimit(i);
429 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
431 << " Actual " << RegionPressure[i] << "\n");
432 if (RegionPressure[i] > Limit)
433 RegionCriticalPSets.push_back(PressureElement(i, 0));
435 DEBUG(dbgs() << "Excess PSets: ";
436 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
437 dbgs() << TRI->getRegPressureSetName(
438 RegionCriticalPSets[i].PSetID) << " ";
442 // FIXME: When the pressure tracker deals in pressure differences then we won't
443 // iterate over all RegionCriticalPSets[i].
445 updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
446 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
447 unsigned ID = RegionCriticalPSets[i].PSetID;
448 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
449 if ((int)NewMaxPressure[ID] > MaxUnits)
450 MaxUnits = NewMaxPressure[ID];
454 // Release all DAG roots for scheduling.
455 void ScheduleDAGMI::releaseRoots() {
456 SmallVector<SUnit*, 16> BotRoots;
458 for (std::vector<SUnit>::iterator
459 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
460 // A SUnit is ready to top schedule if it has no predecessors.
461 if (I->Preds.empty())
462 SchedImpl->releaseTopNode(&(*I));
463 // A SUnit is ready to bottom schedule if it has no successors.
464 if (I->Succs.empty())
465 BotRoots.push_back(&(*I));
467 // Release bottom roots in reverse order so the higher priority nodes appear
468 // first. This is more natural and slightly more efficient.
469 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
470 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
471 SchedImpl->releaseBottomNode(*I);
474 /// schedule - Called back from MachineScheduler::runOnMachineFunction
475 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
476 /// only includes instructions that have DAG nodes, not scheduling boundaries.
478 /// This is a skeletal driver, with all the functionality pushed into helpers,
479 /// so that it can be easilly extended by experimental schedulers. Generally,
480 /// implementing MachineSchedStrategy should be sufficient to implement a new
481 /// scheduling algorithm. However, if a scheduler further subclasses
482 /// ScheduleDAGMI then it will want to override this virtual method in order to
483 /// update any specialized state.
484 void ScheduleDAGMI::schedule() {
485 buildDAGWithRegPressure();
489 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
490 SUnits[su].dumpAll(this));
492 if (ViewMISchedDAGs) viewGraph();
496 bool IsTopNode = false;
497 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
498 assert(!SU->isScheduled && "Node already scheduled");
499 if (!checkSchedLimit())
502 scheduleMI(SU, IsTopNode);
504 updateQueues(SU, IsTopNode);
506 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
511 /// Build the DAG and setup three register pressure trackers.
512 void ScheduleDAGMI::buildDAGWithRegPressure() {
513 // Initialize the register pressure tracker used by buildSchedGraph.
514 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
516 // Account for liveness generate by the region boundary.
517 if (LiveRegionEnd != RegionEnd)
520 // Build the DAG, and compute current register pressure.
521 buildSchedGraph(AA, &RPTracker);
522 if (ViewMISchedDAGs) viewGraph();
524 // Initialize top/bottom trackers after computing region pressure.
528 /// Apply each ScheduleDAGMutation step in order.
529 void ScheduleDAGMI::postprocessDAG() {
530 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
531 Mutations[i]->apply(this);
535 /// Identify DAG roots and setup scheduler queues.
536 void ScheduleDAGMI::initQueues() {
537 // Initialize the strategy before modifying the DAG.
538 SchedImpl->initialize(this);
540 // Release edges from the special Entry node or to the special Exit node.
541 releaseSuccessors(&EntrySU);
542 releasePredecessors(&ExitSU);
544 // Release all DAG roots for scheduling.
547 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
548 CurrentBottom = RegionEnd;
551 /// Move an instruction and update register pressure.
552 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
553 // Move the instruction to its new location in the instruction stream.
554 MachineInstr *MI = SU->getInstr();
557 assert(SU->isTopReady() && "node still has unscheduled dependencies");
558 if (&*CurrentTop == MI)
559 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
561 moveInstruction(MI, CurrentTop);
562 TopRPTracker.setPos(MI);
565 // Update top scheduled pressure.
566 TopRPTracker.advance();
567 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
568 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
571 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
572 MachineBasicBlock::iterator priorII =
573 priorNonDebug(CurrentBottom, CurrentTop);
575 CurrentBottom = priorII;
577 if (&*CurrentTop == MI) {
578 CurrentTop = nextIfDebug(++CurrentTop, priorII);
579 TopRPTracker.setPos(CurrentTop);
581 moveInstruction(MI, CurrentBottom);
584 // Update bottom scheduled pressure.
585 BotRPTracker.recede();
586 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
587 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
591 /// Update scheduler queues after scheduling an instruction.
592 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
593 // Release dependent instructions for scheduling.
595 releaseSuccessors(SU);
597 releasePredecessors(SU);
599 SU->isScheduled = true;
601 // Notify the scheduling strategy after updating the DAG.
602 SchedImpl->schedNode(SU, IsTopNode);
605 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
606 void ScheduleDAGMI::placeDebugValues() {
607 // If first instruction was a DBG_VALUE then put it back.
609 BB->splice(RegionBegin, BB, FirstDbgValue);
610 RegionBegin = FirstDbgValue;
613 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
614 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
615 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
616 MachineInstr *DbgValue = P.first;
617 MachineBasicBlock::iterator OrigPrevMI = P.second;
618 BB->splice(++OrigPrevMI, BB, DbgValue);
619 if (OrigPrevMI == llvm::prior(RegionEnd))
620 RegionEnd = DbgValue;
623 FirstDbgValue = NULL;
626 //===----------------------------------------------------------------------===//
627 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
628 //===----------------------------------------------------------------------===//
631 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
633 class ConvergingScheduler : public MachineSchedStrategy {
635 /// Store the state used by ConvergingScheduler heuristics, required for the
636 /// lifetime of one invocation of pickNode().
637 struct SchedCandidate {
638 // The best SUnit candidate.
641 // Register pressure values for the best candidate.
642 RegPressureDelta RPDelta;
644 SchedCandidate(): SU(NULL) {}
646 /// Represent the type of SchedCandidate found within a single queue.
648 NoCand, NodeOrder, SingleExcess, SingleCritical, SingleMax, MultiPressure };
650 /// Each Scheduling boundary is associated with ready queues. It tracks the
651 /// current cycle in whichever direction at has moved, and maintains the state
652 /// of "hazards" and other interlocks at the current cycle.
653 struct SchedBoundary {
655 const TargetSchedModel *SchedModel;
657 ReadyQueue Available;
661 ScheduleHazardRecognizer *HazardRec;
666 /// MinReadyCycle - Cycle of the soonest available instruction.
667 unsigned MinReadyCycle;
669 // Remember the greatest min operand latency.
670 unsigned MaxMinLatency;
672 /// Pending queues extend the ready queues with the same ID and the
674 SchedBoundary(unsigned ID, const Twine &Name):
675 DAG(0), SchedModel(0), Available(ID, Name+".A"),
676 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
677 CheckPending(false), HazardRec(0), CurrCycle(0), IssueCount(0),
678 MinReadyCycle(UINT_MAX), MaxMinLatency(0) {}
680 ~SchedBoundary() { delete HazardRec; }
682 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel) {
688 return Available.getID() == ConvergingScheduler::TopQID;
691 bool checkHazard(SUnit *SU);
693 void releaseNode(SUnit *SU, unsigned ReadyCycle);
697 void bumpNode(SUnit *SU);
699 void releasePending();
701 void removeReady(SUnit *SU);
703 SUnit *pickOnlyChoice();
707 const TargetSchedModel *SchedModel;
708 const TargetRegisterInfo *TRI;
710 // State of the top and bottom scheduled instruction boundaries.
715 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
722 ConvergingScheduler():
723 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
725 virtual void initialize(ScheduleDAGMI *dag);
727 virtual SUnit *pickNode(bool &IsTopNode);
729 virtual void schedNode(SUnit *SU, bool IsTopNode);
731 virtual void releaseTopNode(SUnit *SU);
733 virtual void releaseBottomNode(SUnit *SU);
736 SUnit *pickNodeBidrectional(bool &IsTopNode);
738 CandResult pickNodeFromQueue(ReadyQueue &Q,
739 const RegPressureTracker &RPTracker,
740 SchedCandidate &Candidate);
742 void traceCandidate(const char *Label, const ReadyQueue &Q, SUnit *SU,
743 PressureElement P = PressureElement());
748 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
750 SchedModel = DAG->getSchedModel();
752 Top.init(DAG, SchedModel);
753 Bot.init(DAG, SchedModel);
755 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
756 // are disabled, then these HazardRecs will be disabled.
757 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
758 const TargetMachine &TM = DAG->MF.getTarget();
759 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
760 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
762 assert((!ForceTopDown || !ForceBottomUp) &&
763 "-misched-topdown incompatible with -misched-bottomup");
766 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
770 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
772 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
773 unsigned MinLatency = I->getMinLatency();
775 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
777 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
778 SU->TopReadyCycle = PredReadyCycle + MinLatency;
780 Top.releaseNode(SU, SU->TopReadyCycle);
783 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
787 assert(SU->getInstr() && "Scheduled SUnit must have instr");
789 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
791 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
792 unsigned MinLatency = I->getMinLatency();
794 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
796 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
797 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
799 Bot.releaseNode(SU, SU->BotReadyCycle);
802 /// Does this SU have a hazard within the current instruction group.
804 /// The scheduler supports two modes of hazard recognition. The first is the
805 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
806 /// supports highly complicated in-order reservation tables
807 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
809 /// The second is a streamlined mechanism that checks for hazards based on
810 /// simple counters that the scheduler itself maintains. It explicitly checks
811 /// for instruction dispatch limitations, including the number of micro-ops that
812 /// can dispatch per cycle.
814 /// TODO: Also check whether the SU must start a new group.
815 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
816 if (HazardRec->isEnabled())
817 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
819 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
820 if (IssueCount + uops > SchedModel->getIssueWidth())
826 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
827 unsigned ReadyCycle) {
828 if (ReadyCycle < MinReadyCycle)
829 MinReadyCycle = ReadyCycle;
831 // Check for interlocks first. For the purpose of other heuristics, an
832 // instruction that cannot issue appears as if it's not in the ReadyQueue.
833 if (ReadyCycle > CurrCycle || checkHazard(SU))
839 /// Move the boundary of scheduled code by one cycle.
840 void ConvergingScheduler::SchedBoundary::bumpCycle() {
841 unsigned Width = SchedModel->getIssueWidth();
842 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
844 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
845 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
847 if (!HazardRec->isEnabled()) {
848 // Bypass HazardRec virtual calls.
849 CurrCycle = NextCycle;
852 // Bypass getHazardType calls in case of long latency.
853 for (; CurrCycle != NextCycle; ++CurrCycle) {
855 HazardRec->AdvanceCycle();
857 HazardRec->RecedeCycle();
862 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
863 << CurrCycle << '\n');
866 /// Move the boundary of scheduled code by one SUnit.
867 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
868 // Update the reservation table.
869 if (HazardRec->isEnabled()) {
870 if (!isTop() && SU->isCall) {
871 // Calls are scheduled with their preceding instructions. For bottom-up
872 // scheduling, clear the pipeline state before emitting.
875 HazardRec->EmitInstruction(SU);
877 // Check the instruction group dispatch limit.
878 // TODO: Check if this SU must end a dispatch group.
879 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
880 if (IssueCount >= SchedModel->getIssueWidth()) {
881 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
886 /// Release pending ready nodes in to the available queue. This makes them
887 /// visible to heuristics.
888 void ConvergingScheduler::SchedBoundary::releasePending() {
889 // If the available queue is empty, it is safe to reset MinReadyCycle.
890 if (Available.empty())
891 MinReadyCycle = UINT_MAX;
893 // Check to see if any of the pending instructions are ready to issue. If
894 // so, add them to the available queue.
895 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
896 SUnit *SU = *(Pending.begin()+i);
897 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
899 if (ReadyCycle < MinReadyCycle)
900 MinReadyCycle = ReadyCycle;
902 if (ReadyCycle > CurrCycle)
909 Pending.remove(Pending.begin()+i);
912 CheckPending = false;
915 /// Remove SU from the ready set for this boundary.
916 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
917 if (Available.isInQueue(SU))
918 Available.remove(Available.find(SU));
920 assert(Pending.isInQueue(SU) && "bad ready count");
921 Pending.remove(Pending.find(SU));
925 /// If this queue only has one ready candidate, return it. As a side effect,
926 /// advance the cycle until at least one node is ready. If multiple instructions
927 /// are ready, return NULL.
928 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
932 for (unsigned i = 0; Available.empty(); ++i) {
933 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
934 "permanent hazard"); (void)i;
938 if (Available.size() == 1)
939 return *Available.begin();
944 void ConvergingScheduler::traceCandidate(const char *Label, const ReadyQueue &Q,
945 SUnit *SU, PressureElement P) {
946 dbgs() << Label << " " << Q.getName() << " ";
948 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
956 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
957 /// more desirable than RHS from scheduling standpoint.
958 static bool compareRPDelta(const RegPressureDelta &LHS,
959 const RegPressureDelta &RHS) {
960 // Compare each component of pressure in decreasing order of importance
961 // without checking if any are valid. Invalid PressureElements are assumed to
962 // have UnitIncrease==0, so are neutral.
964 // Avoid increasing the max critical pressure in the scheduled region.
965 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease)
966 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
968 // Avoid increasing the max critical pressure in the scheduled region.
969 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease)
970 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
972 // Avoid increasing the max pressure of the entire region.
973 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease)
974 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
979 /// Pick the best candidate from the top queue.
981 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
982 /// DAG building. To adjust for the current scheduling location we need to
983 /// maintain the number of vreg uses remaining to be top-scheduled.
984 ConvergingScheduler::CandResult ConvergingScheduler::
985 pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
986 SchedCandidate &Candidate) {
989 // getMaxPressureDelta temporarily modifies the tracker.
990 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
992 // BestSU remains NULL if no top candidates beat the best existing candidate.
993 CandResult FoundCandidate = NoCand;
994 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
995 RegPressureDelta RPDelta;
996 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
997 DAG->getRegionCriticalPSets(),
998 DAG->getRegPressure().MaxSetPressure);
1000 // Initialize the candidate if needed.
1001 if (!Candidate.SU) {
1003 Candidate.RPDelta = RPDelta;
1004 FoundCandidate = NodeOrder;
1007 // Avoid exceeding the target's limit.
1008 if (RPDelta.Excess.UnitIncrease < Candidate.RPDelta.Excess.UnitIncrease) {
1009 DEBUG(traceCandidate("ECAND", Q, *I, RPDelta.Excess));
1011 Candidate.RPDelta = RPDelta;
1012 FoundCandidate = SingleExcess;
1015 if (RPDelta.Excess.UnitIncrease > Candidate.RPDelta.Excess.UnitIncrease)
1017 if (FoundCandidate == SingleExcess)
1018 FoundCandidate = MultiPressure;
1020 // Avoid increasing the max critical pressure in the scheduled region.
1021 if (RPDelta.CriticalMax.UnitIncrease
1022 < Candidate.RPDelta.CriticalMax.UnitIncrease) {
1023 DEBUG(traceCandidate("PCAND", Q, *I, RPDelta.CriticalMax));
1025 Candidate.RPDelta = RPDelta;
1026 FoundCandidate = SingleCritical;
1029 if (RPDelta.CriticalMax.UnitIncrease
1030 > Candidate.RPDelta.CriticalMax.UnitIncrease)
1032 if (FoundCandidate == SingleCritical)
1033 FoundCandidate = MultiPressure;
1035 // Avoid increasing the max pressure of the entire region.
1036 if (RPDelta.CurrentMax.UnitIncrease
1037 < Candidate.RPDelta.CurrentMax.UnitIncrease) {
1038 DEBUG(traceCandidate("MCAND", Q, *I, RPDelta.CurrentMax));
1040 Candidate.RPDelta = RPDelta;
1041 FoundCandidate = SingleMax;
1044 if (RPDelta.CurrentMax.UnitIncrease
1045 > Candidate.RPDelta.CurrentMax.UnitIncrease)
1047 if (FoundCandidate == SingleMax)
1048 FoundCandidate = MultiPressure;
1050 // Fall through to original instruction order.
1051 // Only consider node order if Candidate was chosen from this Q.
1052 if (FoundCandidate == NoCand)
1055 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
1056 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
1057 DEBUG(traceCandidate("NCAND", Q, *I));
1059 Candidate.RPDelta = RPDelta;
1060 FoundCandidate = NodeOrder;
1063 return FoundCandidate;
1066 /// Pick the best candidate node from either the top or bottom queue.
1067 SUnit *ConvergingScheduler::pickNodeBidrectional(bool &IsTopNode) {
1068 // Schedule as far as possible in the direction of no choice. This is most
1069 // efficient, but also provides the best heuristics for CriticalPSets.
1070 if (SUnit *SU = Bot.pickOnlyChoice()) {
1074 if (SUnit *SU = Top.pickOnlyChoice()) {
1078 SchedCandidate BotCand;
1079 // Prefer bottom scheduling when heuristics are silent.
1080 CandResult BotResult = pickNodeFromQueue(Bot.Available,
1081 DAG->getBotRPTracker(), BotCand);
1082 assert(BotResult != NoCand && "failed to find the first candidate");
1084 // If either Q has a single candidate that provides the least increase in
1085 // Excess pressure, we can immediately schedule from that Q.
1087 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1088 // affects picking from either Q. If scheduling in one direction must
1089 // increase pressure for one of the excess PSets, then schedule in that
1090 // direction first to provide more freedom in the other direction.
1091 if (BotResult == SingleExcess || BotResult == SingleCritical) {
1095 // Check if the top Q has a better candidate.
1096 SchedCandidate TopCand;
1097 CandResult TopResult = pickNodeFromQueue(Top.Available,
1098 DAG->getTopRPTracker(), TopCand);
1099 assert(TopResult != NoCand && "failed to find the first candidate");
1101 if (TopResult == SingleExcess || TopResult == SingleCritical) {
1105 // If either Q has a single candidate that minimizes pressure above the
1106 // original region's pressure pick it.
1107 if (BotResult == SingleMax) {
1111 if (TopResult == SingleMax) {
1115 // Check for a salient pressure difference and pick the best from either side.
1116 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
1120 // Otherwise prefer the bottom candidate in node order.
1125 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
1126 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1127 if (DAG->top() == DAG->bottom()) {
1128 assert(Top.Available.empty() && Top.Pending.empty() &&
1129 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
1135 SU = Top.pickOnlyChoice();
1137 SchedCandidate TopCand;
1138 CandResult TopResult =
1139 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
1140 assert(TopResult != NoCand && "failed to find the first candidate");
1146 else if (ForceBottomUp) {
1147 SU = Bot.pickOnlyChoice();
1149 SchedCandidate BotCand;
1150 CandResult BotResult =
1151 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
1152 assert(BotResult != NoCand && "failed to find the first candidate");
1159 SU = pickNodeBidrectional(IsTopNode);
1161 } while (SU->isScheduled);
1163 if (SU->isTopReady())
1164 Top.removeReady(SU);
1165 if (SU->isBottomReady())
1166 Bot.removeReady(SU);
1168 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1169 << " Scheduling Instruction in cycle "
1170 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1175 /// Update the scheduler's state after scheduling a node. This is the same node
1176 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
1177 /// it's state based on the current cycle before MachineSchedStrategy does.
1178 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
1180 SU->TopReadyCycle = Top.CurrCycle;
1184 SU->BotReadyCycle = Bot.CurrCycle;
1189 /// Create the standard converging machine scheduler. This will be used as the
1190 /// default scheduler if the target does not set a default.
1191 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
1192 assert((!ForceTopDown || !ForceBottomUp) &&
1193 "-misched-topdown incompatible with -misched-bottomup");
1194 return new ScheduleDAGMI(C, new ConvergingScheduler());
1196 static MachineSchedRegistry
1197 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
1198 createConvergingSched);
1200 //===----------------------------------------------------------------------===//
1201 // Machine Instruction Shuffler for Correctness Testing
1202 //===----------------------------------------------------------------------===//
1206 /// Apply a less-than relation on the node order, which corresponds to the
1207 /// instruction order prior to scheduling. IsReverse implements greater-than.
1208 template<bool IsReverse>
1210 bool operator()(SUnit *A, SUnit *B) const {
1212 return A->NodeNum > B->NodeNum;
1214 return A->NodeNum < B->NodeNum;
1218 /// Reorder instructions as much as possible.
1219 class InstructionShuffler : public MachineSchedStrategy {
1223 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
1224 // gives nodes with a higher number higher priority causing the latest
1225 // instructions to be scheduled first.
1226 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
1228 // When scheduling bottom-up, use greater-than as the queue priority.
1229 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
1232 InstructionShuffler(bool alternate, bool topdown)
1233 : IsAlternating(alternate), IsTopDown(topdown) {}
1235 virtual void initialize(ScheduleDAGMI *) {
1240 /// Implement MachineSchedStrategy interface.
1241 /// -----------------------------------------
1243 virtual SUnit *pickNode(bool &IsTopNode) {
1247 if (TopQ.empty()) return NULL;
1250 } while (SU->isScheduled);
1255 if (BottomQ.empty()) return NULL;
1258 } while (SU->isScheduled);
1262 IsTopDown = !IsTopDown;
1266 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
1268 virtual void releaseTopNode(SUnit *SU) {
1271 virtual void releaseBottomNode(SUnit *SU) {
1277 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
1278 bool Alternate = !ForceTopDown && !ForceBottomUp;
1279 bool TopDown = !ForceBottomUp;
1280 assert((TopDown || !ForceTopDown) &&
1281 "-misched-topdown incompatible with -misched-bottomup");
1282 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
1284 static MachineSchedRegistry ShufflerRegistry(
1285 "shuffle", "Shuffle machine instructions alternating directions",
1286 createInstructionShuffler);