misched: DAG builder support for tracking register pressure within the current schedu...
[oota-llvm.git] / lib / CodeGen / MachineScheduler.cpp
1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "misched"
16
17 #include "RegisterPressure.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineScheduler.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/PriorityQueue.h"
30
31 #include <queue>
32
33 using namespace llvm;
34
35 static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36                                   cl::desc("Force top-down list scheduling"));
37 static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38                                   cl::desc("Force bottom-up list scheduling"));
39
40 #ifndef NDEBUG
41 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
42   cl::desc("Pop up a window to show MISched dags after they are processed"));
43
44 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
45   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
46 #else
47 static bool ViewMISchedDAGs = false;
48 #endif // NDEBUG
49
50 //===----------------------------------------------------------------------===//
51 // Machine Instruction Scheduling Pass and Registry
52 //===----------------------------------------------------------------------===//
53
54 namespace {
55 /// MachineScheduler runs after coalescing and before register allocation.
56 class MachineScheduler : public MachineSchedContext,
57                          public MachineFunctionPass {
58 public:
59   MachineScheduler();
60
61   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
62
63   virtual void releaseMemory() {}
64
65   virtual bool runOnMachineFunction(MachineFunction&);
66
67   virtual void print(raw_ostream &O, const Module* = 0) const;
68
69   static char ID; // Class identification, replacement for typeinfo
70 };
71 } // namespace
72
73 char MachineScheduler::ID = 0;
74
75 char &llvm::MachineSchedulerID = MachineScheduler::ID;
76
77 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
78                       "Machine Instruction Scheduler", false, false)
79 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
80 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
81 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
82 INITIALIZE_PASS_END(MachineScheduler, "misched",
83                     "Machine Instruction Scheduler", false, false)
84
85 MachineScheduler::MachineScheduler()
86 : MachineFunctionPass(ID) {
87   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
88 }
89
90 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
91   AU.setPreservesCFG();
92   AU.addRequiredID(MachineDominatorsID);
93   AU.addRequired<MachineLoopInfo>();
94   AU.addRequired<AliasAnalysis>();
95   AU.addRequired<TargetPassConfig>();
96   AU.addRequired<SlotIndexes>();
97   AU.addPreserved<SlotIndexes>();
98   AU.addRequired<LiveIntervals>();
99   AU.addPreserved<LiveIntervals>();
100   MachineFunctionPass::getAnalysisUsage(AU);
101 }
102
103 MachinePassRegistry MachineSchedRegistry::Registry;
104
105 /// A dummy default scheduler factory indicates whether the scheduler
106 /// is overridden on the command line.
107 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
108   return 0;
109 }
110
111 /// MachineSchedOpt allows command line selection of the scheduler.
112 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
113                RegisterPassParser<MachineSchedRegistry> >
114 MachineSchedOpt("misched",
115                 cl::init(&useDefaultMachineSched), cl::Hidden,
116                 cl::desc("Machine instruction scheduler to use"));
117
118 static MachineSchedRegistry
119 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
120                      useDefaultMachineSched);
121
122 /// Forward declare the standard machine scheduler. This will be used as the
123 /// default scheduler if the target does not set a default.
124 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
125
126 /// Top-level MachineScheduler pass driver.
127 ///
128 /// Visit blocks in function order. Divide each block into scheduling regions
129 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
130 /// consistent with the DAG builder, which traverses the interior of the
131 /// scheduling regions bottom-up.
132 ///
133 /// This design avoids exposing scheduling boundaries to the DAG builder,
134 /// simplifying the DAG builder's support for "special" target instructions.
135 /// At the same time the design allows target schedulers to operate across
136 /// scheduling boundaries, for example to bundle the boudary instructions
137 /// without reordering them. This creates complexity, because the target
138 /// scheduler must update the RegionBegin and RegionEnd positions cached by
139 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
140 /// design would be to split blocks at scheduling boundaries, but LLVM has a
141 /// general bias against block splitting purely for implementation simplicity.
142 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
143   // Initialize the context of the pass.
144   MF = &mf;
145   MLI = &getAnalysis<MachineLoopInfo>();
146   MDT = &getAnalysis<MachineDominatorTree>();
147   PassConfig = &getAnalysis<TargetPassConfig>();
148   AA = &getAnalysis<AliasAnalysis>();
149
150   LIS = &getAnalysis<LiveIntervals>();
151   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
152
153   RegClassInfo.runOnMachineFunction(*MF);
154
155   // Select the scheduler, or set the default.
156   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
157   if (Ctor == useDefaultMachineSched) {
158     // Get the default scheduler set by the target.
159     Ctor = MachineSchedRegistry::getDefault();
160     if (!Ctor) {
161       Ctor = createConvergingSched;
162       MachineSchedRegistry::setDefault(Ctor);
163     }
164   }
165   // Instantiate the selected scheduler.
166   OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
167
168   // Visit all machine basic blocks.
169   //
170   // TODO: Visit blocks in global postorder or postorder within the bottom-up
171   // loop tree. Then we can optionally compute global RegPressure.
172   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
173        MBB != MBBEnd; ++MBB) {
174
175     Scheduler->startBlock(MBB);
176
177     // Break the block into scheduling regions [I, RegionEnd), and schedule each
178     // region as soon as it is discovered. RegionEnd points the the scheduling
179     // boundary at the bottom of the region. The DAG does not include RegionEnd,
180     // but the region does (i.e. the next RegionEnd is above the previous
181     // RegionBegin). If the current block has no terminator then RegionEnd ==
182     // MBB->end() for the bottom region.
183     //
184     // The Scheduler may insert instructions during either schedule() or
185     // exitRegion(), even for empty regions. So the local iterators 'I' and
186     // 'RegionEnd' are invalid across these calls.
187     unsigned RemainingCount = MBB->size();
188     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
189         RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
190
191       // Avoid decrementing RegionEnd for blocks with no terminator.
192       if (RegionEnd != MBB->end()
193           || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
194         --RegionEnd;
195         // Count the boundary instruction.
196         --RemainingCount;
197       }
198
199       // The next region starts above the previous region. Look backward in the
200       // instruction stream until we find the nearest boundary.
201       MachineBasicBlock::iterator I = RegionEnd;
202       for(;I != MBB->begin(); --I, --RemainingCount) {
203         if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
204           break;
205       }
206       // Notify the scheduler of the region, even if we may skip scheduling
207       // it. Perhaps it still needs to be bundled.
208       Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
209
210       // Skip empty scheduling regions (0 or 1 schedulable instructions).
211       if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
212         // Close the current region. Bundle the terminator if needed.
213         // This invalidates 'RegionEnd' and 'I'.
214         Scheduler->exitRegion();
215         continue;
216       }
217       DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
218             << ":BB#" << MBB->getNumber() << "\n  From: " << *I << "    To: ";
219             if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
220             else dbgs() << "End";
221             dbgs() << " Remaining: " << RemainingCount << "\n");
222
223       // Schedule a region: possibly reorder instructions.
224       // This invalidates 'RegionEnd' and 'I'.
225       Scheduler->schedule();
226
227       // Close the current region.
228       Scheduler->exitRegion();
229
230       // Scheduling has invalidated the current iterator 'I'. Ask the
231       // scheduler for the top of it's scheduled region.
232       RegionEnd = Scheduler->begin();
233     }
234     assert(RemainingCount == 0 && "Instruction count mismatch!");
235     Scheduler->finishBlock();
236   }
237   Scheduler->finalizeSchedule();
238   DEBUG(LIS->print(dbgs()));
239   return true;
240 }
241
242 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
243   // unimplemented
244 }
245
246 //===----------------------------------------------------------------------===//
247 // MachineSchedStrategy - Interface to a machine scheduling algorithm.
248 //===----------------------------------------------------------------------===//
249
250 namespace {
251 class ScheduleDAGMI;
252
253 /// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
254 /// scheduling algorithm.
255 ///
256 /// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
257 /// in ScheduleDAGInstrs.h
258 class MachineSchedStrategy {
259 public:
260   virtual ~MachineSchedStrategy() {}
261
262   /// Initialize the strategy after building the DAG for a new region.
263   virtual void initialize(ScheduleDAGMI *DAG) = 0;
264
265   /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
266   /// schedule the node at the top of the unscheduled region. Otherwise it will
267   /// be scheduled at the bottom.
268   virtual SUnit *pickNode(bool &IsTopNode) = 0;
269
270   /// When all predecessor dependencies have been resolved, free this node for
271   /// top-down scheduling.
272   virtual void releaseTopNode(SUnit *SU) = 0;
273   /// When all successor dependencies have been resolved, free this node for
274   /// bottom-up scheduling.
275   virtual void releaseBottomNode(SUnit *SU) = 0;
276 };
277 } // namespace
278
279 //===----------------------------------------------------------------------===//
280 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
281 // preservation.
282 //===----------------------------------------------------------------------===//
283
284 namespace {
285 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
286 /// machine instructions while updating LiveIntervals.
287 class ScheduleDAGMI : public ScheduleDAGInstrs {
288   AliasAnalysis *AA;
289   RegisterClassInfo *RegClassInfo;
290   MachineSchedStrategy *SchedImpl;
291
292   // Register pressure in this region computed by buildSchedGraph.
293   IntervalPressure RegPressure;
294   RegPressureTracker RPTracker;
295
296   /// The top of the unscheduled zone.
297   MachineBasicBlock::iterator CurrentTop;
298
299   /// The bottom of the unscheduled zone.
300   MachineBasicBlock::iterator CurrentBottom;
301
302   /// The number of instructions scheduled so far. Used to cut off the
303   /// scheduler at the point determined by misched-cutoff.
304   unsigned NumInstrsScheduled;
305 public:
306   ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
307     ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
308     AA(C->AA), RegClassInfo(&C->RegClassInfo), SchedImpl(S),
309     RPTracker(RegPressure), CurrentTop(), CurrentBottom(),
310     NumInstrsScheduled(0) {}
311
312   ~ScheduleDAGMI() {
313     delete SchedImpl;
314   }
315
316   MachineBasicBlock::iterator top() const { return CurrentTop; }
317   MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
318
319   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
320   /// region. This covers all instructions in a block, while schedule() may only
321   /// cover a subset.
322   void enterRegion(MachineBasicBlock *bb,
323                    MachineBasicBlock::iterator begin,
324                    MachineBasicBlock::iterator end,
325                    unsigned endcount);
326
327   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
328   /// reorderable instructions.
329   void schedule();
330
331 protected:
332   void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
333   bool checkSchedLimit();
334
335   void releaseSucc(SUnit *SU, SDep *SuccEdge);
336   void releaseSuccessors(SUnit *SU);
337   void releasePred(SUnit *SU, SDep *PredEdge);
338   void releasePredecessors(SUnit *SU);
339 };
340 } // namespace
341
342 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
343 /// NumPredsLeft reaches zero, release the successor node.
344 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
345   SUnit *SuccSU = SuccEdge->getSUnit();
346
347 #ifndef NDEBUG
348   if (SuccSU->NumPredsLeft == 0) {
349     dbgs() << "*** Scheduling failed! ***\n";
350     SuccSU->dump(this);
351     dbgs() << " has been released too many times!\n";
352     llvm_unreachable(0);
353   }
354 #endif
355   --SuccSU->NumPredsLeft;
356   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
357     SchedImpl->releaseTopNode(SuccSU);
358 }
359
360 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
361 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
362   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
363        I != E; ++I) {
364     releaseSucc(SU, &*I);
365   }
366 }
367
368 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
369 /// NumSuccsLeft reaches zero, release the predecessor node.
370 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
371   SUnit *PredSU = PredEdge->getSUnit();
372
373 #ifndef NDEBUG
374   if (PredSU->NumSuccsLeft == 0) {
375     dbgs() << "*** Scheduling failed! ***\n";
376     PredSU->dump(this);
377     dbgs() << " has been released too many times!\n";
378     llvm_unreachable(0);
379   }
380 #endif
381   --PredSU->NumSuccsLeft;
382   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
383     SchedImpl->releaseBottomNode(PredSU);
384 }
385
386 /// releasePredecessors - Call releasePred on each of SU's predecessors.
387 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
388   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
389        I != E; ++I) {
390     releasePred(SU, &*I);
391   }
392 }
393
394 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
395                                     MachineBasicBlock::iterator InsertPos) {
396   // Fix RegionBegin if the first instruction moves down.
397   if (&*RegionBegin == MI)
398     RegionBegin = llvm::next(RegionBegin);
399   BB->splice(InsertPos, BB, MI);
400   LIS->handleMove(MI);
401   // Fix RegionBegin if another instruction moves above the first instruction.
402   if (RegionBegin == InsertPos)
403     RegionBegin = MI;
404 }
405
406 bool ScheduleDAGMI::checkSchedLimit() {
407 #ifndef NDEBUG
408   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
409     CurrentTop = CurrentBottom;
410     return false;
411   }
412   ++NumInstrsScheduled;
413 #endif
414   return true;
415 }
416
417 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
418 /// crossing a scheduling boundary. [begin, end) includes all instructions in
419 /// the region, including the boundary itself and single-instruction regions
420 /// that don't get scheduled.
421 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
422                                 MachineBasicBlock::iterator begin,
423                                 MachineBasicBlock::iterator end,
424                                 unsigned endcount)
425 {
426   ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
427   // Setup the register pressure tracker to begin tracking at the end of this
428   // region.
429   RPTracker.init(&MF, RegClassInfo, LIS, BB, end);
430 }
431
432 /// schedule - Called back from MachineScheduler::runOnMachineFunction
433 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
434 /// only includes instructions that have DAG nodes, not scheduling boundaries.
435 void ScheduleDAGMI::schedule() {
436   while(RPTracker.getPos() != RegionEnd) {
437     bool Moved = RPTracker.recede();
438     assert(Moved && "Regpressure tracker cannot find RegionEnd"); (void)Moved;
439   }
440
441   // Build the DAG.
442   buildSchedGraph(AA, &RPTracker);
443
444   DEBUG(dbgs() << "********** MI Scheduling **********\n");
445   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
446           SUnits[su].dumpAll(this));
447
448   if (ViewMISchedDAGs) viewGraph();
449
450   SchedImpl->initialize(this);
451
452   // Release edges from the special Entry node or to the special Exit node.
453   releaseSuccessors(&EntrySU);
454   releasePredecessors(&ExitSU);
455
456   // Release all DAG roots for scheduling.
457   for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
458        I != E; ++I) {
459     // A SUnit is ready to top schedule if it has no predecessors.
460     if (I->Preds.empty())
461       SchedImpl->releaseTopNode(&(*I));
462     // A SUnit is ready to bottom schedule if it has no successors.
463     if (I->Succs.empty())
464       SchedImpl->releaseBottomNode(&(*I));
465   }
466
467   CurrentTop = RegionBegin;
468   CurrentBottom = RegionEnd;
469   bool IsTopNode = false;
470   while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
471     DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
472           << " Scheduling Instruction:\n"; SU->dump(this));
473     if (!checkSchedLimit())
474       break;
475
476     // Move the instruction to its new location in the instruction stream.
477     MachineInstr *MI = SU->getInstr();
478
479     if (IsTopNode) {
480       assert(SU->isTopReady() && "node still has unscheduled dependencies");
481       if (&*CurrentTop == MI)
482         ++CurrentTop;
483       else
484         moveInstruction(MI, CurrentTop);
485       // Release dependent instructions for scheduling.
486       releaseSuccessors(SU);
487     }
488     else {
489       assert(SU->isBottomReady() && "node still has unscheduled dependencies");
490       if (&*llvm::prior(CurrentBottom) == MI)
491         --CurrentBottom;
492       else {
493         if (&*CurrentTop == MI)
494           CurrentTop = llvm::next(CurrentTop);
495         moveInstruction(MI, CurrentBottom);
496         CurrentBottom = MI;
497       }
498       // Release dependent instructions for scheduling.
499       releasePredecessors(SU);
500     }
501     SU->isScheduled = true;
502   }
503   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
504 }
505
506 //===----------------------------------------------------------------------===//
507 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
508 //===----------------------------------------------------------------------===//
509
510 namespace {
511 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
512 /// the schedule.
513 class ConvergingScheduler : public MachineSchedStrategy {
514   ScheduleDAGMI *DAG;
515
516   unsigned NumTopReady;
517   unsigned NumBottomReady;
518
519 public:
520   virtual void initialize(ScheduleDAGMI *dag) {
521     DAG = dag;
522
523     assert((!ForceTopDown || !ForceBottomUp) &&
524            "-misched-topdown incompatible with -misched-bottomup");
525   }
526
527   virtual SUnit *pickNode(bool &IsTopNode) {
528     if (DAG->top() == DAG->bottom())
529       return NULL;
530
531     // As an initial placeholder heuristic, schedule in the direction that has
532     // the fewest choices.
533     SUnit *SU;
534     if (ForceTopDown || (!ForceBottomUp && NumTopReady <= NumBottomReady)) {
535       SU = DAG->getSUnit(DAG->top());
536       IsTopNode = true;
537     }
538     else {
539       SU = DAG->getSUnit(llvm::prior(DAG->bottom()));
540       IsTopNode = false;
541     }
542     if (SU->isTopReady()) {
543       assert(NumTopReady > 0 && "bad ready count");
544       --NumTopReady;
545     }
546     if (SU->isBottomReady()) {
547       assert(NumBottomReady > 0 && "bad ready count");
548       --NumBottomReady;
549     }
550     return SU;
551   }
552
553   virtual void releaseTopNode(SUnit *SU) {
554     ++NumTopReady;
555   }
556   virtual void releaseBottomNode(SUnit *SU) {
557     ++NumBottomReady;
558   }
559 };
560 } // namespace
561
562 /// Create the standard converging machine scheduler. This will be used as the
563 /// default scheduler if the target does not set a default.
564 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
565   assert((!ForceTopDown || !ForceBottomUp) &&
566          "-misched-topdown incompatible with -misched-bottomup");
567   return new ScheduleDAGMI(C, new ConvergingScheduler());
568 }
569 static MachineSchedRegistry
570 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
571                         createConvergingSched);
572
573 //===----------------------------------------------------------------------===//
574 // Machine Instruction Shuffler for Correctness Testing
575 //===----------------------------------------------------------------------===//
576
577 #ifndef NDEBUG
578 namespace {
579 /// Apply a less-than relation on the node order, which corresponds to the
580 /// instruction order prior to scheduling. IsReverse implements greater-than.
581 template<bool IsReverse>
582 struct SUnitOrder {
583   bool operator()(SUnit *A, SUnit *B) const {
584     if (IsReverse)
585       return A->NodeNum > B->NodeNum;
586     else
587       return A->NodeNum < B->NodeNum;
588   }
589 };
590
591 /// Reorder instructions as much as possible.
592 class InstructionShuffler : public MachineSchedStrategy {
593   bool IsAlternating;
594   bool IsTopDown;
595
596   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
597   // gives nodes with a higher number higher priority causing the latest
598   // instructions to be scheduled first.
599   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
600     TopQ;
601   // When scheduling bottom-up, use greater-than as the queue priority.
602   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
603     BottomQ;
604 public:
605   InstructionShuffler(bool alternate, bool topdown)
606     : IsAlternating(alternate), IsTopDown(topdown) {}
607
608   virtual void initialize(ScheduleDAGMI *) {
609     TopQ.clear();
610     BottomQ.clear();
611   }
612
613   /// Implement MachineSchedStrategy interface.
614   /// -----------------------------------------
615
616   virtual SUnit *pickNode(bool &IsTopNode) {
617     SUnit *SU;
618     if (IsTopDown) {
619       do {
620         if (TopQ.empty()) return NULL;
621         SU = TopQ.top();
622         TopQ.pop();
623       } while (SU->isScheduled);
624       IsTopNode = true;
625     }
626     else {
627       do {
628         if (BottomQ.empty()) return NULL;
629         SU = BottomQ.top();
630         BottomQ.pop();
631       } while (SU->isScheduled);
632       IsTopNode = false;
633     }
634     if (IsAlternating)
635       IsTopDown = !IsTopDown;
636     return SU;
637   }
638
639   virtual void releaseTopNode(SUnit *SU) {
640     TopQ.push(SU);
641   }
642   virtual void releaseBottomNode(SUnit *SU) {
643     BottomQ.push(SU);
644   }
645 };
646 } // namespace
647
648 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
649   bool Alternate = !ForceTopDown && !ForceBottomUp;
650   bool TopDown = !ForceBottomUp;
651   assert((TopDown || !ForceTopDown) &&
652          "-misched-topdown incompatible with -misched-bottomup");
653   return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
654 }
655 static MachineSchedRegistry ShufflerRegistry(
656   "shuffle", "Shuffle machine instructions alternating directions",
657   createInstructionShuffler);
658 #endif // !NDEBUG