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/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterClassInfo.h"
27 #include "llvm/CodeGen/ScheduleDFS.h"
28 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
40 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
41 cl::desc("Force top-down list scheduling"));
42 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
43 cl::desc("Force bottom-up list scheduling"));
47 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
48 cl::desc("Pop up a window to show MISched dags after they are processed"));
50 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
51 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
53 static bool ViewMISchedDAGs = false;
56 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
57 cl::desc("Enable register pressure scheduling."), cl::init(true));
59 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
60 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
62 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
63 cl::desc("Enable load clustering."), cl::init(true));
65 // Experimental heuristics
66 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
67 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
69 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
70 cl::desc("Verify machine instrs before and after machine scheduling"));
72 // DAG subtrees must have at least this many nodes.
73 static const unsigned MinSubtreeSize = 8;
75 // Pin the vtables to this file.
76 void MachineSchedStrategy::anchor() {}
77 void ScheduleDAGMutation::anchor() {}
79 //===----------------------------------------------------------------------===//
80 // Machine Instruction Scheduling Pass and Registry
81 //===----------------------------------------------------------------------===//
83 MachineSchedContext::MachineSchedContext():
84 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
85 RegClassInfo = new RegisterClassInfo();
88 MachineSchedContext::~MachineSchedContext() {
93 /// Base class for a machine scheduler class that can run at any point.
94 class MachineSchedulerBase : public MachineSchedContext,
95 public MachineFunctionPass {
97 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
99 virtual void print(raw_ostream &O, const Module* = 0) const;
102 void scheduleRegions(ScheduleDAGInstrs &Scheduler);
105 /// MachineScheduler runs after coalescing and before register allocation.
106 class MachineScheduler : public MachineSchedulerBase {
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
112 virtual bool runOnMachineFunction(MachineFunction&);
114 static char ID; // Class identification, replacement for typeinfo
117 ScheduleDAGInstrs *createMachineScheduler();
120 /// PostMachineScheduler runs after shortly before code emission.
121 class PostMachineScheduler : public MachineSchedulerBase {
123 PostMachineScheduler();
125 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
127 virtual bool runOnMachineFunction(MachineFunction&);
129 static char ID; // Class identification, replacement for typeinfo
132 ScheduleDAGInstrs *createPostMachineScheduler();
136 char MachineScheduler::ID = 0;
138 char &llvm::MachineSchedulerID = MachineScheduler::ID;
140 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
141 "Machine Instruction Scheduler", false, false)
142 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
143 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
144 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
145 INITIALIZE_PASS_END(MachineScheduler, "misched",
146 "Machine Instruction Scheduler", false, false)
148 MachineScheduler::MachineScheduler()
149 : MachineSchedulerBase(ID) {
150 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
153 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.setPreservesCFG();
155 AU.addRequiredID(MachineDominatorsID);
156 AU.addRequired<MachineLoopInfo>();
157 AU.addRequired<AliasAnalysis>();
158 AU.addRequired<TargetPassConfig>();
159 AU.addRequired<SlotIndexes>();
160 AU.addPreserved<SlotIndexes>();
161 AU.addRequired<LiveIntervals>();
162 AU.addPreserved<LiveIntervals>();
163 MachineFunctionPass::getAnalysisUsage(AU);
166 char PostMachineScheduler::ID = 0;
168 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
170 INITIALIZE_PASS(PostMachineScheduler, "postmisched",
171 "PostRA Machine Instruction Scheduler", false, false);
173 PostMachineScheduler::PostMachineScheduler()
174 : MachineSchedulerBase(ID) {
175 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
178 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
179 AU.setPreservesCFG();
180 AU.addRequiredID(MachineDominatorsID);
181 AU.addRequired<MachineLoopInfo>();
182 AU.addRequired<TargetPassConfig>();
183 MachineFunctionPass::getAnalysisUsage(AU);
186 MachinePassRegistry MachineSchedRegistry::Registry;
188 /// A dummy default scheduler factory indicates whether the scheduler
189 /// is overridden on the command line.
190 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
194 /// MachineSchedOpt allows command line selection of the scheduler.
195 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
196 RegisterPassParser<MachineSchedRegistry> >
197 MachineSchedOpt("misched",
198 cl::init(&useDefaultMachineSched), cl::Hidden,
199 cl::desc("Machine instruction scheduler to use"));
201 static MachineSchedRegistry
202 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
203 useDefaultMachineSched);
205 /// Forward declare the standard machine scheduler. This will be used as the
206 /// default scheduler if the target does not set a default.
207 static ScheduleDAGInstrs *createGenericSched(MachineSchedContext *C);
208 static ScheduleDAGInstrs *createRawGenericSched(MachineSchedContext *C);
210 /// Decrement this iterator until reaching the top or a non-debug instr.
211 static MachineBasicBlock::const_iterator
212 priorNonDebug(MachineBasicBlock::const_iterator I,
213 MachineBasicBlock::const_iterator Beg) {
214 assert(I != Beg && "reached the top of the region, cannot decrement");
216 if (!I->isDebugValue())
222 /// Non-const version.
223 static MachineBasicBlock::iterator
224 priorNonDebug(MachineBasicBlock::iterator I,
225 MachineBasicBlock::const_iterator Beg) {
226 return const_cast<MachineInstr*>(
227 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
230 /// If this iterator is a debug value, increment until reaching the End or a
231 /// non-debug instruction.
232 static MachineBasicBlock::const_iterator
233 nextIfDebug(MachineBasicBlock::const_iterator I,
234 MachineBasicBlock::const_iterator End) {
235 for(; I != End; ++I) {
236 if (!I->isDebugValue())
242 /// Non-const version.
243 static MachineBasicBlock::iterator
244 nextIfDebug(MachineBasicBlock::iterator I,
245 MachineBasicBlock::const_iterator End) {
246 // Cast the return value to nonconst MachineInstr, then cast to an
247 // instr_iterator, which does not check for null, finally return a
249 return MachineBasicBlock::instr_iterator(
250 const_cast<MachineInstr*>(
251 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
254 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
255 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
256 // Select the scheduler, or set the default.
257 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
258 if (Ctor != useDefaultMachineSched)
261 // Get the default scheduler set by the target for this function.
262 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
266 // Default to GenericScheduler.
267 return createGenericSched(this);
270 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
271 /// the caller. We don't have a command line option to override the postRA
272 /// scheduler. The Target must configure it.
273 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
274 // Get the postRA scheduler set by the target for this function.
275 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
279 // Default to GenericScheduler.
280 // return createRawGenericSched(this);
284 /// Top-level MachineScheduler pass driver.
286 /// Visit blocks in function order. Divide each block into scheduling regions
287 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
288 /// consistent with the DAG builder, which traverses the interior of the
289 /// scheduling regions bottom-up.
291 /// This design avoids exposing scheduling boundaries to the DAG builder,
292 /// simplifying the DAG builder's support for "special" target instructions.
293 /// At the same time the design allows target schedulers to operate across
294 /// scheduling boundaries, for example to bundle the boudary instructions
295 /// without reordering them. This creates complexity, because the target
296 /// scheduler must update the RegionBegin and RegionEnd positions cached by
297 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
298 /// design would be to split blocks at scheduling boundaries, but LLVM has a
299 /// general bias against block splitting purely for implementation simplicity.
300 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
301 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
303 // Initialize the context of the pass.
305 MLI = &getAnalysis<MachineLoopInfo>();
306 MDT = &getAnalysis<MachineDominatorTree>();
307 PassConfig = &getAnalysis<TargetPassConfig>();
308 AA = &getAnalysis<AliasAnalysis>();
310 LIS = &getAnalysis<LiveIntervals>();
312 if (VerifyScheduling) {
314 MF->verify(this, "Before machine scheduling.");
316 RegClassInfo->runOnMachineFunction(*MF);
318 // Instantiate the selected scheduler for this target, function, and
319 // optimization level.
320 OwningPtr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
321 scheduleRegions(*Scheduler);
324 if (VerifyScheduling)
325 MF->verify(this, "After machine scheduling.");
329 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
330 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
332 // Initialize the context of the pass.
334 PassConfig = &getAnalysis<TargetPassConfig>();
336 if (VerifyScheduling)
337 MF->verify(this, "Before post machine scheduling.");
339 // Instantiate the selected scheduler for this target, function, and
340 // optimization level.
341 OwningPtr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
342 scheduleRegions(*Scheduler);
344 if (VerifyScheduling)
345 MF->verify(this, "After post machine scheduling.");
349 /// Main driver for both MachineScheduler and PostMachineScheduler.
350 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
351 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
353 // Visit all machine basic blocks.
355 // TODO: Visit blocks in global postorder or postorder within the bottom-up
356 // loop tree. Then we can optionally compute global RegPressure.
357 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
358 MBB != MBBEnd; ++MBB) {
360 Scheduler.startBlock(MBB);
362 // Break the block into scheduling regions [I, RegionEnd), and schedule each
363 // region as soon as it is discovered. RegionEnd points the scheduling
364 // boundary at the bottom of the region. The DAG does not include RegionEnd,
365 // but the region does (i.e. the next RegionEnd is above the previous
366 // RegionBegin). If the current block has no terminator then RegionEnd ==
367 // MBB->end() for the bottom region.
369 // The Scheduler may insert instructions during either schedule() or
370 // exitRegion(), even for empty regions. So the local iterators 'I' and
371 // 'RegionEnd' are invalid across these calls.
372 unsigned RemainingInstrs = MBB->size();
373 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
374 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
376 // Avoid decrementing RegionEnd for blocks with no terminator.
377 if (RegionEnd != MBB->end()
378 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
380 // Count the boundary instruction.
384 // The next region starts above the previous region. Look backward in the
385 // instruction stream until we find the nearest boundary.
386 unsigned NumRegionInstrs = 0;
387 MachineBasicBlock::iterator I = RegionEnd;
388 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
389 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
392 // Notify the scheduler of the region, even if we may skip scheduling
393 // it. Perhaps it still needs to be bundled.
394 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
396 // Skip empty scheduling regions (0 or 1 schedulable instructions).
397 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
398 // Close the current region. Bundle the terminator if needed.
399 // This invalidates 'RegionEnd' and 'I'.
400 Scheduler.exitRegion();
403 DEBUG(dbgs() << "********** MI Scheduling **********\n");
404 DEBUG(dbgs() << MF->getName()
405 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
406 << "\n From: " << *I << " To: ";
407 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
408 else dbgs() << "End";
409 dbgs() << " RegionInstrs: " << NumRegionInstrs
410 << " Remaining: " << RemainingInstrs << "\n");
412 // Schedule a region: possibly reorder instructions.
413 // This invalidates 'RegionEnd' and 'I'.
414 Scheduler.schedule();
416 // Close the current region.
417 Scheduler.exitRegion();
419 // Scheduling has invalidated the current iterator 'I'. Ask the
420 // scheduler for the top of it's scheduled region.
421 RegionEnd = Scheduler.begin();
423 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
424 Scheduler.finishBlock();
426 Scheduler.finalizeSchedule();
429 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
433 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
434 void ReadyQueue::dump() {
435 dbgs() << Name << ": ";
436 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
437 dbgs() << Queue[i]->NodeNum << " ";
442 //===----------------------------------------------------------------------===//
443 // ScheduleDAGMI - Basic machine instruction scheduling. This is
444 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
445 // virtual registers.
446 // ===----------------------------------------------------------------------===/
448 ScheduleDAGMI::~ScheduleDAGMI() {
449 DeleteContainerPointers(Mutations);
453 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
454 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
457 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
458 if (SuccSU != &ExitSU) {
459 // Do not use WillCreateCycle, it assumes SD scheduling.
460 // If Pred is reachable from Succ, then the edge creates a cycle.
461 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
463 Topo.AddPred(SuccSU, PredDep.getSUnit());
465 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
466 // Return true regardless of whether a new edge needed to be inserted.
470 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
471 /// NumPredsLeft reaches zero, release the successor node.
473 /// FIXME: Adjust SuccSU height based on MinLatency.
474 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
475 SUnit *SuccSU = SuccEdge->getSUnit();
477 if (SuccEdge->isWeak()) {
478 --SuccSU->WeakPredsLeft;
479 if (SuccEdge->isCluster())
480 NextClusterSucc = SuccSU;
484 if (SuccSU->NumPredsLeft == 0) {
485 dbgs() << "*** Scheduling failed! ***\n";
487 dbgs() << " has been released too many times!\n";
491 --SuccSU->NumPredsLeft;
492 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
493 SchedImpl->releaseTopNode(SuccSU);
496 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
497 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
498 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
500 releaseSucc(SU, &*I);
504 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
505 /// NumSuccsLeft reaches zero, release the predecessor node.
507 /// FIXME: Adjust PredSU height based on MinLatency.
508 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
509 SUnit *PredSU = PredEdge->getSUnit();
511 if (PredEdge->isWeak()) {
512 --PredSU->WeakSuccsLeft;
513 if (PredEdge->isCluster())
514 NextClusterPred = PredSU;
518 if (PredSU->NumSuccsLeft == 0) {
519 dbgs() << "*** Scheduling failed! ***\n";
521 dbgs() << " has been released too many times!\n";
525 --PredSU->NumSuccsLeft;
526 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
527 SchedImpl->releaseBottomNode(PredSU);
530 /// releasePredecessors - Call releasePred on each of SU's predecessors.
531 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
532 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
534 releasePred(SU, &*I);
538 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
539 /// crossing a scheduling boundary. [begin, end) includes all instructions in
540 /// the region, including the boundary itself and single-instruction regions
541 /// that don't get scheduled.
542 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
543 MachineBasicBlock::iterator begin,
544 MachineBasicBlock::iterator end,
545 unsigned regioninstrs)
547 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
549 SchedImpl->initPolicy(begin, end, regioninstrs);
552 /// This is normally called from the main scheduler loop but may also be invoked
553 /// by the scheduling strategy to perform additional code motion.
554 void ScheduleDAGMI::moveInstruction(
555 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
556 // Advance RegionBegin if the first instruction moves down.
557 if (&*RegionBegin == MI)
560 // Update the instruction stream.
561 BB->splice(InsertPos, BB, MI);
563 // Update LiveIntervals
565 LIS->handleMove(MI, /*UpdateFlags=*/true);
567 // Recede RegionBegin if an instruction moves above the first.
568 if (RegionBegin == InsertPos)
572 bool ScheduleDAGMI::checkSchedLimit() {
574 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
575 CurrentTop = CurrentBottom;
578 ++NumInstrsScheduled;
583 /// Per-region scheduling driver, called back from
584 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
585 /// does not consider liveness or register pressure. It is useful for PostRA
586 /// scheduling and potentially other custom schedulers.
587 void ScheduleDAGMI::schedule() {
591 Topo.InitDAGTopologicalSorting();
595 SmallVector<SUnit*, 8> TopRoots, BotRoots;
596 findRootsAndBiasEdges(TopRoots, BotRoots);
598 // Initialize the strategy before modifying the DAG.
599 // This may initialize a DFSResult to be used for queue priority.
600 SchedImpl->initialize(this);
602 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
603 SUnits[su].dumpAll(this));
604 if (ViewMISchedDAGs) viewGraph();
606 // Initialize ready queues now that the DAG and priority data are finalized.
607 initQueues(TopRoots, BotRoots);
609 bool IsTopNode = false;
610 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
611 assert(!SU->isScheduled && "Node already scheduled");
612 if (!checkSchedLimit())
615 MachineInstr *MI = SU->getInstr();
617 assert(SU->isTopReady() && "node still has unscheduled dependencies");
618 if (&*CurrentTop == MI)
619 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
621 moveInstruction(MI, CurrentTop);
624 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
625 MachineBasicBlock::iterator priorII =
626 priorNonDebug(CurrentBottom, CurrentTop);
628 CurrentBottom = priorII;
630 if (&*CurrentTop == MI)
631 CurrentTop = nextIfDebug(++CurrentTop, priorII);
632 moveInstruction(MI, CurrentBottom);
636 updateQueues(SU, IsTopNode);
638 // Notify the scheduling strategy after updating the DAG.
639 SchedImpl->schedNode(SU, IsTopNode);
641 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
646 unsigned BBNum = begin()->getParent()->getNumber();
647 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
653 /// Apply each ScheduleDAGMutation step in order.
654 void ScheduleDAGMI::postprocessDAG() {
655 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
656 Mutations[i]->apply(this);
661 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
662 SmallVectorImpl<SUnit*> &BotRoots) {
663 for (std::vector<SUnit>::iterator
664 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
666 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
668 // Order predecessors so DFSResult follows the critical path.
669 SU->biasCriticalPath();
671 // A SUnit is ready to top schedule if it has no predecessors.
672 if (!I->NumPredsLeft)
673 TopRoots.push_back(SU);
674 // A SUnit is ready to bottom schedule if it has no successors.
675 if (!I->NumSuccsLeft)
676 BotRoots.push_back(SU);
678 ExitSU.biasCriticalPath();
681 /// Identify DAG roots and setup scheduler queues.
682 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
683 ArrayRef<SUnit*> BotRoots) {
684 NextClusterSucc = NULL;
685 NextClusterPred = NULL;
687 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
689 // Nodes with unreleased weak edges can still be roots.
690 // Release top roots in forward order.
691 for (SmallVectorImpl<SUnit*>::const_iterator
692 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
693 SchedImpl->releaseTopNode(*I);
695 // Release bottom roots in reverse order so the higher priority nodes appear
696 // first. This is more natural and slightly more efficient.
697 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
698 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
699 SchedImpl->releaseBottomNode(*I);
702 releaseSuccessors(&EntrySU);
703 releasePredecessors(&ExitSU);
705 SchedImpl->registerRoots();
707 // Advance past initial DebugValues.
708 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
709 CurrentBottom = RegionEnd;
712 /// Update scheduler queues after scheduling an instruction.
713 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
714 // Release dependent instructions for scheduling.
716 releaseSuccessors(SU);
718 releasePredecessors(SU);
720 SU->isScheduled = true;
723 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
724 void ScheduleDAGMI::placeDebugValues() {
725 // If first instruction was a DBG_VALUE then put it back.
727 BB->splice(RegionBegin, BB, FirstDbgValue);
728 RegionBegin = FirstDbgValue;
731 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
732 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
733 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
734 MachineInstr *DbgValue = P.first;
735 MachineBasicBlock::iterator OrigPrevMI = P.second;
736 if (&*RegionBegin == DbgValue)
738 BB->splice(++OrigPrevMI, BB, DbgValue);
739 if (OrigPrevMI == llvm::prior(RegionEnd))
740 RegionEnd = DbgValue;
743 FirstDbgValue = NULL;
746 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
747 void ScheduleDAGMI::dumpSchedule() const {
748 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
749 if (SUnit *SU = getSUnit(&(*MI)))
752 dbgs() << "Missing SUnit\n";
757 //===----------------------------------------------------------------------===//
758 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
760 //===----------------------------------------------------------------------===//
762 ScheduleDAGMILive::~ScheduleDAGMILive() {
766 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
767 /// crossing a scheduling boundary. [begin, end) includes all instructions in
768 /// the region, including the boundary itself and single-instruction regions
769 /// that don't get scheduled.
770 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
771 MachineBasicBlock::iterator begin,
772 MachineBasicBlock::iterator end,
773 unsigned regioninstrs)
775 // ScheduleDAGMI initializes SchedImpl's per-region policy.
776 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
778 // For convenience remember the end of the liveness region.
780 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
782 SUPressureDiffs.clear();
784 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
787 // Setup the register pressure trackers for the top scheduled top and bottom
788 // scheduled regions.
789 void ScheduleDAGMILive::initRegPressure() {
790 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
791 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
793 // Close the RPTracker to finalize live ins.
794 RPTracker.closeRegion();
796 DEBUG(RPTracker.dump());
798 // Initialize the live ins and live outs.
799 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
800 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
802 // Close one end of the tracker so we can call
803 // getMaxUpward/DownwardPressureDelta before advancing across any
804 // instructions. This converts currently live regs into live ins/outs.
805 TopRPTracker.closeTop();
806 BotRPTracker.closeBottom();
808 BotRPTracker.initLiveThru(RPTracker);
809 if (!BotRPTracker.getLiveThru().empty()) {
810 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
811 DEBUG(dbgs() << "Live Thru: ";
812 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
815 // For each live out vreg reduce the pressure change associated with other
816 // uses of the same vreg below the live-out reaching def.
817 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
819 // Account for liveness generated by the region boundary.
820 if (LiveRegionEnd != RegionEnd) {
821 SmallVector<unsigned, 8> LiveUses;
822 BotRPTracker.recede(&LiveUses);
823 updatePressureDiffs(LiveUses);
826 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
828 // Cache the list of excess pressure sets in this region. This will also track
829 // the max pressure in the scheduled code for these sets.
830 RegionCriticalPSets.clear();
831 const std::vector<unsigned> &RegionPressure =
832 RPTracker.getPressure().MaxSetPressure;
833 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
834 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
835 if (RegionPressure[i] > Limit) {
836 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
837 << " Limit " << Limit
838 << " Actual " << RegionPressure[i] << "\n");
839 RegionCriticalPSets.push_back(PressureChange(i));
842 DEBUG(dbgs() << "Excess PSets: ";
843 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
844 dbgs() << TRI->getRegPressureSetName(
845 RegionCriticalPSets[i].getPSet()) << " ";
849 void ScheduleDAGMILive::
850 updateScheduledPressure(const SUnit *SU,
851 const std::vector<unsigned> &NewMaxPressure) {
852 const PressureDiff &PDiff = getPressureDiff(SU);
853 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
854 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
858 unsigned ID = I->getPSet();
859 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
861 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
862 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
863 && NewMaxPressure[ID] <= INT16_MAX)
864 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
866 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
867 if (NewMaxPressure[ID] >= Limit - 2) {
868 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
869 << NewMaxPressure[ID] << " > " << Limit << "(+ "
870 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
875 /// Update the PressureDiff array for liveness after scheduling this
877 void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
878 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
879 /// FIXME: Currently assuming single-use physregs.
880 unsigned Reg = LiveUses[LUIdx];
881 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
882 if (!TRI->isVirtualRegister(Reg))
885 // This may be called before CurrentBottom has been initialized. However,
886 // BotRPTracker must have a valid position. We want the value live into the
887 // instruction or live out of the block, so ask for the previous
888 // instruction's live-out.
889 const LiveInterval &LI = LIS->getInterval(Reg);
891 MachineBasicBlock::const_iterator I =
892 nextIfDebug(BotRPTracker.getPos(), BB->end());
894 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
896 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
899 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
900 assert(VNI && "No live value at use.");
901 for (VReg2UseMap::iterator
902 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
904 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
906 // If this use comes before the reaching def, it cannot be a last use, so
907 // descrease its pressure change.
908 if (!SU->isScheduled && SU != &ExitSU) {
910 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
911 if (LRQ.valueIn() == VNI)
912 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
918 /// schedule - Called back from MachineScheduler::runOnMachineFunction
919 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
920 /// only includes instructions that have DAG nodes, not scheduling boundaries.
922 /// This is a skeletal driver, with all the functionality pushed into helpers,
923 /// so that it can be easilly extended by experimental schedulers. Generally,
924 /// implementing MachineSchedStrategy should be sufficient to implement a new
925 /// scheduling algorithm. However, if a scheduler further subclasses
926 /// ScheduleDAGMILive then it will want to override this virtual method in order
927 /// to update any specialized state.
928 void ScheduleDAGMILive::schedule() {
929 buildDAGWithRegPressure();
931 Topo.InitDAGTopologicalSorting();
935 SmallVector<SUnit*, 8> TopRoots, BotRoots;
936 findRootsAndBiasEdges(TopRoots, BotRoots);
938 // Initialize the strategy before modifying the DAG.
939 // This may initialize a DFSResult to be used for queue priority.
940 SchedImpl->initialize(this);
942 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
943 SUnits[su].dumpAll(this));
944 if (ViewMISchedDAGs) viewGraph();
946 // Initialize ready queues now that the DAG and priority data are finalized.
947 initQueues(TopRoots, BotRoots);
949 if (ShouldTrackPressure) {
950 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
951 TopRPTracker.setPos(CurrentTop);
954 bool IsTopNode = false;
955 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
956 assert(!SU->isScheduled && "Node already scheduled");
957 if (!checkSchedLimit())
960 scheduleMI(SU, IsTopNode);
962 updateQueues(SU, IsTopNode);
965 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
966 if (!ScheduledTrees.test(SubtreeID)) {
967 ScheduledTrees.set(SubtreeID);
968 DFSResult->scheduleTree(SubtreeID);
969 SchedImpl->scheduleTree(SubtreeID);
973 // Notify the scheduling strategy after updating the DAG.
974 SchedImpl->schedNode(SU, IsTopNode);
976 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
981 unsigned BBNum = begin()->getParent()->getNumber();
982 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
988 /// Build the DAG and setup three register pressure trackers.
989 void ScheduleDAGMILive::buildDAGWithRegPressure() {
990 if (!ShouldTrackPressure) {
992 RegionCriticalPSets.clear();
997 // Initialize the register pressure tracker used by buildSchedGraph.
998 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
999 /*TrackUntiedDefs=*/true);
1001 // Account for liveness generate by the region boundary.
1002 if (LiveRegionEnd != RegionEnd)
1005 // Build the DAG, and compute current register pressure.
1006 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
1008 // Initialize top/bottom trackers after computing region pressure.
1012 void ScheduleDAGMILive::computeDFSResult() {
1014 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1016 ScheduledTrees.clear();
1017 DFSResult->resize(SUnits.size());
1018 DFSResult->compute(SUnits);
1019 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1022 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1023 /// only provides the critical path for single block loops. To handle loops that
1024 /// span blocks, we could use the vreg path latencies provided by
1025 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1026 /// available for use in the scheduler.
1028 /// The cyclic path estimation identifies a def-use pair that crosses the back
1029 /// edge and considers the depth and height of the nodes. For example, consider
1030 /// the following instruction sequence where each instruction has unit latency
1031 /// and defines an epomymous virtual register:
1033 /// a->b(a,c)->c(b)->d(c)->exit
1035 /// The cyclic critical path is a two cycles: b->c->b
1036 /// The acyclic critical path is four cycles: a->b->c->d->exit
1037 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1038 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1039 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1040 /// LiveInDepth = depth(b) = len(a->b) = 1
1042 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1043 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1044 /// CyclicCriticalPath = min(2, 2) = 2
1046 /// This could be relevant to PostRA scheduling, but is currently implemented
1047 /// assuming LiveIntervals.
1048 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1049 // This only applies to single block loop.
1050 if (!BB->isSuccessor(BB))
1053 unsigned MaxCyclicLatency = 0;
1054 // Visit each live out vreg def to find def/use pairs that cross iterations.
1055 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1056 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1059 if (!TRI->isVirtualRegister(Reg))
1061 const LiveInterval &LI = LIS->getInterval(Reg);
1062 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1066 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1067 const SUnit *DefSU = getSUnit(DefMI);
1071 unsigned LiveOutHeight = DefSU->getHeight();
1072 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1073 // Visit all local users of the vreg def.
1074 for (VReg2UseMap::iterator
1075 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1076 if (UI->SU == &ExitSU)
1079 // Only consider uses of the phi.
1080 LiveQueryResult LRQ =
1081 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
1082 if (!LRQ.valueIn()->isPHIDef())
1085 // Assume that a path spanning two iterations is a cycle, which could
1086 // overestimate in strange cases. This allows cyclic latency to be
1087 // estimated as the minimum slack of the vreg's depth or height.
1088 unsigned CyclicLatency = 0;
1089 if (LiveOutDepth > UI->SU->getDepth())
1090 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1092 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1093 if (LiveInHeight > LiveOutHeight) {
1094 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1095 CyclicLatency = LiveInHeight - LiveOutHeight;
1100 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1101 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1102 if (CyclicLatency > MaxCyclicLatency)
1103 MaxCyclicLatency = CyclicLatency;
1106 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1107 return MaxCyclicLatency;
1110 /// Move an instruction and update register pressure.
1111 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1112 // Move the instruction to its new location in the instruction stream.
1113 MachineInstr *MI = SU->getInstr();
1116 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1117 if (&*CurrentTop == MI)
1118 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1120 moveInstruction(MI, CurrentTop);
1121 TopRPTracker.setPos(MI);
1124 if (ShouldTrackPressure) {
1125 // Update top scheduled pressure.
1126 TopRPTracker.advance();
1127 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1128 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1132 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1133 MachineBasicBlock::iterator priorII =
1134 priorNonDebug(CurrentBottom, CurrentTop);
1135 if (&*priorII == MI)
1136 CurrentBottom = priorII;
1138 if (&*CurrentTop == MI) {
1139 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1140 TopRPTracker.setPos(CurrentTop);
1142 moveInstruction(MI, CurrentBottom);
1145 if (ShouldTrackPressure) {
1146 // Update bottom scheduled pressure.
1147 SmallVector<unsigned, 8> LiveUses;
1148 BotRPTracker.recede(&LiveUses);
1149 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1150 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1151 updatePressureDiffs(LiveUses);
1156 //===----------------------------------------------------------------------===//
1157 // LoadClusterMutation - DAG post-processing to cluster loads.
1158 //===----------------------------------------------------------------------===//
1161 /// \brief Post-process the DAG to create cluster edges between neighboring
1163 class LoadClusterMutation : public ScheduleDAGMutation {
1168 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1169 : SU(su), BaseReg(reg), Offset(ofs) {}
1171 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
1172 const LoadClusterMutation::LoadInfo &RHS);
1174 const TargetInstrInfo *TII;
1175 const TargetRegisterInfo *TRI;
1177 LoadClusterMutation(const TargetInstrInfo *tii,
1178 const TargetRegisterInfo *tri)
1179 : TII(tii), TRI(tri) {}
1181 virtual void apply(ScheduleDAGMI *DAG);
1183 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1187 bool LoadClusterMutation::LoadInfoLess(
1188 const LoadClusterMutation::LoadInfo &LHS,
1189 const LoadClusterMutation::LoadInfo &RHS) {
1190 if (LHS.BaseReg != RHS.BaseReg)
1191 return LHS.BaseReg < RHS.BaseReg;
1192 return LHS.Offset < RHS.Offset;
1195 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1196 ScheduleDAGMI *DAG) {
1197 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1198 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1199 SUnit *SU = Loads[Idx];
1202 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1203 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1205 if (LoadRecords.size() < 2)
1207 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
1208 unsigned ClusterLength = 1;
1209 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1210 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1215 SUnit *SUa = LoadRecords[Idx].SU;
1216 SUnit *SUb = LoadRecords[Idx+1].SU;
1217 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
1218 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1220 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1221 << SUb->NodeNum << ")\n");
1222 // Copy successor edges from SUa to SUb. Interleaving computation
1223 // dependent on SUa can prevent load combining due to register reuse.
1224 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1225 // loads should have effectively the same inputs.
1226 for (SUnit::const_succ_iterator
1227 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1228 if (SI->getSUnit() == SUb)
1230 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1231 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1240 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1241 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1242 // Map DAG NodeNum to store chain ID.
1243 DenseMap<unsigned, unsigned> StoreChainIDs;
1244 // Map each store chain to a set of dependent loads.
1245 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1246 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1247 SUnit *SU = &DAG->SUnits[Idx];
1248 if (!SU->getInstr()->mayLoad())
1250 unsigned ChainPredID = DAG->SUnits.size();
1251 for (SUnit::const_pred_iterator
1252 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1254 ChainPredID = PI->getSUnit()->NodeNum;
1258 // Check if this chain-like pred has been seen
1259 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1260 unsigned NumChains = StoreChainDependents.size();
1261 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1262 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1264 StoreChainDependents.resize(NumChains + 1);
1265 StoreChainDependents[Result.first->second].push_back(SU);
1267 // Iterate over the store chains.
1268 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1269 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1272 //===----------------------------------------------------------------------===//
1273 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1274 //===----------------------------------------------------------------------===//
1277 /// \brief Post-process the DAG to create cluster edges between instructions
1278 /// that may be fused by the processor into a single operation.
1279 class MacroFusion : public ScheduleDAGMutation {
1280 const TargetInstrInfo *TII;
1282 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1284 virtual void apply(ScheduleDAGMI *DAG);
1288 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1289 /// fused operations.
1290 void MacroFusion::apply(ScheduleDAGMI *DAG) {
1291 // For now, assume targets can only fuse with the branch.
1292 MachineInstr *Branch = DAG->ExitSU.getInstr();
1296 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1297 SUnit *SU = &DAG->SUnits[--Idx];
1298 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1301 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1302 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1303 // need to copy predecessor edges from ExitSU to SU, since top-down
1304 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1305 // of SU, we could create an artificial edge from the deepest root, but it
1306 // hasn't been needed yet.
1307 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1309 assert(Success && "No DAG nodes should be reachable from ExitSU");
1311 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1316 //===----------------------------------------------------------------------===//
1317 // CopyConstrain - DAG post-processing to encourage copy elimination.
1318 //===----------------------------------------------------------------------===//
1321 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1322 /// the one use that defines the copy's source vreg, most likely an induction
1323 /// variable increment.
1324 class CopyConstrain : public ScheduleDAGMutation {
1326 SlotIndex RegionBeginIdx;
1327 // RegionEndIdx is the slot index of the last non-debug instruction in the
1328 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1329 SlotIndex RegionEndIdx;
1331 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1333 virtual void apply(ScheduleDAGMI *DAG);
1336 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1340 /// constrainLocalCopy handles two possibilities:
1345 /// I3: dst = src (copy)
1346 /// (create pred->succ edges I0->I1, I2->I1)
1349 /// I0: dst = src (copy)
1353 /// (create pred->succ edges I1->I2, I3->I2)
1355 /// Although the MachineScheduler is currently constrained to single blocks,
1356 /// this algorithm should handle extended blocks. An EBB is a set of
1357 /// contiguously numbered blocks such that the previous block in the EBB is
1358 /// always the single predecessor.
1359 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1360 LiveIntervals *LIS = DAG->getLIS();
1361 MachineInstr *Copy = CopySU->getInstr();
1363 // Check for pure vreg copies.
1364 unsigned SrcReg = Copy->getOperand(1).getReg();
1365 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1368 unsigned DstReg = Copy->getOperand(0).getReg();
1369 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1372 // Check if either the dest or source is local. If it's live across a back
1373 // edge, it's not local. Note that if both vregs are live across the back
1374 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1375 unsigned LocalReg = DstReg;
1376 unsigned GlobalReg = SrcReg;
1377 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1378 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1381 LocalLI = &LIS->getInterval(LocalReg);
1382 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1385 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1387 // Find the global segment after the start of the local LI.
1388 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1389 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1390 // local live range. We could create edges from other global uses to the local
1391 // start, but the coalescer should have already eliminated these cases, so
1392 // don't bother dealing with it.
1393 if (GlobalSegment == GlobalLI->end())
1396 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1397 // returned the next global segment. But if GlobalSegment overlaps with
1398 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1399 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1400 if (GlobalSegment->contains(LocalLI->beginIndex()))
1403 if (GlobalSegment == GlobalLI->end())
1406 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1407 if (GlobalSegment != GlobalLI->begin()) {
1408 // Two address defs have no hole.
1409 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1410 GlobalSegment->start)) {
1413 // If the prior global segment may be defined by the same two-address
1414 // instruction that also defines LocalLI, then can't make a hole here.
1415 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1416 LocalLI->beginIndex())) {
1419 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1420 // it would be a disconnected component in the live range.
1421 assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1422 "Disconnected LRG within the scheduling region.");
1424 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1428 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1432 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1433 // constraining the uses of the last local def to precede GlobalDef.
1434 SmallVector<SUnit*,8> LocalUses;
1435 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1436 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1437 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1438 for (SUnit::const_succ_iterator
1439 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1441 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1443 if (I->getSUnit() == GlobalSU)
1445 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1447 LocalUses.push_back(I->getSUnit());
1449 // Open the top of the GlobalLI hole by constraining any earlier global uses
1450 // to precede the start of LocalLI.
1451 SmallVector<SUnit*,8> GlobalUses;
1452 MachineInstr *FirstLocalDef =
1453 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1454 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1455 for (SUnit::const_pred_iterator
1456 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1457 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1459 if (I->getSUnit() == FirstLocalSU)
1461 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1463 GlobalUses.push_back(I->getSUnit());
1465 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1466 // Add the weak edges.
1467 for (SmallVectorImpl<SUnit*>::const_iterator
1468 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1469 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1470 << GlobalSU->NodeNum << ")\n");
1471 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1473 for (SmallVectorImpl<SUnit*>::const_iterator
1474 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1475 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1476 << FirstLocalSU->NodeNum << ")\n");
1477 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1481 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1482 /// copy elimination.
1483 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1484 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1486 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1487 if (FirstPos == DAG->end())
1489 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1490 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1491 &*priorNonDebug(DAG->end(), DAG->begin()));
1493 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1494 SUnit *SU = &DAG->SUnits[Idx];
1495 if (!SU->getInstr()->isCopy())
1498 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1502 //===----------------------------------------------------------------------===//
1503 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1504 // and possibly other custom schedulers.
1505 // ===----------------------------------------------------------------------===/
1507 static const unsigned InvalidCycle = ~0U;
1509 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1511 void SchedBoundary::reset() {
1512 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1513 // Destroying and reconstructing it is very expensive though. So keep
1514 // invalid, placeholder HazardRecs.
1515 if (HazardRec && HazardRec->isEnabled()) {
1521 CheckPending = false;
1525 MinReadyCycle = UINT_MAX;
1526 ExpectedLatency = 0;
1527 DependentLatency = 0;
1529 MaxExecutedResCount = 0;
1531 IsResourceLimited = false;
1532 ReservedCycles.clear();
1534 MaxObservedLatency = 0;
1536 // Reserve a zero-count for invalid CritResIdx.
1537 ExecutedResCounts.resize(1);
1538 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1541 void SchedRemainder::
1542 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1544 if (!SchedModel->hasInstrSchedModel())
1546 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1547 for (std::vector<SUnit>::iterator
1548 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1549 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1550 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1551 * SchedModel->getMicroOpFactor();
1552 for (TargetSchedModel::ProcResIter
1553 PI = SchedModel->getWriteProcResBegin(SC),
1554 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1555 unsigned PIdx = PI->ProcResourceIdx;
1556 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1557 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1562 void SchedBoundary::
1563 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1566 SchedModel = smodel;
1568 if (SchedModel->hasInstrSchedModel()) {
1569 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1570 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1574 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1575 /// these "soft stalls" differently than the hard stall cycles based on CPU
1576 /// resources and computed by checkHazard(). A fully in-order model
1577 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1578 /// available for scheduling until they are ready. However, a weaker in-order
1579 /// model may use this for heuristics. For example, if a processor has in-order
1580 /// behavior when reading certain resources, this may come into play.
1581 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1582 if (!SU->isUnbuffered)
1585 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1586 if (ReadyCycle > CurrCycle)
1587 return ReadyCycle - CurrCycle;
1591 /// Compute the next cycle at which the given processor resource can be
1593 unsigned SchedBoundary::
1594 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1595 unsigned NextUnreserved = ReservedCycles[PIdx];
1596 // If this resource has never been used, always return cycle zero.
1597 if (NextUnreserved == InvalidCycle)
1599 // For bottom-up scheduling add the cycles needed for the current operation.
1601 NextUnreserved += Cycles;
1602 return NextUnreserved;
1605 /// Does this SU have a hazard within the current instruction group.
1607 /// The scheduler supports two modes of hazard recognition. The first is the
1608 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1609 /// supports highly complicated in-order reservation tables
1610 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1612 /// The second is a streamlined mechanism that checks for hazards based on
1613 /// simple counters that the scheduler itself maintains. It explicitly checks
1614 /// for instruction dispatch limitations, including the number of micro-ops that
1615 /// can dispatch per cycle.
1617 /// TODO: Also check whether the SU must start a new group.
1618 bool SchedBoundary::checkHazard(SUnit *SU) {
1619 if (HazardRec->isEnabled())
1620 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1622 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1623 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1624 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1625 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1628 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1629 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1630 for (TargetSchedModel::ProcResIter
1631 PI = SchedModel->getWriteProcResBegin(SC),
1632 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1633 if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1640 // Find the unscheduled node in ReadySUs with the highest latency.
1641 unsigned SchedBoundary::
1642 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1644 unsigned RemLatency = 0;
1645 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1647 unsigned L = getUnscheduledLatency(*I);
1648 if (L > RemLatency) {
1654 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1655 << LateSU->NodeNum << ") " << RemLatency << "c\n");
1660 // Count resources in this zone and the remaining unscheduled
1661 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1662 // resource index, or zero if the zone is issue limited.
1663 unsigned SchedBoundary::
1664 getOtherResourceCount(unsigned &OtherCritIdx) {
1666 if (!SchedModel->hasInstrSchedModel())
1669 unsigned OtherCritCount = Rem->RemIssueCount
1670 + (RetiredMOps * SchedModel->getMicroOpFactor());
1671 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1672 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1673 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1674 PIdx != PEnd; ++PIdx) {
1675 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1676 if (OtherCount > OtherCritCount) {
1677 OtherCritCount = OtherCount;
1678 OtherCritIdx = PIdx;
1682 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1683 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1684 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1686 return OtherCritCount;
1689 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1690 if (ReadyCycle < MinReadyCycle)
1691 MinReadyCycle = ReadyCycle;
1693 // Check for interlocks first. For the purpose of other heuristics, an
1694 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1695 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1696 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1701 // Record this node as an immediate dependent of the scheduled node.
1705 void SchedBoundary::releaseTopNode(SUnit *SU) {
1706 if (SU->isScheduled)
1709 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1713 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1714 unsigned Latency = I->getLatency();
1716 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1718 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1719 SU->TopReadyCycle = PredReadyCycle + Latency;
1721 releaseNode(SU, SU->TopReadyCycle);
1724 void SchedBoundary::releaseBottomNode(SUnit *SU) {
1725 if (SU->isScheduled)
1728 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1730 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1734 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1735 unsigned Latency = I->getLatency();
1737 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1739 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1740 SU->BotReadyCycle = SuccReadyCycle + Latency;
1742 releaseNode(SU, SU->BotReadyCycle);
1745 /// Move the boundary of scheduled code by one cycle.
1746 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1747 if (SchedModel->getMicroOpBufferSize() == 0) {
1748 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1749 if (MinReadyCycle > NextCycle)
1750 NextCycle = MinReadyCycle;
1752 // Update the current micro-ops, which will issue in the next cycle.
1753 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1754 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1756 // Decrement DependentLatency based on the next cycle.
1757 if ((NextCycle - CurrCycle) > DependentLatency)
1758 DependentLatency = 0;
1760 DependentLatency -= (NextCycle - CurrCycle);
1762 if (!HazardRec->isEnabled()) {
1763 // Bypass HazardRec virtual calls.
1764 CurrCycle = NextCycle;
1767 // Bypass getHazardType calls in case of long latency.
1768 for (; CurrCycle != NextCycle; ++CurrCycle) {
1770 HazardRec->AdvanceCycle();
1772 HazardRec->RecedeCycle();
1775 CheckPending = true;
1776 unsigned LFactor = SchedModel->getLatencyFactor();
1778 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1781 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1784 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
1785 ExecutedResCounts[PIdx] += Count;
1786 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1787 MaxExecutedResCount = ExecutedResCounts[PIdx];
1790 /// Add the given processor resource to this scheduled zone.
1792 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1793 /// during which this resource is consumed.
1795 /// \return the next cycle at which the instruction may execute without
1796 /// oversubscribing resources.
1797 unsigned SchedBoundary::
1798 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
1799 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1800 unsigned Count = Factor * Cycles;
1801 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
1802 << " +" << Cycles << "x" << Factor << "u\n");
1804 // Update Executed resources counts.
1805 incExecutedResources(PIdx, Count);
1806 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1807 Rem->RemainingCounts[PIdx] -= Count;
1809 // Check if this resource exceeds the current critical resource. If so, it
1810 // becomes the critical resource.
1811 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1812 ZoneCritResIdx = PIdx;
1813 DEBUG(dbgs() << " *** Critical resource "
1814 << SchedModel->getResourceName(PIdx) << ": "
1815 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1817 // For reserved resources, record the highest cycle using the resource.
1818 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1819 if (NextAvailable > CurrCycle) {
1820 DEBUG(dbgs() << " Resource conflict: "
1821 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1822 << NextAvailable << "\n");
1824 return NextAvailable;
1827 /// Move the boundary of scheduled code by one SUnit.
1828 void SchedBoundary::bumpNode(SUnit *SU) {
1829 // Update the reservation table.
1830 if (HazardRec->isEnabled()) {
1831 if (!isTop() && SU->isCall) {
1832 // Calls are scheduled with their preceding instructions. For bottom-up
1833 // scheduling, clear the pipeline state before emitting.
1836 HazardRec->EmitInstruction(SU);
1838 // checkHazard should prevent scheduling multiple instructions per cycle that
1839 // exceed the issue width.
1840 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1841 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1843 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
1844 "Cannot schedule this instruction's MicroOps in the current cycle.");
1846 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1847 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1849 unsigned NextCycle = CurrCycle;
1850 switch (SchedModel->getMicroOpBufferSize()) {
1852 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1855 if (ReadyCycle > NextCycle) {
1856 NextCycle = ReadyCycle;
1857 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1861 // We don't currently model the OOO reorder buffer, so consider all
1862 // scheduled MOps to be "retired". We do loosely model in-order resource
1863 // latency. If this instruction uses an in-order resource, account for any
1864 // likely stall cycles.
1865 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1866 NextCycle = ReadyCycle;
1869 RetiredMOps += IncMOps;
1871 // Update resource counts and critical resource.
1872 if (SchedModel->hasInstrSchedModel()) {
1873 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1874 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1875 Rem->RemIssueCount -= DecRemIssue;
1876 if (ZoneCritResIdx) {
1877 // Scale scheduled micro-ops for comparing with the critical resource.
1878 unsigned ScaledMOps =
1879 RetiredMOps * SchedModel->getMicroOpFactor();
1881 // If scaled micro-ops are now more than the previous critical resource by
1882 // a full cycle, then micro-ops issue becomes critical.
1883 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1884 >= (int)SchedModel->getLatencyFactor()) {
1886 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1887 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1890 for (TargetSchedModel::ProcResIter
1891 PI = SchedModel->getWriteProcResBegin(SC),
1892 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1894 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
1895 if (RCycle > NextCycle)
1898 if (SU->hasReservedResource) {
1899 // For reserved resources, record the highest cycle using the resource.
1900 // For top-down scheduling, this is the cycle in which we schedule this
1901 // instruction plus the number of cycles the operations reserves the
1902 // resource. For bottom-up is it simply the instruction's cycle.
1903 for (TargetSchedModel::ProcResIter
1904 PI = SchedModel->getWriteProcResBegin(SC),
1905 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1906 unsigned PIdx = PI->ProcResourceIdx;
1907 if (SchedModel->getProcResource(PIdx)->BufferSize == 0)
1908 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
1912 // Update ExpectedLatency and DependentLatency.
1913 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1914 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1915 if (SU->getDepth() > TopLatency) {
1916 TopLatency = SU->getDepth();
1917 DEBUG(dbgs() << " " << Available.getName()
1918 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1920 if (SU->getHeight() > BotLatency) {
1921 BotLatency = SU->getHeight();
1922 DEBUG(dbgs() << " " << Available.getName()
1923 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1925 // If we stall for any reason, bump the cycle.
1926 if (NextCycle > CurrCycle) {
1927 bumpCycle(NextCycle);
1930 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1931 // resource limited. If a stall occured, bumpCycle does this.
1932 unsigned LFactor = SchedModel->getLatencyFactor();
1934 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1937 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1938 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1939 // one cycle. Since we commonly reach the max MOps here, opportunistically
1940 // bump the cycle to avoid uselessly checking everything in the readyQ.
1941 CurrMOps += IncMOps;
1942 while (CurrMOps >= SchedModel->getIssueWidth()) {
1943 bumpCycle(++NextCycle);
1944 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1945 << " at cycle " << CurrCycle << '\n');
1947 DEBUG(dumpScheduledState());
1950 /// Release pending ready nodes in to the available queue. This makes them
1951 /// visible to heuristics.
1952 void SchedBoundary::releasePending() {
1953 // If the available queue is empty, it is safe to reset MinReadyCycle.
1954 if (Available.empty())
1955 MinReadyCycle = UINT_MAX;
1957 // Check to see if any of the pending instructions are ready to issue. If
1958 // so, add them to the available queue.
1959 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1960 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1961 SUnit *SU = *(Pending.begin()+i);
1962 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1964 if (ReadyCycle < MinReadyCycle)
1965 MinReadyCycle = ReadyCycle;
1967 if (!IsBuffered && ReadyCycle > CurrCycle)
1970 if (checkHazard(SU))
1974 Pending.remove(Pending.begin()+i);
1977 DEBUG(if (!Pending.empty()) Pending.dump());
1978 CheckPending = false;
1981 /// Remove SU from the ready set for this boundary.
1982 void SchedBoundary::removeReady(SUnit *SU) {
1983 if (Available.isInQueue(SU))
1984 Available.remove(Available.find(SU));
1986 assert(Pending.isInQueue(SU) && "bad ready count");
1987 Pending.remove(Pending.find(SU));
1991 /// If this queue only has one ready candidate, return it. As a side effect,
1992 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1993 /// one node is ready. If multiple instructions are ready, return NULL.
1994 SUnit *SchedBoundary::pickOnlyChoice() {
1999 // Defer any ready instrs that now have a hazard.
2000 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2001 if (checkHazard(*I)) {
2003 I = Available.remove(I);
2009 for (unsigned i = 0; Available.empty(); ++i) {
2010 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
2011 "permanent hazard"); (void)i;
2012 bumpCycle(CurrCycle + 1);
2015 if (Available.size() == 1)
2016 return *Available.begin();
2021 // This is useful information to dump after bumpNode.
2022 // Note that the Queue contents are more useful before pickNodeFromQueue.
2023 void SchedBoundary::dumpScheduledState() {
2026 if (ZoneCritResIdx) {
2027 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2028 ResCount = getResourceCount(ZoneCritResIdx);
2031 ResFactor = SchedModel->getMicroOpFactor();
2032 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2034 unsigned LFactor = SchedModel->getLatencyFactor();
2035 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2036 << " Retired: " << RetiredMOps;
2037 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2038 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
2039 << ResCount / ResFactor << " "
2040 << SchedModel->getResourceName(ZoneCritResIdx)
2041 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2042 << (IsResourceLimited ? " - Resource" : " - Latency")
2047 //===----------------------------------------------------------------------===//
2048 // GenericScheduler - Implementation of the generic MachineSchedStrategy.
2049 //===----------------------------------------------------------------------===//
2052 /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
2054 class GenericScheduler : public MachineSchedStrategy {
2056 /// Represent the type of SchedCandidate found within a single queue.
2057 /// pickNodeBidirectional depends on these listed by decreasing priority.
2059 NoCand, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak, RegMax,
2060 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
2061 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
2064 static const char *getReasonStr(GenericScheduler::CandReason Reason);
2067 /// Policy for scheduling the next instruction in the candidate's zone.
2070 unsigned ReduceResIdx;
2071 unsigned DemandResIdx;
2073 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
2076 /// Status of an instruction's critical resource consumption.
2077 struct SchedResourceDelta {
2078 // Count critical resources in the scheduled region required by SU.
2079 unsigned CritResources;
2081 // Count critical resources from another region consumed by SU.
2082 unsigned DemandedResources;
2084 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
2086 bool operator==(const SchedResourceDelta &RHS) const {
2087 return CritResources == RHS.CritResources
2088 && DemandedResources == RHS.DemandedResources;
2090 bool operator!=(const SchedResourceDelta &RHS) const {
2091 return !operator==(RHS);
2095 /// Store the state used by GenericScheduler heuristics, required for the
2096 /// lifetime of one invocation of pickNode().
2097 struct SchedCandidate {
2100 // The best SUnit candidate.
2103 // The reason for this candidate.
2106 // Set of reasons that apply to multiple candidates.
2107 uint32_t RepeatReasonSet;
2109 // Register pressure values for the best candidate.
2110 RegPressureDelta RPDelta;
2112 // Critical resource consumption of the best candidate.
2113 SchedResourceDelta ResDelta;
2115 SchedCandidate(const CandPolicy &policy)
2116 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
2118 bool isValid() const { return SU; }
2120 // Copy the status of another candidate without changing policy.
2121 void setBest(SchedCandidate &Best) {
2122 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
2124 Reason = Best.Reason;
2125 RPDelta = Best.RPDelta;
2126 ResDelta = Best.ResDelta;
2129 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
2130 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
2132 void initResourceDelta(const ScheduleDAGMILive *DAG,
2133 const TargetSchedModel *SchedModel);
2137 const MachineSchedContext *Context;
2138 ScheduleDAGMILive *DAG;
2139 const TargetSchedModel *SchedModel;
2140 const TargetRegisterInfo *TRI;
2142 // State of the top and bottom scheduled instruction boundaries.
2147 MachineSchedPolicy RegionPolicy;
2149 GenericScheduler(const MachineSchedContext *C):
2150 Context(C), DAG(0), SchedModel(0), TRI(0),
2151 Top(SchedBoundary::TopQID, "TopQ"), Bot(SchedBoundary::BotQID, "BotQ") {}
2153 virtual void initPolicy(MachineBasicBlock::iterator Begin,
2154 MachineBasicBlock::iterator End,
2155 unsigned NumRegionInstrs);
2157 bool shouldTrackPressure() const { return RegionPolicy.ShouldTrackPressure; }
2159 virtual void initialize(ScheduleDAGMI *dag);
2161 virtual SUnit *pickNode(bool &IsTopNode);
2163 virtual void schedNode(SUnit *SU, bool IsTopNode);
2165 virtual void releaseTopNode(SUnit *SU) { Top.releaseTopNode(SU); }
2167 virtual void releaseBottomNode(SUnit *SU) { Bot.releaseBottomNode(SU); }
2169 virtual void registerRoots();
2172 void checkAcyclicLatency();
2174 void setPolicy(CandPolicy &Policy, SchedBoundary &CurrZone,
2175 SchedBoundary &OtherZone);
2177 void tryCandidate(SchedCandidate &Cand,
2178 SchedCandidate &TryCand,
2179 SchedBoundary &Zone,
2180 const RegPressureTracker &RPTracker,
2181 RegPressureTracker &TempTracker);
2183 SUnit *pickNodeBidirectional(bool &IsTopNode);
2185 void pickNodeFromQueue(SchedBoundary &Zone,
2186 const RegPressureTracker &RPTracker,
2187 SchedCandidate &Candidate);
2189 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
2192 void traceCandidate(const SchedCandidate &Cand);
2197 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2198 assert(dag->hasVRegLiveness() &&
2199 "(PreRA)GenericScheduler needs vreg liveness");
2200 DAG = static_cast<ScheduleDAGMILive*>(dag);
2201 SchedModel = DAG->getSchedModel();
2204 Rem.init(DAG, SchedModel);
2205 Top.init(DAG, SchedModel, &Rem);
2206 Bot.init(DAG, SchedModel, &Rem);
2208 // Initialize resource counts.
2210 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2211 // are disabled, then these HazardRecs will be disabled.
2212 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2213 const TargetMachine &TM = DAG->MF.getTarget();
2214 if (!Top.HazardRec) {
2216 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2218 if (!Bot.HazardRec) {
2220 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2224 /// Initialize the per-region scheduling policy.
2225 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2226 MachineBasicBlock::iterator End,
2227 unsigned NumRegionInstrs) {
2228 const TargetMachine &TM = Context->MF->getTarget();
2230 // Avoid setting up the register pressure tracker for small regions to save
2231 // compile time. As a rough heuristic, only track pressure when the number of
2232 // schedulable instructions exceeds half the integer register file.
2233 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2234 TM.getTargetLowering()->getRegClassFor(MVT::i32));
2236 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2238 // For generic targets, we default to bottom-up, because it's simpler and more
2239 // compile-time optimizations have been implemented in that direction.
2240 RegionPolicy.OnlyBottomUp = true;
2242 // Allow the subtarget to override default policy.
2243 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2244 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2246 // After subtarget overrides, apply command line options.
2247 if (!EnableRegPressure)
2248 RegionPolicy.ShouldTrackPressure = false;
2250 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2251 // e.g. -misched-bottomup=false allows scheduling in both directions.
2252 assert((!ForceTopDown || !ForceBottomUp) &&
2253 "-misched-topdown incompatible with -misched-bottomup");
2254 if (ForceBottomUp.getNumOccurrences() > 0) {
2255 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2256 if (RegionPolicy.OnlyBottomUp)
2257 RegionPolicy.OnlyTopDown = false;
2259 if (ForceTopDown.getNumOccurrences() > 0) {
2260 RegionPolicy.OnlyTopDown = ForceTopDown;
2261 if (RegionPolicy.OnlyTopDown)
2262 RegionPolicy.OnlyBottomUp = false;
2266 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2267 /// critical path by more cycles than it takes to drain the instruction buffer.
2268 /// We estimate an upper bounds on in-flight instructions as:
2270 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2271 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2272 /// InFlightResources = InFlightIterations * LoopResources
2274 /// TODO: Check execution resources in addition to IssueCount.
2275 void GenericScheduler::checkAcyclicLatency() {
2276 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2279 // Scaled number of cycles per loop iteration.
2280 unsigned IterCount =
2281 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2283 // Scaled acyclic critical path.
2284 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2285 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2286 unsigned InFlightCount =
2287 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2288 unsigned BufferLimit =
2289 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2291 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2293 DEBUG(dbgs() << "IssueCycles="
2294 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2295 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2296 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2297 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2298 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2299 if (Rem.IsAcyclicLatencyLimited)
2300 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2303 void GenericScheduler::registerRoots() {
2304 Rem.CriticalPath = DAG->ExitSU.getDepth();
2306 // Some roots may not feed into ExitSU. Check all of them in case.
2307 for (std::vector<SUnit*>::const_iterator
2308 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2309 if ((*I)->getDepth() > Rem.CriticalPath)
2310 Rem.CriticalPath = (*I)->getDepth();
2312 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2314 if (EnableCyclicPath) {
2315 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2316 checkAcyclicLatency();
2320 /// Set the CandPolicy given a scheduling zone given the current resources and
2321 /// latencies inside and outside the zone.
2322 void GenericScheduler::setPolicy(CandPolicy &Policy, SchedBoundary &CurrZone,
2323 SchedBoundary &OtherZone) {
2324 // Apply preemptive heuristics based on the the total latency and resources
2325 // inside and outside this zone. Potential stalls should be considered before
2326 // following this policy.
2328 // Compute remaining latency. We need this both to determine whether the
2329 // overall schedule has become latency-limited and whether the instructions
2330 // outside this zone are resource or latency limited.
2332 // The "dependent" latency is updated incrementally during scheduling as the
2333 // max height/depth of scheduled nodes minus the cycles since it was
2335 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2337 // The "independent" latency is the max ready queue depth:
2338 // ILat = max N.depth for N in Available|Pending
2340 // RemainingLatency is the greater of independent and dependent latency.
2341 unsigned RemLatency = CurrZone.getDependentLatency();
2342 RemLatency = std::max(RemLatency,
2343 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2344 RemLatency = std::max(RemLatency,
2345 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2347 // Compute the critical resource outside the zone.
2348 unsigned OtherCritIdx;
2349 unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
2351 bool OtherResLimited = false;
2352 if (SchedModel->hasInstrSchedModel()) {
2353 unsigned LFactor = SchedModel->getLatencyFactor();
2354 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2356 if (!OtherResLimited
2357 && (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2358 Policy.ReduceLatency |= true;
2359 DEBUG(dbgs() << " " << CurrZone.Available.getName() << " RemainingLatency "
2360 << RemLatency << " + " << CurrZone.getCurrCycle() << "c > CritPath "
2361 << Rem.CriticalPath << "\n");
2363 // If the same resource is limiting inside and outside the zone, do nothing.
2364 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2368 if (CurrZone.isResourceLimited()) {
2369 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2370 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2373 if (OtherResLimited)
2374 dbgs() << " RemainingLimit: "
2375 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2376 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2377 dbgs() << " Latency limited both directions.\n");
2379 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2380 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2382 if (OtherResLimited)
2383 Policy.DemandResIdx = OtherCritIdx;
2386 void GenericScheduler::SchedCandidate::
2387 initResourceDelta(const ScheduleDAGMILive *DAG,
2388 const TargetSchedModel *SchedModel) {
2389 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2392 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2393 for (TargetSchedModel::ProcResIter
2394 PI = SchedModel->getWriteProcResBegin(SC),
2395 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2396 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2397 ResDelta.CritResources += PI->Cycles;
2398 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2399 ResDelta.DemandedResources += PI->Cycles;
2403 /// Return true if this heuristic determines order.
2404 static bool tryLess(int TryVal, int CandVal,
2405 GenericScheduler::SchedCandidate &TryCand,
2406 GenericScheduler::SchedCandidate &Cand,
2407 GenericScheduler::CandReason Reason) {
2408 if (TryVal < CandVal) {
2409 TryCand.Reason = Reason;
2412 if (TryVal > CandVal) {
2413 if (Cand.Reason > Reason)
2414 Cand.Reason = Reason;
2417 Cand.setRepeat(Reason);
2421 static bool tryGreater(int TryVal, int CandVal,
2422 GenericScheduler::SchedCandidate &TryCand,
2423 GenericScheduler::SchedCandidate &Cand,
2424 GenericScheduler::CandReason Reason) {
2425 if (TryVal > CandVal) {
2426 TryCand.Reason = Reason;
2429 if (TryVal < CandVal) {
2430 if (Cand.Reason > Reason)
2431 Cand.Reason = Reason;
2434 Cand.setRepeat(Reason);
2438 static bool tryPressure(const PressureChange &TryP,
2439 const PressureChange &CandP,
2440 GenericScheduler::SchedCandidate &TryCand,
2441 GenericScheduler::SchedCandidate &Cand,
2442 GenericScheduler::CandReason Reason) {
2443 int TryRank = TryP.getPSetOrMax();
2444 int CandRank = CandP.getPSetOrMax();
2445 // If both candidates affect the same set, go with the smallest increase.
2446 if (TryRank == CandRank) {
2447 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2450 // If one candidate decreases and the other increases, go with it.
2451 // Invalid candidates have UnitInc==0.
2452 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2456 // If the candidates are decreasing pressure, reverse priority.
2457 if (TryP.getUnitInc() < 0)
2458 std::swap(TryRank, CandRank);
2459 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2462 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2463 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2466 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2467 /// their physreg def/use.
2469 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2470 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2471 /// with the operation that produces or consumes the physreg. We'll do this when
2472 /// regalloc has support for parallel copies.
2473 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2474 const MachineInstr *MI = SU->getInstr();
2478 unsigned ScheduledOper = isTop ? 1 : 0;
2479 unsigned UnscheduledOper = isTop ? 0 : 1;
2480 // If we have already scheduled the physreg produce/consumer, immediately
2481 // schedule the copy.
2482 if (TargetRegisterInfo::isPhysicalRegister(
2483 MI->getOperand(ScheduledOper).getReg()))
2485 // If the physreg is at the boundary, defer it. Otherwise schedule it
2486 // immediately to free the dependent. We can hoist the copy later.
2487 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2488 if (TargetRegisterInfo::isPhysicalRegister(
2489 MI->getOperand(UnscheduledOper).getReg()))
2490 return AtBoundary ? -1 : 1;
2494 static bool tryLatency(GenericScheduler::SchedCandidate &TryCand,
2495 GenericScheduler::SchedCandidate &Cand,
2496 SchedBoundary &Zone) {
2498 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2499 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2500 TryCand, Cand, GenericScheduler::TopDepthReduce))
2503 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2504 TryCand, Cand, GenericScheduler::TopPathReduce))
2508 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2509 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2510 TryCand, Cand, GenericScheduler::BotHeightReduce))
2513 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2514 TryCand, Cand, GenericScheduler::BotPathReduce))
2520 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2521 /// hierarchical. This may be more efficient than a graduated cost model because
2522 /// we don't need to evaluate all aspects of the model for each node in the
2523 /// queue. But it's really done to make the heuristics easier to debug and
2524 /// statistically analyze.
2526 /// \param Cand provides the policy and current best candidate.
2527 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2528 /// \param Zone describes the scheduled zone that we are extending.
2529 /// \param RPTracker describes reg pressure within the scheduled zone.
2530 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2531 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2532 SchedCandidate &TryCand,
2533 SchedBoundary &Zone,
2534 const RegPressureTracker &RPTracker,
2535 RegPressureTracker &TempTracker) {
2537 if (DAG->isTrackingPressure()) {
2538 // Always initialize TryCand's RPDelta.
2540 TempTracker.getMaxDownwardPressureDelta(
2541 TryCand.SU->getInstr(),
2543 DAG->getRegionCriticalPSets(),
2544 DAG->getRegPressure().MaxSetPressure);
2547 if (VerifyScheduling) {
2548 TempTracker.getMaxUpwardPressureDelta(
2549 TryCand.SU->getInstr(),
2550 &DAG->getPressureDiff(TryCand.SU),
2552 DAG->getRegionCriticalPSets(),
2553 DAG->getRegPressure().MaxSetPressure);
2556 RPTracker.getUpwardPressureDelta(
2557 TryCand.SU->getInstr(),
2558 DAG->getPressureDiff(TryCand.SU),
2560 DAG->getRegionCriticalPSets(),
2561 DAG->getRegPressure().MaxSetPressure);
2565 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2566 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2567 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2568 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
2570 // Initialize the candidate if needed.
2571 if (!Cand.isValid()) {
2572 TryCand.Reason = NodeOrder;
2576 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2577 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2578 TryCand, Cand, PhysRegCopy))
2581 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2582 // invalid; convert it to INT_MAX to give it lowest priority.
2583 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2584 Cand.RPDelta.Excess,
2585 TryCand, Cand, RegExcess))
2588 // Avoid increasing the max critical pressure in the scheduled region.
2589 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2590 Cand.RPDelta.CriticalMax,
2591 TryCand, Cand, RegCritical))
2594 // For loops that are acyclic path limited, aggressively schedule for latency.
2595 // This can result in very long dependence chains scheduled in sequence, so
2596 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
2597 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
2598 && tryLatency(TryCand, Cand, Zone))
2601 // Prioritize instructions that read unbuffered resources by stall cycles.
2602 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2603 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2606 // Keep clustered nodes together to encourage downstream peephole
2607 // optimizations which may reduce resource requirements.
2609 // This is a best effort to set things up for a post-RA pass. Optimizations
2610 // like generating loads of multiple registers should ideally be done within
2611 // the scheduler pass by combining the loads during DAG postprocessing.
2612 const SUnit *NextClusterSU =
2613 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2614 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2615 TryCand, Cand, Cluster))
2618 // Weak edges are for clustering and other constraints.
2619 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2620 getWeakLeft(Cand.SU, Zone.isTop()),
2621 TryCand, Cand, Weak)) {
2624 // Avoid increasing the max pressure of the entire region.
2625 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2626 Cand.RPDelta.CurrentMax,
2627 TryCand, Cand, RegMax))
2630 // Avoid critical resource consumption and balance the schedule.
2631 TryCand.initResourceDelta(DAG, SchedModel);
2632 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2633 TryCand, Cand, ResourceReduce))
2635 if (tryGreater(TryCand.ResDelta.DemandedResources,
2636 Cand.ResDelta.DemandedResources,
2637 TryCand, Cand, ResourceDemand))
2640 // Avoid serializing long latency dependence chains.
2641 // For acyclic path limited loops, latency was already checked above.
2642 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2643 && tryLatency(TryCand, Cand, Zone)) {
2647 // Prefer immediate defs/users of the last scheduled instruction. This is a
2648 // local pressure avoidance strategy that also makes the machine code
2650 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
2651 TryCand, Cand, NextDefUse))
2654 // Fall through to original instruction order.
2655 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2656 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2657 TryCand.Reason = NodeOrder;
2662 const char *GenericScheduler::getReasonStr(
2663 GenericScheduler::CandReason Reason) {
2665 case NoCand: return "NOCAND ";
2666 case PhysRegCopy: return "PREG-COPY";
2667 case RegExcess: return "REG-EXCESS";
2668 case RegCritical: return "REG-CRIT ";
2669 case Stall: return "STALL ";
2670 case Cluster: return "CLUSTER ";
2671 case Weak: return "WEAK ";
2672 case RegMax: return "REG-MAX ";
2673 case ResourceReduce: return "RES-REDUCE";
2674 case ResourceDemand: return "RES-DEMAND";
2675 case TopDepthReduce: return "TOP-DEPTH ";
2676 case TopPathReduce: return "TOP-PATH ";
2677 case BotHeightReduce:return "BOT-HEIGHT";
2678 case BotPathReduce: return "BOT-PATH ";
2679 case NextDefUse: return "DEF-USE ";
2680 case NodeOrder: return "ORDER ";
2682 llvm_unreachable("Unknown reason!");
2685 void GenericScheduler::traceCandidate(const SchedCandidate &Cand) {
2687 unsigned ResIdx = 0;
2688 unsigned Latency = 0;
2689 switch (Cand.Reason) {
2693 P = Cand.RPDelta.Excess;
2696 P = Cand.RPDelta.CriticalMax;
2699 P = Cand.RPDelta.CurrentMax;
2701 case ResourceReduce:
2702 ResIdx = Cand.Policy.ReduceResIdx;
2704 case ResourceDemand:
2705 ResIdx = Cand.Policy.DemandResIdx;
2707 case TopDepthReduce:
2708 Latency = Cand.SU->getDepth();
2711 Latency = Cand.SU->getHeight();
2713 case BotHeightReduce:
2714 Latency = Cand.SU->getHeight();
2717 Latency = Cand.SU->getDepth();
2720 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2722 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2723 << ":" << P.getUnitInc() << " ";
2727 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2731 dbgs() << " " << Latency << " cycles ";
2738 /// Pick the best candidate from the queue.
2740 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2741 /// DAG building. To adjust for the current scheduling location we need to
2742 /// maintain the number of vreg uses remaining to be top-scheduled.
2743 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2744 const RegPressureTracker &RPTracker,
2745 SchedCandidate &Cand) {
2746 ReadyQueue &Q = Zone.Available;
2750 // getMaxPressureDelta temporarily modifies the tracker.
2751 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2753 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2755 SchedCandidate TryCand(Cand.Policy);
2757 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2758 if (TryCand.Reason != NoCand) {
2759 // Initialize resource delta if needed in case future heuristics query it.
2760 if (TryCand.ResDelta == SchedResourceDelta())
2761 TryCand.initResourceDelta(DAG, SchedModel);
2762 Cand.setBest(TryCand);
2763 DEBUG(traceCandidate(Cand));
2768 static void tracePick(const GenericScheduler::SchedCandidate &Cand,
2770 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2771 << GenericScheduler::getReasonStr(Cand.Reason) << '\n');
2774 /// Pick the best candidate node from either the top or bottom queue.
2775 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2776 // Schedule as far as possible in the direction of no choice. This is most
2777 // efficient, but also provides the best heuristics for CriticalPSets.
2778 if (SUnit *SU = Bot.pickOnlyChoice()) {
2780 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2783 if (SUnit *SU = Top.pickOnlyChoice()) {
2785 DEBUG(dbgs() << "Pick Top NOCAND\n");
2788 CandPolicy NoPolicy;
2789 SchedCandidate BotCand(NoPolicy);
2790 SchedCandidate TopCand(NoPolicy);
2791 // Set the bottom-up policy based on the state of the current bottom zone and
2792 // the instructions outside the zone, including the top zone.
2793 setPolicy(BotCand.Policy, Bot, Top);
2794 // Set the top-down policy based on the state of the current top zone and
2795 // the instructions outside the zone, including the bottom zone.
2796 setPolicy(TopCand.Policy, Top, Bot);
2798 // Prefer bottom scheduling when heuristics are silent.
2799 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2800 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2802 // If either Q has a single candidate that provides the least increase in
2803 // Excess pressure, we can immediately schedule from that Q.
2805 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2806 // affects picking from either Q. If scheduling in one direction must
2807 // increase pressure for one of the excess PSets, then schedule in that
2808 // direction first to provide more freedom in the other direction.
2809 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2810 || (BotCand.Reason == RegCritical
2811 && !BotCand.isRepeat(RegCritical)))
2814 tracePick(BotCand, IsTopNode);
2817 // Check if the top Q has a better candidate.
2818 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2819 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2821 // Choose the queue with the most important (lowest enum) reason.
2822 if (TopCand.Reason < BotCand.Reason) {
2824 tracePick(TopCand, IsTopNode);
2827 // Otherwise prefer the bottom candidate, in node order if all else failed.
2829 tracePick(BotCand, IsTopNode);
2833 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2834 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2835 if (DAG->top() == DAG->bottom()) {
2836 assert(Top.Available.empty() && Top.Pending.empty() &&
2837 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2842 if (RegionPolicy.OnlyTopDown) {
2843 SU = Top.pickOnlyChoice();
2845 CandPolicy NoPolicy;
2846 SchedCandidate TopCand(NoPolicy);
2847 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2848 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2849 tracePick(TopCand, true);
2854 else if (RegionPolicy.OnlyBottomUp) {
2855 SU = Bot.pickOnlyChoice();
2857 CandPolicy NoPolicy;
2858 SchedCandidate BotCand(NoPolicy);
2859 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2860 assert(BotCand.Reason != NoCand && "failed to find a candidate");
2861 tracePick(BotCand, false);
2867 SU = pickNodeBidirectional(IsTopNode);
2869 } while (SU->isScheduled);
2871 if (SU->isTopReady())
2872 Top.removeReady(SU);
2873 if (SU->isBottomReady())
2874 Bot.removeReady(SU);
2876 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2880 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2882 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2885 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2887 // Find already scheduled copies with a single physreg dependence and move
2888 // them just above the scheduled instruction.
2889 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2891 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2893 SUnit *DepSU = I->getSUnit();
2894 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2896 MachineInstr *Copy = DepSU->getInstr();
2897 if (!Copy->isCopy())
2899 DEBUG(dbgs() << " Rescheduling physreg copy ";
2900 I->getSUnit()->dump(DAG));
2901 DAG->moveInstruction(Copy, InsertPos);
2905 /// Update the scheduler's state after scheduling a node. This is the same node
2906 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to update
2907 /// it's state based on the current cycle before MachineSchedStrategy does.
2909 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2910 /// them here. See comments in biasPhysRegCopy.
2911 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2913 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2915 if (SU->hasPhysRegUses)
2916 reschedulePhysRegCopies(SU, true);
2919 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
2921 if (SU->hasPhysRegDefs)
2922 reschedulePhysRegCopies(SU, false);
2926 /// Create a generic scheduler with no DAG mutation passes.
2927 static ScheduleDAGInstrs *createRawGenericSched(MachineSchedContext *C) {
2928 return new ScheduleDAGMILive(C, new GenericScheduler(C));
2931 /// Create the standard converging machine scheduler. This will be used as the
2932 /// default scheduler if the target does not set a default.
2933 static ScheduleDAGInstrs *createGenericSched(MachineSchedContext *C) {
2934 ScheduleDAGMILive *DAG =
2935 static_cast<ScheduleDAGMILive*>(createRawGenericSched(C));
2936 // Register DAG post-processors.
2938 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2939 // data and pass it to later mutations. Have a single mutation that gathers
2940 // the interesting nodes in one pass.
2941 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
2942 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
2943 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2944 if (EnableMacroFusion)
2945 DAG->addMutation(new MacroFusion(DAG->TII));
2948 static MachineSchedRegistry
2949 GenericSchedRegistry("converge", "Standard converging scheduler.",
2950 createGenericSched);
2952 //===----------------------------------------------------------------------===//
2953 // ILP Scheduler. Currently for experimental analysis of heuristics.
2954 //===----------------------------------------------------------------------===//
2957 /// \brief Order nodes by the ILP metric.
2959 const SchedDFSResult *DFSResult;
2960 const BitVector *ScheduledTrees;
2963 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2965 /// \brief Apply a less-than relation on node priority.
2967 /// (Return true if A comes after B in the Q.)
2968 bool operator()(const SUnit *A, const SUnit *B) const {
2969 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2970 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2971 if (SchedTreeA != SchedTreeB) {
2972 // Unscheduled trees have lower priority.
2973 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2974 return ScheduledTrees->test(SchedTreeB);
2976 // Trees with shallower connections have have lower priority.
2977 if (DFSResult->getSubtreeLevel(SchedTreeA)
2978 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2979 return DFSResult->getSubtreeLevel(SchedTreeA)
2980 < DFSResult->getSubtreeLevel(SchedTreeB);
2984 return DFSResult->getILP(A) < DFSResult->getILP(B);
2986 return DFSResult->getILP(A) > DFSResult->getILP(B);
2990 /// \brief Schedule based on the ILP metric.
2991 class ILPScheduler : public MachineSchedStrategy {
2992 ScheduleDAGMILive *DAG;
2995 std::vector<SUnit*> ReadyQ;
2997 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2999 virtual void initialize(ScheduleDAGMI *dag) {
3000 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3001 DAG = static_cast<ScheduleDAGMILive*>(dag);
3002 DAG->computeDFSResult();
3003 Cmp.DFSResult = DAG->getDFSResult();
3004 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3008 virtual void registerRoots() {
3009 // Restore the heap in ReadyQ with the updated DFS results.
3010 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3013 /// Implement MachineSchedStrategy interface.
3014 /// -----------------------------------------
3016 /// Callback to select the highest priority node from the ready Q.
3017 virtual SUnit *pickNode(bool &IsTopNode) {
3018 if (ReadyQ.empty()) return NULL;
3019 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3020 SUnit *SU = ReadyQ.back();
3023 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3024 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3025 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3026 << DAG->getDFSResult()->getSubtreeLevel(
3027 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3028 << "Scheduling " << *SU->getInstr());
3032 /// \brief Scheduler callback to notify that a new subtree is scheduled.
3033 virtual void scheduleTree(unsigned SubtreeID) {
3034 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3037 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3038 /// DFSResults, and resort the priority Q.
3039 virtual void schedNode(SUnit *SU, bool IsTopNode) {
3040 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3043 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
3045 virtual void releaseBottomNode(SUnit *SU) {
3046 ReadyQ.push_back(SU);
3047 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3052 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3053 return new ScheduleDAGMILive(C, new ILPScheduler(true));
3055 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3056 return new ScheduleDAGMILive(C, new ILPScheduler(false));
3058 static MachineSchedRegistry ILPMaxRegistry(
3059 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3060 static MachineSchedRegistry ILPMinRegistry(
3061 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3063 //===----------------------------------------------------------------------===//
3064 // Machine Instruction Shuffler for Correctness Testing
3065 //===----------------------------------------------------------------------===//
3069 /// Apply a less-than relation on the node order, which corresponds to the
3070 /// instruction order prior to scheduling. IsReverse implements greater-than.
3071 template<bool IsReverse>
3073 bool operator()(SUnit *A, SUnit *B) const {
3075 return A->NodeNum > B->NodeNum;
3077 return A->NodeNum < B->NodeNum;
3081 /// Reorder instructions as much as possible.
3082 class InstructionShuffler : public MachineSchedStrategy {
3086 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3087 // gives nodes with a higher number higher priority causing the latest
3088 // instructions to be scheduled first.
3089 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3091 // When scheduling bottom-up, use greater-than as the queue priority.
3092 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3095 InstructionShuffler(bool alternate, bool topdown)
3096 : IsAlternating(alternate), IsTopDown(topdown) {}
3098 virtual void initialize(ScheduleDAGMI*) {
3103 /// Implement MachineSchedStrategy interface.
3104 /// -----------------------------------------
3106 virtual SUnit *pickNode(bool &IsTopNode) {
3110 if (TopQ.empty()) return NULL;
3113 } while (SU->isScheduled);
3118 if (BottomQ.empty()) return NULL;
3121 } while (SU->isScheduled);
3125 IsTopDown = !IsTopDown;
3129 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
3131 virtual void releaseTopNode(SUnit *SU) {
3134 virtual void releaseBottomNode(SUnit *SU) {
3140 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3141 bool Alternate = !ForceTopDown && !ForceBottomUp;
3142 bool TopDown = !ForceBottomUp;
3143 assert((TopDown || !ForceTopDown) &&
3144 "-misched-topdown incompatible with -misched-bottomup");
3145 return new ScheduleDAGMILive(C, new InstructionShuffler(Alternate, TopDown));
3147 static MachineSchedRegistry ShufflerRegistry(
3148 "shuffle", "Shuffle machine instructions alternating directions",
3149 createInstructionShuffler);
3152 //===----------------------------------------------------------------------===//
3153 // GraphWriter support for ScheduleDAGMILive.
3154 //===----------------------------------------------------------------------===//
3159 template<> struct GraphTraits<
3160 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3163 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3165 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3167 static std::string getGraphName(const ScheduleDAG *G) {
3168 return G->MF.getName();
3171 static bool renderGraphFromBottomUp() {
3175 static bool isNodeHidden(const SUnit *Node) {
3176 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
3179 static bool hasNodeAddressLabel(const SUnit *Node,
3180 const ScheduleDAG *Graph) {
3184 /// If you want to override the dot attributes printed for a particular
3185 /// edge, override this method.
3186 static std::string getEdgeAttributes(const SUnit *Node,
3188 const ScheduleDAG *Graph) {
3189 if (EI.isArtificialDep())
3190 return "color=cyan,style=dashed";
3192 return "color=blue,style=dashed";
3196 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3198 raw_string_ostream SS(Str);
3199 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3200 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3201 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3202 SS << "SU:" << SU->NodeNum;
3204 SS << " I:" << DFS->getNumInstrs(SU);
3207 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3208 return G->getGraphNodeLabel(SU);
3211 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3212 std::string Str("shape=Mrecord");
3213 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3214 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3215 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3217 Str += ",style=filled,fillcolor=\"#";
3218 Str += DOT::getColorString(DFS->getSubtreeID(N));
3227 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3228 /// rendered using 'dot'.
3230 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3232 ViewGraph(this, Name, false, Title);
3234 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3235 << "systems with Graphviz or gv!\n";
3239 /// Out-of-line implementation with no arguments is handy for gdb.
3240 void ScheduleDAGMI::viewGraph() {
3241 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());