Change TargetLowering::getRepRegClassFor to take an MVT, instead of
[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 "llvm/CodeGen/MachineScheduler.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/PriorityQueue.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegisterClassInfo.h"
24 #include "llvm/CodeGen/ScheduleDFS.h"
25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <queue>
31
32 using namespace llvm;
33
34 namespace llvm {
35 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36                            cl::desc("Force top-down list scheduling"));
37 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38                             cl::desc("Force bottom-up list scheduling"));
39 }
40
41 #ifndef NDEBUG
42 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43   cl::desc("Pop up a window to show MISched dags after they are processed"));
44
45 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
47 #else
48 static bool ViewMISchedDAGs = false;
49 #endif // NDEBUG
50
51 // Threshold to very roughly model an out-of-order processor's instruction
52 // buffers. If the actual value of this threshold matters much in practice, then
53 // it can be specified by the machine model. For now, it's an experimental
54 // tuning knob to determine when and if it matters.
55 static cl::opt<unsigned> ILPWindow("ilp-window", cl::Hidden,
56   cl::desc("Allow expected latency to exceed the critical path by N cycles "
57            "before attempting to balance ILP"),
58   cl::init(10U));
59
60 // Experimental heuristics
61 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
62   cl::desc("Enable load clustering."), cl::init(true));
63
64 // Experimental heuristics
65 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
66   cl::desc("Enable scheduling for macro fusion."), cl::init(true));
67
68 //===----------------------------------------------------------------------===//
69 // Machine Instruction Scheduling Pass and Registry
70 //===----------------------------------------------------------------------===//
71
72 MachineSchedContext::MachineSchedContext():
73     MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
74   RegClassInfo = new RegisterClassInfo();
75 }
76
77 MachineSchedContext::~MachineSchedContext() {
78   delete RegClassInfo;
79 }
80
81 namespace {
82 /// MachineScheduler runs after coalescing and before register allocation.
83 class MachineScheduler : public MachineSchedContext,
84                          public MachineFunctionPass {
85 public:
86   MachineScheduler();
87
88   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
89
90   virtual void releaseMemory() {}
91
92   virtual bool runOnMachineFunction(MachineFunction&);
93
94   virtual void print(raw_ostream &O, const Module* = 0) const;
95
96   static char ID; // Class identification, replacement for typeinfo
97 };
98 } // namespace
99
100 char MachineScheduler::ID = 0;
101
102 char &llvm::MachineSchedulerID = MachineScheduler::ID;
103
104 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
105                       "Machine Instruction Scheduler", false, false)
106 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
107 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
108 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
109 INITIALIZE_PASS_END(MachineScheduler, "misched",
110                     "Machine Instruction Scheduler", false, false)
111
112 MachineScheduler::MachineScheduler()
113 : MachineFunctionPass(ID) {
114   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
115 }
116
117 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
118   AU.setPreservesCFG();
119   AU.addRequiredID(MachineDominatorsID);
120   AU.addRequired<MachineLoopInfo>();
121   AU.addRequired<AliasAnalysis>();
122   AU.addRequired<TargetPassConfig>();
123   AU.addRequired<SlotIndexes>();
124   AU.addPreserved<SlotIndexes>();
125   AU.addRequired<LiveIntervals>();
126   AU.addPreserved<LiveIntervals>();
127   MachineFunctionPass::getAnalysisUsage(AU);
128 }
129
130 MachinePassRegistry MachineSchedRegistry::Registry;
131
132 /// A dummy default scheduler factory indicates whether the scheduler
133 /// is overridden on the command line.
134 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
135   return 0;
136 }
137
138 /// MachineSchedOpt allows command line selection of the scheduler.
139 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
140                RegisterPassParser<MachineSchedRegistry> >
141 MachineSchedOpt("misched",
142                 cl::init(&useDefaultMachineSched), cl::Hidden,
143                 cl::desc("Machine instruction scheduler to use"));
144
145 static MachineSchedRegistry
146 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
147                      useDefaultMachineSched);
148
149 /// Forward declare the standard machine scheduler. This will be used as the
150 /// default scheduler if the target does not set a default.
151 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
152
153
154 /// Decrement this iterator until reaching the top or a non-debug instr.
155 static MachineBasicBlock::iterator
156 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
157   assert(I != Beg && "reached the top of the region, cannot decrement");
158   while (--I != Beg) {
159     if (!I->isDebugValue())
160       break;
161   }
162   return I;
163 }
164
165 /// If this iterator is a debug value, increment until reaching the End or a
166 /// non-debug instruction.
167 static MachineBasicBlock::iterator
168 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
169   for(; I != End; ++I) {
170     if (!I->isDebugValue())
171       break;
172   }
173   return I;
174 }
175
176 /// Top-level MachineScheduler pass driver.
177 ///
178 /// Visit blocks in function order. Divide each block into scheduling regions
179 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
180 /// consistent with the DAG builder, which traverses the interior of the
181 /// scheduling regions bottom-up.
182 ///
183 /// This design avoids exposing scheduling boundaries to the DAG builder,
184 /// simplifying the DAG builder's support for "special" target instructions.
185 /// At the same time the design allows target schedulers to operate across
186 /// scheduling boundaries, for example to bundle the boudary instructions
187 /// without reordering them. This creates complexity, because the target
188 /// scheduler must update the RegionBegin and RegionEnd positions cached by
189 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
190 /// design would be to split blocks at scheduling boundaries, but LLVM has a
191 /// general bias against block splitting purely for implementation simplicity.
192 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
193   DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
194
195   // Initialize the context of the pass.
196   MF = &mf;
197   MLI = &getAnalysis<MachineLoopInfo>();
198   MDT = &getAnalysis<MachineDominatorTree>();
199   PassConfig = &getAnalysis<TargetPassConfig>();
200   AA = &getAnalysis<AliasAnalysis>();
201
202   LIS = &getAnalysis<LiveIntervals>();
203   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
204
205   RegClassInfo->runOnMachineFunction(*MF);
206
207   // Select the scheduler, or set the default.
208   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
209   if (Ctor == useDefaultMachineSched) {
210     // Get the default scheduler set by the target.
211     Ctor = MachineSchedRegistry::getDefault();
212     if (!Ctor) {
213       Ctor = createConvergingSched;
214       MachineSchedRegistry::setDefault(Ctor);
215     }
216   }
217   // Instantiate the selected scheduler.
218   OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
219
220   // Visit all machine basic blocks.
221   //
222   // TODO: Visit blocks in global postorder or postorder within the bottom-up
223   // loop tree. Then we can optionally compute global RegPressure.
224   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
225        MBB != MBBEnd; ++MBB) {
226
227     Scheduler->startBlock(MBB);
228
229     // Break the block into scheduling regions [I, RegionEnd), and schedule each
230     // region as soon as it is discovered. RegionEnd points the scheduling
231     // boundary at the bottom of the region. The DAG does not include RegionEnd,
232     // but the region does (i.e. the next RegionEnd is above the previous
233     // RegionBegin). If the current block has no terminator then RegionEnd ==
234     // MBB->end() for the bottom region.
235     //
236     // The Scheduler may insert instructions during either schedule() or
237     // exitRegion(), even for empty regions. So the local iterators 'I' and
238     // 'RegionEnd' are invalid across these calls.
239     unsigned RemainingInstrs = MBB->size();
240     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
241         RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
242
243       // Avoid decrementing RegionEnd for blocks with no terminator.
244       if (RegionEnd != MBB->end()
245           || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
246         --RegionEnd;
247         // Count the boundary instruction.
248         --RemainingInstrs;
249       }
250
251       // The next region starts above the previous region. Look backward in the
252       // instruction stream until we find the nearest boundary.
253       MachineBasicBlock::iterator I = RegionEnd;
254       for(;I != MBB->begin(); --I, --RemainingInstrs) {
255         if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
256           break;
257       }
258       // Notify the scheduler of the region, even if we may skip scheduling
259       // it. Perhaps it still needs to be bundled.
260       Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
261
262       // Skip empty scheduling regions (0 or 1 schedulable instructions).
263       if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
264         // Close the current region. Bundle the terminator if needed.
265         // This invalidates 'RegionEnd' and 'I'.
266         Scheduler->exitRegion();
267         continue;
268       }
269       DEBUG(dbgs() << "********** MI Scheduling **********\n");
270       DEBUG(dbgs() << MF->getName()
271             << ":BB#" << MBB->getNumber() << "\n  From: " << *I << "    To: ";
272             if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
273             else dbgs() << "End";
274             dbgs() << " Remaining: " << RemainingInstrs << "\n");
275
276       // Schedule a region: possibly reorder instructions.
277       // This invalidates 'RegionEnd' and 'I'.
278       Scheduler->schedule();
279
280       // Close the current region.
281       Scheduler->exitRegion();
282
283       // Scheduling has invalidated the current iterator 'I'. Ask the
284       // scheduler for the top of it's scheduled region.
285       RegionEnd = Scheduler->begin();
286     }
287     assert(RemainingInstrs == 0 && "Instruction count mismatch!");
288     Scheduler->finishBlock();
289   }
290   Scheduler->finalizeSchedule();
291   DEBUG(LIS->print(dbgs()));
292   return true;
293 }
294
295 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
296   // unimplemented
297 }
298
299 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
300 void ReadyQueue::dump() {
301   dbgs() << Name << ": ";
302   for (unsigned i = 0, e = Queue.size(); i < e; ++i)
303     dbgs() << Queue[i]->NodeNum << " ";
304   dbgs() << "\n";
305 }
306 #endif
307
308 //===----------------------------------------------------------------------===//
309 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
310 // preservation.
311 //===----------------------------------------------------------------------===//
312
313 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
314   if (SuccSU != &ExitSU) {
315     // Do not use WillCreateCycle, it assumes SD scheduling.
316     // If Pred is reachable from Succ, then the edge creates a cycle.
317     if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
318       return false;
319     Topo.AddPred(SuccSU, PredDep.getSUnit());
320   }
321   SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
322   // Return true regardless of whether a new edge needed to be inserted.
323   return true;
324 }
325
326 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
327 /// NumPredsLeft reaches zero, release the successor node.
328 ///
329 /// FIXME: Adjust SuccSU height based on MinLatency.
330 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
331   SUnit *SuccSU = SuccEdge->getSUnit();
332
333   if (SuccEdge->isWeak()) {
334     --SuccSU->WeakPredsLeft;
335     if (SuccEdge->isCluster())
336       NextClusterSucc = SuccSU;
337     return;
338   }
339 #ifndef NDEBUG
340   if (SuccSU->NumPredsLeft == 0) {
341     dbgs() << "*** Scheduling failed! ***\n";
342     SuccSU->dump(this);
343     dbgs() << " has been released too many times!\n";
344     llvm_unreachable(0);
345   }
346 #endif
347   --SuccSU->NumPredsLeft;
348   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
349     SchedImpl->releaseTopNode(SuccSU);
350 }
351
352 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
353 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
354   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
355        I != E; ++I) {
356     releaseSucc(SU, &*I);
357   }
358 }
359
360 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
361 /// NumSuccsLeft reaches zero, release the predecessor node.
362 ///
363 /// FIXME: Adjust PredSU height based on MinLatency.
364 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
365   SUnit *PredSU = PredEdge->getSUnit();
366
367   if (PredEdge->isWeak()) {
368     --PredSU->WeakSuccsLeft;
369     if (PredEdge->isCluster())
370       NextClusterPred = PredSU;
371     return;
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   // Advance RegionBegin if the first instruction moves down.
397   if (&*RegionBegin == MI)
398     ++RegionBegin;
399
400   // Update the instruction stream.
401   BB->splice(InsertPos, BB, MI);
402
403   // Update LiveIntervals
404   LIS->handleMove(MI, /*UpdateFlags=*/true);
405
406   // Recede RegionBegin if an instruction moves above the first.
407   if (RegionBegin == InsertPos)
408     RegionBegin = MI;
409 }
410
411 bool ScheduleDAGMI::checkSchedLimit() {
412 #ifndef NDEBUG
413   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
414     CurrentTop = CurrentBottom;
415     return false;
416   }
417   ++NumInstrsScheduled;
418 #endif
419   return true;
420 }
421
422 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
423 /// crossing a scheduling boundary. [begin, end) includes all instructions in
424 /// the region, including the boundary itself and single-instruction regions
425 /// that don't get scheduled.
426 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
427                                 MachineBasicBlock::iterator begin,
428                                 MachineBasicBlock::iterator end,
429                                 unsigned endcount)
430 {
431   ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
432
433   // For convenience remember the end of the liveness region.
434   LiveRegionEnd =
435     (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
436 }
437
438 // Setup the register pressure trackers for the top scheduled top and bottom
439 // scheduled regions.
440 void ScheduleDAGMI::initRegPressure() {
441   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
442   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
443
444   // Close the RPTracker to finalize live ins.
445   RPTracker.closeRegion();
446
447   DEBUG(RPTracker.getPressure().dump(TRI));
448
449   // Initialize the live ins and live outs.
450   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
451   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
452
453   // Close one end of the tracker so we can call
454   // getMaxUpward/DownwardPressureDelta before advancing across any
455   // instructions. This converts currently live regs into live ins/outs.
456   TopRPTracker.closeTop();
457   BotRPTracker.closeBottom();
458
459   // Account for liveness generated by the region boundary.
460   if (LiveRegionEnd != RegionEnd)
461     BotRPTracker.recede();
462
463   assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
464
465   // Cache the list of excess pressure sets in this region. This will also track
466   // the max pressure in the scheduled code for these sets.
467   RegionCriticalPSets.clear();
468   std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
469   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
470     unsigned Limit = TRI->getRegPressureSetLimit(i);
471     DEBUG(dbgs() << TRI->getRegPressureSetName(i)
472           << "Limit " << Limit
473           << " Actual " << RegionPressure[i] << "\n");
474     if (RegionPressure[i] > Limit)
475       RegionCriticalPSets.push_back(PressureElement(i, 0));
476   }
477   DEBUG(dbgs() << "Excess PSets: ";
478         for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
479           dbgs() << TRI->getRegPressureSetName(
480             RegionCriticalPSets[i].PSetID) << " ";
481         dbgs() << "\n");
482 }
483
484 // FIXME: When the pressure tracker deals in pressure differences then we won't
485 // iterate over all RegionCriticalPSets[i].
486 void ScheduleDAGMI::
487 updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
488   for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
489     unsigned ID = RegionCriticalPSets[i].PSetID;
490     int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
491     if ((int)NewMaxPressure[ID] > MaxUnits)
492       MaxUnits = NewMaxPressure[ID];
493   }
494 }
495
496 /// schedule - Called back from MachineScheduler::runOnMachineFunction
497 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
498 /// only includes instructions that have DAG nodes, not scheduling boundaries.
499 ///
500 /// This is a skeletal driver, with all the functionality pushed into helpers,
501 /// so that it can be easilly extended by experimental schedulers. Generally,
502 /// implementing MachineSchedStrategy should be sufficient to implement a new
503 /// scheduling algorithm. However, if a scheduler further subclasses
504 /// ScheduleDAGMI then it will want to override this virtual method in order to
505 /// update any specialized state.
506 void ScheduleDAGMI::schedule() {
507   buildDAGWithRegPressure();
508
509   Topo.InitDAGTopologicalSorting();
510
511   postprocessDAG();
512
513   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
514           SUnits[su].dumpAll(this));
515
516   if (ViewMISchedDAGs) viewGraph();
517
518   initQueues();
519
520   bool IsTopNode = false;
521   while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
522     assert(!SU->isScheduled && "Node already scheduled");
523     if (!checkSchedLimit())
524       break;
525
526     scheduleMI(SU, IsTopNode);
527
528     updateQueues(SU, IsTopNode);
529   }
530   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
531
532   placeDebugValues();
533
534   DEBUG({
535       unsigned BBNum = begin()->getParent()->getNumber();
536       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
537       dumpSchedule();
538       dbgs() << '\n';
539     });
540 }
541
542 /// Build the DAG and setup three register pressure trackers.
543 void ScheduleDAGMI::buildDAGWithRegPressure() {
544   // Initialize the register pressure tracker used by buildSchedGraph.
545   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
546
547   // Account for liveness generate by the region boundary.
548   if (LiveRegionEnd != RegionEnd)
549     RPTracker.recede();
550
551   // Build the DAG, and compute current register pressure.
552   buildSchedGraph(AA, &RPTracker);
553   if (ViewMISchedDAGs) viewGraph();
554
555   // Initialize top/bottom trackers after computing region pressure.
556   initRegPressure();
557 }
558
559 /// Apply each ScheduleDAGMutation step in order.
560 void ScheduleDAGMI::postprocessDAG() {
561   for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
562     Mutations[i]->apply(this);
563   }
564 }
565
566 // Release all DAG roots for scheduling.
567 //
568 // Nodes with unreleased weak edges can still be roots.
569 void ScheduleDAGMI::releaseRoots() {
570   SmallVector<SUnit*, 16> BotRoots;
571
572   for (std::vector<SUnit>::iterator
573          I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
574     SUnit *SU = &(*I);
575     // A SUnit is ready to top schedule if it has no predecessors.
576     if (!I->NumPredsLeft && SU != &EntrySU)
577       SchedImpl->releaseTopNode(SU);
578     // A SUnit is ready to bottom schedule if it has no successors.
579     if (!I->NumSuccsLeft && SU != &ExitSU)
580       BotRoots.push_back(SU);
581   }
582   // Release bottom roots in reverse order so the higher priority nodes appear
583   // first. This is more natural and slightly more efficient.
584   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
585          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
586     SchedImpl->releaseBottomNode(*I);
587 }
588
589 /// Identify DAG roots and setup scheduler queues.
590 void ScheduleDAGMI::initQueues() {
591   NextClusterSucc = NULL;
592   NextClusterPred = NULL;
593
594   // Initialize the strategy before modifying the DAG.
595   SchedImpl->initialize(this);
596
597   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
598   releaseRoots();
599
600   releaseSuccessors(&EntrySU);
601   releasePredecessors(&ExitSU);
602
603   SchedImpl->registerRoots();
604
605   // Advance past initial DebugValues.
606   assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
607   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
608   TopRPTracker.setPos(CurrentTop);
609
610   CurrentBottom = RegionEnd;
611 }
612
613 /// Move an instruction and update register pressure.
614 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
615   // Move the instruction to its new location in the instruction stream.
616   MachineInstr *MI = SU->getInstr();
617
618   if (IsTopNode) {
619     assert(SU->isTopReady() && "node still has unscheduled dependencies");
620     if (&*CurrentTop == MI)
621       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
622     else {
623       moveInstruction(MI, CurrentTop);
624       TopRPTracker.setPos(MI);
625     }
626
627     // Update top scheduled pressure.
628     TopRPTracker.advance();
629     assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
630     updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
631   }
632   else {
633     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
634     MachineBasicBlock::iterator priorII =
635       priorNonDebug(CurrentBottom, CurrentTop);
636     if (&*priorII == MI)
637       CurrentBottom = priorII;
638     else {
639       if (&*CurrentTop == MI) {
640         CurrentTop = nextIfDebug(++CurrentTop, priorII);
641         TopRPTracker.setPos(CurrentTop);
642       }
643       moveInstruction(MI, CurrentBottom);
644       CurrentBottom = MI;
645     }
646     // Update bottom scheduled pressure.
647     BotRPTracker.recede();
648     assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
649     updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
650   }
651 }
652
653 /// Update scheduler queues after scheduling an instruction.
654 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
655   // Release dependent instructions for scheduling.
656   if (IsTopNode)
657     releaseSuccessors(SU);
658   else
659     releasePredecessors(SU);
660
661   SU->isScheduled = true;
662
663   // Notify the scheduling strategy after updating the DAG.
664   SchedImpl->schedNode(SU, IsTopNode);
665 }
666
667 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
668 void ScheduleDAGMI::placeDebugValues() {
669   // If first instruction was a DBG_VALUE then put it back.
670   if (FirstDbgValue) {
671     BB->splice(RegionBegin, BB, FirstDbgValue);
672     RegionBegin = FirstDbgValue;
673   }
674
675   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
676          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
677     std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
678     MachineInstr *DbgValue = P.first;
679     MachineBasicBlock::iterator OrigPrevMI = P.second;
680     if (&*RegionBegin == DbgValue)
681       ++RegionBegin;
682     BB->splice(++OrigPrevMI, BB, DbgValue);
683     if (OrigPrevMI == llvm::prior(RegionEnd))
684       RegionEnd = DbgValue;
685   }
686   DbgValues.clear();
687   FirstDbgValue = NULL;
688 }
689
690 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
691 void ScheduleDAGMI::dumpSchedule() const {
692   for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
693     if (SUnit *SU = getSUnit(&(*MI)))
694       SU->dump(this);
695     else
696       dbgs() << "Missing SUnit\n";
697   }
698 }
699 #endif
700
701 //===----------------------------------------------------------------------===//
702 // LoadClusterMutation - DAG post-processing to cluster loads.
703 //===----------------------------------------------------------------------===//
704
705 namespace {
706 /// \brief Post-process the DAG to create cluster edges between neighboring
707 /// loads.
708 class LoadClusterMutation : public ScheduleDAGMutation {
709   struct LoadInfo {
710     SUnit *SU;
711     unsigned BaseReg;
712     unsigned Offset;
713     LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
714       : SU(su), BaseReg(reg), Offset(ofs) {}
715   };
716   static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
717                            const LoadClusterMutation::LoadInfo &RHS);
718
719   const TargetInstrInfo *TII;
720   const TargetRegisterInfo *TRI;
721 public:
722   LoadClusterMutation(const TargetInstrInfo *tii,
723                       const TargetRegisterInfo *tri)
724     : TII(tii), TRI(tri) {}
725
726   virtual void apply(ScheduleDAGMI *DAG);
727 protected:
728   void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
729 };
730 } // anonymous
731
732 bool LoadClusterMutation::LoadInfoLess(
733   const LoadClusterMutation::LoadInfo &LHS,
734   const LoadClusterMutation::LoadInfo &RHS) {
735   if (LHS.BaseReg != RHS.BaseReg)
736     return LHS.BaseReg < RHS.BaseReg;
737   return LHS.Offset < RHS.Offset;
738 }
739
740 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
741                                                   ScheduleDAGMI *DAG) {
742   SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
743   for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
744     SUnit *SU = Loads[Idx];
745     unsigned BaseReg;
746     unsigned Offset;
747     if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
748       LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
749   }
750   if (LoadRecords.size() < 2)
751     return;
752   std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
753   unsigned ClusterLength = 1;
754   for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
755     if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
756       ClusterLength = 1;
757       continue;
758     }
759
760     SUnit *SUa = LoadRecords[Idx].SU;
761     SUnit *SUb = LoadRecords[Idx+1].SU;
762     if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
763         && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
764
765       DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
766             << SUb->NodeNum << ")\n");
767       // Copy successor edges from SUa to SUb. Interleaving computation
768       // dependent on SUa can prevent load combining due to register reuse.
769       // Predecessor edges do not need to be copied from SUb to SUa since nearby
770       // loads should have effectively the same inputs.
771       for (SUnit::const_succ_iterator
772              SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
773         if (SI->getSUnit() == SUb)
774           continue;
775         DEBUG(dbgs() << "  Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
776         DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
777       }
778       ++ClusterLength;
779     }
780     else
781       ClusterLength = 1;
782   }
783 }
784
785 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
786 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
787   // Map DAG NodeNum to store chain ID.
788   DenseMap<unsigned, unsigned> StoreChainIDs;
789   // Map each store chain to a set of dependent loads.
790   SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
791   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
792     SUnit *SU = &DAG->SUnits[Idx];
793     if (!SU->getInstr()->mayLoad())
794       continue;
795     unsigned ChainPredID = DAG->SUnits.size();
796     for (SUnit::const_pred_iterator
797            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
798       if (PI->isCtrl()) {
799         ChainPredID = PI->getSUnit()->NodeNum;
800         break;
801       }
802     }
803     // Check if this chain-like pred has been seen
804     // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
805     unsigned NumChains = StoreChainDependents.size();
806     std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
807       StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
808     if (Result.second)
809       StoreChainDependents.resize(NumChains + 1);
810     StoreChainDependents[Result.first->second].push_back(SU);
811   }
812   // Iterate over the store chains.
813   for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
814     clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
815 }
816
817 //===----------------------------------------------------------------------===//
818 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
819 //===----------------------------------------------------------------------===//
820
821 namespace {
822 /// \brief Post-process the DAG to create cluster edges between instructions
823 /// that may be fused by the processor into a single operation.
824 class MacroFusion : public ScheduleDAGMutation {
825   const TargetInstrInfo *TII;
826 public:
827   MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
828
829   virtual void apply(ScheduleDAGMI *DAG);
830 };
831 } // anonymous
832
833 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
834 /// fused operations.
835 void MacroFusion::apply(ScheduleDAGMI *DAG) {
836   // For now, assume targets can only fuse with the branch.
837   MachineInstr *Branch = DAG->ExitSU.getInstr();
838   if (!Branch)
839     return;
840
841   for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
842     SUnit *SU = &DAG->SUnits[--Idx];
843     if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
844       continue;
845
846     // Create a single weak edge from SU to ExitSU. The only effect is to cause
847     // bottom-up scheduling to heavily prioritize the clustered SU.  There is no
848     // need to copy predecessor edges from ExitSU to SU, since top-down
849     // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
850     // of SU, we could create an artificial edge from the deepest root, but it
851     // hasn't been needed yet.
852     bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
853     (void)Success;
854     assert(Success && "No DAG nodes should be reachable from ExitSU");
855
856     DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
857     break;
858   }
859 }
860
861 //===----------------------------------------------------------------------===//
862 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
863 //===----------------------------------------------------------------------===//
864
865 namespace {
866 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
867 /// the schedule.
868 class ConvergingScheduler : public MachineSchedStrategy {
869 public:
870   /// Represent the type of SchedCandidate found within a single queue.
871   /// pickNodeBidirectional depends on these listed by decreasing priority.
872   enum CandReason {
873     NoCand, SingleExcess, SingleCritical, Cluster,
874     ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
875     TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
876     NodeOrder};
877
878 #ifndef NDEBUG
879   static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
880 #endif
881
882   /// Policy for scheduling the next instruction in the candidate's zone.
883   struct CandPolicy {
884     bool ReduceLatency;
885     unsigned ReduceResIdx;
886     unsigned DemandResIdx;
887
888     CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
889   };
890
891   /// Status of an instruction's critical resource consumption.
892   struct SchedResourceDelta {
893     // Count critical resources in the scheduled region required by SU.
894     unsigned CritResources;
895
896     // Count critical resources from another region consumed by SU.
897     unsigned DemandedResources;
898
899     SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
900
901     bool operator==(const SchedResourceDelta &RHS) const {
902       return CritResources == RHS.CritResources
903         && DemandedResources == RHS.DemandedResources;
904     }
905     bool operator!=(const SchedResourceDelta &RHS) const {
906       return !operator==(RHS);
907     }
908   };
909
910   /// Store the state used by ConvergingScheduler heuristics, required for the
911   /// lifetime of one invocation of pickNode().
912   struct SchedCandidate {
913     CandPolicy Policy;
914
915     // The best SUnit candidate.
916     SUnit *SU;
917
918     // The reason for this candidate.
919     CandReason Reason;
920
921     // Register pressure values for the best candidate.
922     RegPressureDelta RPDelta;
923
924     // Critical resource consumption of the best candidate.
925     SchedResourceDelta ResDelta;
926
927     SchedCandidate(const CandPolicy &policy)
928     : Policy(policy), SU(NULL), Reason(NoCand) {}
929
930     bool isValid() const { return SU; }
931
932     // Copy the status of another candidate without changing policy.
933     void setBest(SchedCandidate &Best) {
934       assert(Best.Reason != NoCand && "uninitialized Sched candidate");
935       SU = Best.SU;
936       Reason = Best.Reason;
937       RPDelta = Best.RPDelta;
938       ResDelta = Best.ResDelta;
939     }
940
941     void initResourceDelta(const ScheduleDAGMI *DAG,
942                            const TargetSchedModel *SchedModel);
943   };
944
945   /// Summarize the unscheduled region.
946   struct SchedRemainder {
947     // Critical path through the DAG in expected latency.
948     unsigned CriticalPath;
949
950     // Unscheduled resources
951     SmallVector<unsigned, 16> RemainingCounts;
952     // Critical resource for the unscheduled zone.
953     unsigned CritResIdx;
954     // Number of micro-ops left to schedule.
955     unsigned RemainingMicroOps;
956     // Is the unscheduled zone resource limited.
957     bool IsResourceLimited;
958
959     unsigned MaxRemainingCount;
960
961     void reset() {
962       CriticalPath = 0;
963       RemainingCounts.clear();
964       CritResIdx = 0;
965       RemainingMicroOps = 0;
966       IsResourceLimited = false;
967       MaxRemainingCount = 0;
968     }
969
970     SchedRemainder() { reset(); }
971
972     void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
973   };
974
975   /// Each Scheduling boundary is associated with ready queues. It tracks the
976   /// current cycle in the direction of movement, and maintains the state
977   /// of "hazards" and other interlocks at the current cycle.
978   struct SchedBoundary {
979     ScheduleDAGMI *DAG;
980     const TargetSchedModel *SchedModel;
981     SchedRemainder *Rem;
982
983     ReadyQueue Available;
984     ReadyQueue Pending;
985     bool CheckPending;
986
987     // For heuristics, keep a list of the nodes that immediately depend on the
988     // most recently scheduled node.
989     SmallPtrSet<const SUnit*, 8> NextSUs;
990
991     ScheduleHazardRecognizer *HazardRec;
992
993     unsigned CurrCycle;
994     unsigned IssueCount;
995
996     /// MinReadyCycle - Cycle of the soonest available instruction.
997     unsigned MinReadyCycle;
998
999     // The expected latency of the critical path in this scheduled zone.
1000     unsigned ExpectedLatency;
1001
1002     // Resources used in the scheduled zone beyond this boundary.
1003     SmallVector<unsigned, 16> ResourceCounts;
1004
1005     // Cache the critical resources ID in this scheduled zone.
1006     unsigned CritResIdx;
1007
1008     // Is the scheduled region resource limited vs. latency limited.
1009     bool IsResourceLimited;
1010
1011     unsigned ExpectedCount;
1012
1013     // Policy flag: attempt to find ILP until expected latency is covered.
1014     bool ShouldIncreaseILP;
1015
1016 #ifndef NDEBUG
1017     // Remember the greatest min operand latency.
1018     unsigned MaxMinLatency;
1019 #endif
1020
1021     void reset() {
1022       Available.clear();
1023       Pending.clear();
1024       CheckPending = false;
1025       NextSUs.clear();
1026       HazardRec = 0;
1027       CurrCycle = 0;
1028       IssueCount = 0;
1029       MinReadyCycle = UINT_MAX;
1030       ExpectedLatency = 0;
1031       ResourceCounts.resize(1);
1032       assert(!ResourceCounts[0] && "nonzero count for bad resource");
1033       CritResIdx = 0;
1034       IsResourceLimited = false;
1035       ExpectedCount = 0;
1036       ShouldIncreaseILP = false;
1037 #ifndef NDEBUG
1038       MaxMinLatency = 0;
1039 #endif
1040       // Reserve a zero-count for invalid CritResIdx.
1041       ResourceCounts.resize(1);
1042     }
1043
1044     /// Pending queues extend the ready queues with the same ID and the
1045     /// PendingFlag set.
1046     SchedBoundary(unsigned ID, const Twine &Name):
1047       DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1048       Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1049       reset();
1050     }
1051
1052     ~SchedBoundary() { delete HazardRec; }
1053
1054     void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1055               SchedRemainder *rem);
1056
1057     bool isTop() const {
1058       return Available.getID() == ConvergingScheduler::TopQID;
1059     }
1060
1061     unsigned getUnscheduledLatency(SUnit *SU) const {
1062       if (isTop())
1063         return SU->getHeight();
1064       return SU->getDepth();
1065     }
1066
1067     unsigned getCriticalCount() const {
1068       return ResourceCounts[CritResIdx];
1069     }
1070
1071     bool checkHazard(SUnit *SU);
1072
1073     void checkILPPolicy();
1074
1075     void releaseNode(SUnit *SU, unsigned ReadyCycle);
1076
1077     void bumpCycle();
1078
1079     void countResource(unsigned PIdx, unsigned Cycles);
1080
1081     void bumpNode(SUnit *SU);
1082
1083     void releasePending();
1084
1085     void removeReady(SUnit *SU);
1086
1087     SUnit *pickOnlyChoice();
1088   };
1089
1090 private:
1091   ScheduleDAGMI *DAG;
1092   const TargetSchedModel *SchedModel;
1093   const TargetRegisterInfo *TRI;
1094
1095   // State of the top and bottom scheduled instruction boundaries.
1096   SchedRemainder Rem;
1097   SchedBoundary Top;
1098   SchedBoundary Bot;
1099
1100 public:
1101   /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1102   enum {
1103     TopQID = 1,
1104     BotQID = 2,
1105     LogMaxQID = 2
1106   };
1107
1108   ConvergingScheduler():
1109     DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1110
1111   virtual void initialize(ScheduleDAGMI *dag);
1112
1113   virtual SUnit *pickNode(bool &IsTopNode);
1114
1115   virtual void schedNode(SUnit *SU, bool IsTopNode);
1116
1117   virtual void releaseTopNode(SUnit *SU);
1118
1119   virtual void releaseBottomNode(SUnit *SU);
1120
1121   virtual void registerRoots();
1122
1123 protected:
1124   void balanceZones(
1125     ConvergingScheduler::SchedBoundary &CriticalZone,
1126     ConvergingScheduler::SchedCandidate &CriticalCand,
1127     ConvergingScheduler::SchedBoundary &OppositeZone,
1128     ConvergingScheduler::SchedCandidate &OppositeCand);
1129
1130   void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1131                            ConvergingScheduler::SchedCandidate &BotCand);
1132
1133   void tryCandidate(SchedCandidate &Cand,
1134                     SchedCandidate &TryCand,
1135                     SchedBoundary &Zone,
1136                     const RegPressureTracker &RPTracker,
1137                     RegPressureTracker &TempTracker);
1138
1139   SUnit *pickNodeBidirectional(bool &IsTopNode);
1140
1141   void pickNodeFromQueue(SchedBoundary &Zone,
1142                          const RegPressureTracker &RPTracker,
1143                          SchedCandidate &Candidate);
1144
1145 #ifndef NDEBUG
1146   void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
1147 #endif
1148 };
1149 } // namespace
1150
1151 void ConvergingScheduler::SchedRemainder::
1152 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1153   reset();
1154   if (!SchedModel->hasInstrSchedModel())
1155     return;
1156   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1157   for (std::vector<SUnit>::iterator
1158          I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1159     const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1160     RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1161     for (TargetSchedModel::ProcResIter
1162            PI = SchedModel->getWriteProcResBegin(SC),
1163            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1164       unsigned PIdx = PI->ProcResourceIdx;
1165       unsigned Factor = SchedModel->getResourceFactor(PIdx);
1166       RemainingCounts[PIdx] += (Factor * PI->Cycles);
1167     }
1168   }
1169 }
1170
1171 void ConvergingScheduler::SchedBoundary::
1172 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1173   reset();
1174   DAG = dag;
1175   SchedModel = smodel;
1176   Rem = rem;
1177   if (SchedModel->hasInstrSchedModel())
1178     ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1179 }
1180
1181 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1182   DAG = dag;
1183   SchedModel = DAG->getSchedModel();
1184   TRI = DAG->TRI;
1185   Rem.init(DAG, SchedModel);
1186   Top.init(DAG, SchedModel, &Rem);
1187   Bot.init(DAG, SchedModel, &Rem);
1188
1189   // Initialize resource counts.
1190
1191   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1192   // are disabled, then these HazardRecs will be disabled.
1193   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1194   const TargetMachine &TM = DAG->MF.getTarget();
1195   Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1196   Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1197
1198   assert((!ForceTopDown || !ForceBottomUp) &&
1199          "-misched-topdown incompatible with -misched-bottomup");
1200 }
1201
1202 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1203   if (SU->isScheduled)
1204     return;
1205
1206   for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1207        I != E; ++I) {
1208     unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1209     unsigned MinLatency = I->getMinLatency();
1210 #ifndef NDEBUG
1211     Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
1212 #endif
1213     if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1214       SU->TopReadyCycle = PredReadyCycle + MinLatency;
1215   }
1216   Top.releaseNode(SU, SU->TopReadyCycle);
1217 }
1218
1219 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1220   if (SU->isScheduled)
1221     return;
1222
1223   assert(SU->getInstr() && "Scheduled SUnit must have instr");
1224
1225   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1226        I != E; ++I) {
1227     if (I->isWeak())
1228       continue;
1229     unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1230     unsigned MinLatency = I->getMinLatency();
1231 #ifndef NDEBUG
1232     Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
1233 #endif
1234     if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1235       SU->BotReadyCycle = SuccReadyCycle + MinLatency;
1236   }
1237   Bot.releaseNode(SU, SU->BotReadyCycle);
1238 }
1239
1240 void ConvergingScheduler::registerRoots() {
1241   Rem.CriticalPath = DAG->ExitSU.getDepth();
1242   // Some roots may not feed into ExitSU. Check all of them in case.
1243   for (std::vector<SUnit*>::const_iterator
1244          I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1245     if ((*I)->getDepth() > Rem.CriticalPath)
1246       Rem.CriticalPath = (*I)->getDepth();
1247   }
1248   DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1249 }
1250
1251 /// Does this SU have a hazard within the current instruction group.
1252 ///
1253 /// The scheduler supports two modes of hazard recognition. The first is the
1254 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1255 /// supports highly complicated in-order reservation tables
1256 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1257 ///
1258 /// The second is a streamlined mechanism that checks for hazards based on
1259 /// simple counters that the scheduler itself maintains. It explicitly checks
1260 /// for instruction dispatch limitations, including the number of micro-ops that
1261 /// can dispatch per cycle.
1262 ///
1263 /// TODO: Also check whether the SU must start a new group.
1264 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1265   if (HazardRec->isEnabled())
1266     return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1267
1268   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1269   if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1270     DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
1271           << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1272     return true;
1273   }
1274   return false;
1275 }
1276
1277 /// If expected latency is covered, disable ILP policy.
1278 void ConvergingScheduler::SchedBoundary::checkILPPolicy() {
1279   if (ShouldIncreaseILP
1280       && (IsResourceLimited || ExpectedLatency <= CurrCycle)) {
1281     ShouldIncreaseILP = false;
1282     DEBUG(dbgs() << "Disable ILP: " << Available.getName() << '\n');
1283   }
1284 }
1285
1286 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1287                                                      unsigned ReadyCycle) {
1288
1289   if (ReadyCycle < MinReadyCycle)
1290     MinReadyCycle = ReadyCycle;
1291
1292   // Check for interlocks first. For the purpose of other heuristics, an
1293   // instruction that cannot issue appears as if it's not in the ReadyQueue.
1294   if (ReadyCycle > CurrCycle || checkHazard(SU))
1295     Pending.push(SU);
1296   else
1297     Available.push(SU);
1298
1299   // Record this node as an immediate dependent of the scheduled node.
1300   NextSUs.insert(SU);
1301
1302   // If CriticalPath has been computed, then check if the unscheduled nodes
1303   // exceed the ILP window. Before registerRoots, CriticalPath==0.
1304   if (Rem->CriticalPath && (ExpectedLatency + getUnscheduledLatency(SU)
1305                             > Rem->CriticalPath + ILPWindow)) {
1306     ShouldIncreaseILP = true;
1307     DEBUG(dbgs() << "Increase ILP: " << Available.getName() << " "
1308           << ExpectedLatency << " + " << getUnscheduledLatency(SU) << '\n');
1309   }
1310 }
1311
1312 /// Move the boundary of scheduled code by one cycle.
1313 void ConvergingScheduler::SchedBoundary::bumpCycle() {
1314   unsigned Width = SchedModel->getIssueWidth();
1315   IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
1316
1317   unsigned NextCycle = CurrCycle + 1;
1318   assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1319   if (MinReadyCycle > NextCycle) {
1320     IssueCount = 0;
1321     NextCycle = MinReadyCycle;
1322   }
1323
1324   if (!HazardRec->isEnabled()) {
1325     // Bypass HazardRec virtual calls.
1326     CurrCycle = NextCycle;
1327   }
1328   else {
1329     // Bypass getHazardType calls in case of long latency.
1330     for (; CurrCycle != NextCycle; ++CurrCycle) {
1331       if (isTop())
1332         HazardRec->AdvanceCycle();
1333       else
1334         HazardRec->RecedeCycle();
1335     }
1336   }
1337   CheckPending = true;
1338   IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1339
1340   DEBUG(dbgs() << "  *** " << Available.getName() << " cycle "
1341         << CurrCycle << '\n');
1342 }
1343
1344 /// Add the given processor resource to this scheduled zone.
1345 void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1346                                                        unsigned Cycles) {
1347   unsigned Factor = SchedModel->getResourceFactor(PIdx);
1348   DEBUG(dbgs() << "  " << SchedModel->getProcResource(PIdx)->Name
1349         << " +(" << Cycles << "x" << Factor
1350         << ") / " << SchedModel->getLatencyFactor() << '\n');
1351
1352   unsigned Count = Factor * Cycles;
1353   ResourceCounts[PIdx] += Count;
1354   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1355   Rem->RemainingCounts[PIdx] -= Count;
1356
1357   // Reset MaxRemainingCount for sanity.
1358   Rem->MaxRemainingCount = 0;
1359
1360   // Check if this resource exceeds the current critical resource by a full
1361   // cycle. If so, it becomes the critical resource.
1362   if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1363       >= (int)SchedModel->getLatencyFactor()) {
1364     CritResIdx = PIdx;
1365     DEBUG(dbgs() << "  *** Critical resource "
1366           << SchedModel->getProcResource(PIdx)->Name << " x"
1367           << ResourceCounts[PIdx] << '\n');
1368   }
1369 }
1370
1371 /// Move the boundary of scheduled code by one SUnit.
1372 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1373   // Update the reservation table.
1374   if (HazardRec->isEnabled()) {
1375     if (!isTop() && SU->isCall) {
1376       // Calls are scheduled with their preceding instructions. For bottom-up
1377       // scheduling, clear the pipeline state before emitting.
1378       HazardRec->Reset();
1379     }
1380     HazardRec->EmitInstruction(SU);
1381   }
1382   // Update resource counts and critical resource.
1383   if (SchedModel->hasInstrSchedModel()) {
1384     const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1385     Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1386     for (TargetSchedModel::ProcResIter
1387            PI = SchedModel->getWriteProcResBegin(SC),
1388            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1389       countResource(PI->ProcResourceIdx, PI->Cycles);
1390     }
1391   }
1392   if (isTop()) {
1393     if (SU->getDepth() > ExpectedLatency)
1394       ExpectedLatency = SU->getDepth();
1395   }
1396   else {
1397     if (SU->getHeight() > ExpectedLatency)
1398       ExpectedLatency = SU->getHeight();
1399   }
1400
1401   IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1402
1403   // Check the instruction group dispatch limit.
1404   // TODO: Check if this SU must end a dispatch group.
1405   IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
1406
1407   // checkHazard prevents scheduling multiple instructions per cycle that exceed
1408   // issue width. However, we commonly reach the maximum. In this case
1409   // opportunistically bump the cycle to avoid uselessly checking everything in
1410   // the readyQ. Furthermore, a single instruction may produce more than one
1411   // cycle's worth of micro-ops.
1412   if (IssueCount >= SchedModel->getIssueWidth()) {
1413     DEBUG(dbgs() << "  *** Max instrs at cycle " << CurrCycle << '\n');
1414     bumpCycle();
1415   }
1416 }
1417
1418 /// Release pending ready nodes in to the available queue. This makes them
1419 /// visible to heuristics.
1420 void ConvergingScheduler::SchedBoundary::releasePending() {
1421   // If the available queue is empty, it is safe to reset MinReadyCycle.
1422   if (Available.empty())
1423     MinReadyCycle = UINT_MAX;
1424
1425   // Check to see if any of the pending instructions are ready to issue.  If
1426   // so, add them to the available queue.
1427   for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1428     SUnit *SU = *(Pending.begin()+i);
1429     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1430
1431     if (ReadyCycle < MinReadyCycle)
1432       MinReadyCycle = ReadyCycle;
1433
1434     if (ReadyCycle > CurrCycle)
1435       continue;
1436
1437     if (checkHazard(SU))
1438       continue;
1439
1440     Available.push(SU);
1441     Pending.remove(Pending.begin()+i);
1442     --i; --e;
1443   }
1444   DEBUG(if (!Pending.empty()) Pending.dump());
1445   CheckPending = false;
1446 }
1447
1448 /// Remove SU from the ready set for this boundary.
1449 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1450   if (Available.isInQueue(SU))
1451     Available.remove(Available.find(SU));
1452   else {
1453     assert(Pending.isInQueue(SU) && "bad ready count");
1454     Pending.remove(Pending.find(SU));
1455   }
1456 }
1457
1458 /// If this queue only has one ready candidate, return it. As a side effect,
1459 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1460 /// one node is ready. If multiple instructions are ready, return NULL.
1461 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1462   if (CheckPending)
1463     releasePending();
1464
1465   if (IssueCount > 0) {
1466     // Defer any ready instrs that now have a hazard.
1467     for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1468       if (checkHazard(*I)) {
1469         Pending.push(*I);
1470         I = Available.remove(I);
1471         continue;
1472       }
1473       ++I;
1474     }
1475   }
1476   for (unsigned i = 0; Available.empty(); ++i) {
1477     assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1478            "permanent hazard"); (void)i;
1479     bumpCycle();
1480     releasePending();
1481   }
1482   if (Available.size() == 1)
1483     return *Available.begin();
1484   return NULL;
1485 }
1486
1487 /// Record the candidate policy for opposite zones with different critical
1488 /// resources.
1489 ///
1490 /// If the CriticalZone is latency limited, don't force a policy for the
1491 /// candidates here. Instead, When releasing each candidate, releaseNode
1492 /// compares the region's critical path to the candidate's height or depth and
1493 /// the scheduled zone's expected latency then sets ShouldIncreaseILP.
1494 void ConvergingScheduler::balanceZones(
1495   ConvergingScheduler::SchedBoundary &CriticalZone,
1496   ConvergingScheduler::SchedCandidate &CriticalCand,
1497   ConvergingScheduler::SchedBoundary &OppositeZone,
1498   ConvergingScheduler::SchedCandidate &OppositeCand) {
1499
1500   if (!CriticalZone.IsResourceLimited)
1501     return;
1502
1503   SchedRemainder *Rem = CriticalZone.Rem;
1504
1505   // If the critical zone is overconsuming a resource relative to the
1506   // remainder, try to reduce it.
1507   unsigned RemainingCritCount =
1508     Rem->RemainingCounts[CriticalZone.CritResIdx];
1509   if ((int)(Rem->MaxRemainingCount - RemainingCritCount)
1510       > (int)SchedModel->getLatencyFactor()) {
1511     CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1512     DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1513           << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1514           << '\n');
1515   }
1516   // If the other zone is underconsuming a resource relative to the full zone,
1517   // try to increase it.
1518   unsigned OppositeCount =
1519     OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1520   if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1521       > (int)SchedModel->getLatencyFactor()) {
1522     OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1523     DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1524           << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1525           << '\n');
1526   }
1527 }
1528
1529 /// Determine if the scheduled zones exceed resource limits or critical path and
1530 /// set each candidate's ReduceHeight policy accordingly.
1531 void ConvergingScheduler::checkResourceLimits(
1532   ConvergingScheduler::SchedCandidate &TopCand,
1533   ConvergingScheduler::SchedCandidate &BotCand) {
1534
1535   Bot.checkILPPolicy();
1536   Top.checkILPPolicy();
1537   if (Bot.ShouldIncreaseILP)
1538     BotCand.Policy.ReduceLatency = true;
1539   if (Top.ShouldIncreaseILP)
1540     TopCand.Policy.ReduceLatency = true;
1541
1542   // Handle resource-limited regions.
1543   if (Top.IsResourceLimited && Bot.IsResourceLimited
1544       && Top.CritResIdx == Bot.CritResIdx) {
1545     // If the scheduled critical resource in both zones is no longer the
1546     // critical remaining resource, attempt to reduce resource height both ways.
1547     if (Top.CritResIdx != Rem.CritResIdx) {
1548       TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1549       BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1550       DEBUG(dbgs() << "Reduce scheduled "
1551             << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1552     }
1553     return;
1554   }
1555   // Handle latency-limited regions.
1556   if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1557     // If the total scheduled expected latency exceeds the region's critical
1558     // path then reduce latency both ways.
1559     //
1560     // Just because a zone is not resource limited does not mean it is latency
1561     // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1562     // to exceed expected latency.
1563     if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1564         && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1565       TopCand.Policy.ReduceLatency = true;
1566       BotCand.Policy.ReduceLatency = true;
1567       DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1568             << " + " << Bot.ExpectedLatency << '\n');
1569     }
1570     return;
1571   }
1572   // The critical resource is different in each zone, so request balancing.
1573
1574   // Compute the cost of each zone.
1575   Rem.MaxRemainingCount = std::max(
1576     Rem.RemainingMicroOps * SchedModel->getMicroOpFactor(),
1577     Rem.RemainingCounts[Rem.CritResIdx]);
1578   Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1579   Top.ExpectedCount = std::max(
1580     Top.getCriticalCount(),
1581     Top.ExpectedCount * SchedModel->getLatencyFactor());
1582   Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1583   Bot.ExpectedCount = std::max(
1584     Bot.getCriticalCount(),
1585     Bot.ExpectedCount * SchedModel->getLatencyFactor());
1586
1587   balanceZones(Top, TopCand, Bot, BotCand);
1588   balanceZones(Bot, BotCand, Top, TopCand);
1589 }
1590
1591 void ConvergingScheduler::SchedCandidate::
1592 initResourceDelta(const ScheduleDAGMI *DAG,
1593                   const TargetSchedModel *SchedModel) {
1594   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1595     return;
1596
1597   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1598   for (TargetSchedModel::ProcResIter
1599          PI = SchedModel->getWriteProcResBegin(SC),
1600          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1601     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1602       ResDelta.CritResources += PI->Cycles;
1603     if (PI->ProcResourceIdx == Policy.DemandResIdx)
1604       ResDelta.DemandedResources += PI->Cycles;
1605   }
1606 }
1607
1608 /// Return true if this heuristic determines order.
1609 static bool tryLess(unsigned TryVal, unsigned CandVal,
1610                     ConvergingScheduler::SchedCandidate &TryCand,
1611                     ConvergingScheduler::SchedCandidate &Cand,
1612                     ConvergingScheduler::CandReason Reason) {
1613   if (TryVal < CandVal) {
1614     TryCand.Reason = Reason;
1615     return true;
1616   }
1617   if (TryVal > CandVal) {
1618     if (Cand.Reason > Reason)
1619       Cand.Reason = Reason;
1620     return true;
1621   }
1622   return false;
1623 }
1624
1625 static bool tryGreater(unsigned TryVal, unsigned CandVal,
1626                        ConvergingScheduler::SchedCandidate &TryCand,
1627                        ConvergingScheduler::SchedCandidate &Cand,
1628                        ConvergingScheduler::CandReason Reason) {
1629   if (TryVal > CandVal) {
1630     TryCand.Reason = Reason;
1631     return true;
1632   }
1633   if (TryVal < CandVal) {
1634     if (Cand.Reason > Reason)
1635       Cand.Reason = Reason;
1636     return true;
1637   }
1638   return false;
1639 }
1640
1641 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1642   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1643 }
1644
1645 /// Apply a set of heursitics to a new candidate. Heuristics are currently
1646 /// hierarchical. This may be more efficient than a graduated cost model because
1647 /// we don't need to evaluate all aspects of the model for each node in the
1648 /// queue. But it's really done to make the heuristics easier to debug and
1649 /// statistically analyze.
1650 ///
1651 /// \param Cand provides the policy and current best candidate.
1652 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1653 /// \param Zone describes the scheduled zone that we are extending.
1654 /// \param RPTracker describes reg pressure within the scheduled zone.
1655 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
1656 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1657                                        SchedCandidate &TryCand,
1658                                        SchedBoundary &Zone,
1659                                        const RegPressureTracker &RPTracker,
1660                                        RegPressureTracker &TempTracker) {
1661
1662   // Always initialize TryCand's RPDelta.
1663   TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1664                                   DAG->getRegionCriticalPSets(),
1665                                   DAG->getRegPressure().MaxSetPressure);
1666
1667   // Initialize the candidate if needed.
1668   if (!Cand.isValid()) {
1669     TryCand.Reason = NodeOrder;
1670     return;
1671   }
1672   // Avoid exceeding the target's limit.
1673   if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1674               Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1675     return;
1676   if (Cand.Reason == SingleExcess)
1677     Cand.Reason = MultiPressure;
1678
1679   // Avoid increasing the max critical pressure in the scheduled region.
1680   if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1681               Cand.RPDelta.CriticalMax.UnitIncrease,
1682               TryCand, Cand, SingleCritical))
1683     return;
1684   if (Cand.Reason == SingleCritical)
1685     Cand.Reason = MultiPressure;
1686
1687   // Keep clustered nodes together to encourage downstream peephole
1688   // optimizations which may reduce resource requirements.
1689   //
1690   // This is a best effort to set things up for a post-RA pass. Optimizations
1691   // like generating loads of multiple registers should ideally be done within
1692   // the scheduler pass by combining the loads during DAG postprocessing.
1693   const SUnit *NextClusterSU =
1694     Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1695   if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1696                  TryCand, Cand, Cluster))
1697     return;
1698   // Currently, weak edges are for clustering, so we hard-code that reason.
1699   // However, deferring the current TryCand will not change Cand's reason.
1700   CandReason OrigReason = Cand.Reason;
1701   if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1702               getWeakLeft(Cand.SU, Zone.isTop()),
1703               TryCand, Cand, Cluster)) {
1704     Cand.Reason = OrigReason;
1705     return;
1706   }
1707   // Avoid critical resource consumption and balance the schedule.
1708   TryCand.initResourceDelta(DAG, SchedModel);
1709   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1710               TryCand, Cand, ResourceReduce))
1711     return;
1712   if (tryGreater(TryCand.ResDelta.DemandedResources,
1713                  Cand.ResDelta.DemandedResources,
1714                  TryCand, Cand, ResourceDemand))
1715     return;
1716
1717   // Avoid serializing long latency dependence chains.
1718   if (Cand.Policy.ReduceLatency) {
1719     if (Zone.isTop()) {
1720       if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1721           > Zone.ExpectedCount) {
1722         if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1723                     TryCand, Cand, TopDepthReduce))
1724           return;
1725       }
1726       if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1727                      TryCand, Cand, TopPathReduce))
1728         return;
1729     }
1730     else {
1731       if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1732           > Zone.ExpectedCount) {
1733         if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1734                     TryCand, Cand, BotHeightReduce))
1735           return;
1736       }
1737       if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1738                      TryCand, Cand, BotPathReduce))
1739         return;
1740     }
1741   }
1742
1743   // Avoid increasing the max pressure of the entire region.
1744   if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1745               Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1746     return;
1747   if (Cand.Reason == SingleMax)
1748     Cand.Reason = MultiPressure;
1749
1750   // Prefer immediate defs/users of the last scheduled instruction. This is a
1751   // nice pressure avoidance strategy that also conserves the processor's
1752   // register renaming resources and keeps the machine code readable.
1753   if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1754                  TryCand, Cand, NextDefUse))
1755     return;
1756
1757   // Fall through to original instruction order.
1758   if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1759       || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1760     TryCand.Reason = NodeOrder;
1761   }
1762 }
1763
1764 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1765 /// more desirable than RHS from scheduling standpoint.
1766 static bool compareRPDelta(const RegPressureDelta &LHS,
1767                            const RegPressureDelta &RHS) {
1768   // Compare each component of pressure in decreasing order of importance
1769   // without checking if any are valid. Invalid PressureElements are assumed to
1770   // have UnitIncrease==0, so are neutral.
1771
1772   // Avoid increasing the max critical pressure in the scheduled region.
1773   if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1774     DEBUG(dbgs() << "RP excess top - bot: "
1775           << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
1776     return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1777   }
1778   // Avoid increasing the max critical pressure in the scheduled region.
1779   if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1780     DEBUG(dbgs() << "RP critical top - bot: "
1781           << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1782           << '\n');
1783     return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1784   }
1785   // Avoid increasing the max pressure of the entire region.
1786   if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1787     DEBUG(dbgs() << "RP current top - bot: "
1788           << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1789           << '\n');
1790     return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1791   }
1792   return false;
1793 }
1794
1795 #ifndef NDEBUG
1796 const char *ConvergingScheduler::getReasonStr(
1797   ConvergingScheduler::CandReason Reason) {
1798   switch (Reason) {
1799   case NoCand:         return "NOCAND    ";
1800   case SingleExcess:   return "REG-EXCESS";
1801   case SingleCritical: return "REG-CRIT  ";
1802   case Cluster:        return "CLUSTER   ";
1803   case SingleMax:      return "REG-MAX   ";
1804   case MultiPressure:  return "REG-MULTI ";
1805   case ResourceReduce: return "RES-REDUCE";
1806   case ResourceDemand: return "RES-DEMAND";
1807   case TopDepthReduce: return "TOP-DEPTH ";
1808   case TopPathReduce:  return "TOP-PATH  ";
1809   case BotHeightReduce:return "BOT-HEIGHT";
1810   case BotPathReduce:  return "BOT-PATH  ";
1811   case NextDefUse:     return "DEF-USE   ";
1812   case NodeOrder:      return "ORDER     ";
1813   };
1814   llvm_unreachable("Unknown reason!");
1815 }
1816
1817 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1818                                          const SchedBoundary &Zone) {
1819   const char *Label = getReasonStr(Cand.Reason);
1820   PressureElement P;
1821   unsigned ResIdx = 0;
1822   unsigned Latency = 0;
1823   switch (Cand.Reason) {
1824   default:
1825     break;
1826   case SingleExcess:
1827     P = Cand.RPDelta.Excess;
1828     break;
1829   case SingleCritical:
1830     P = Cand.RPDelta.CriticalMax;
1831     break;
1832   case SingleMax:
1833     P = Cand.RPDelta.CurrentMax;
1834     break;
1835   case ResourceReduce:
1836     ResIdx = Cand.Policy.ReduceResIdx;
1837     break;
1838   case ResourceDemand:
1839     ResIdx = Cand.Policy.DemandResIdx;
1840     break;
1841   case TopDepthReduce:
1842     Latency = Cand.SU->getDepth();
1843     break;
1844   case TopPathReduce:
1845     Latency = Cand.SU->getHeight();
1846     break;
1847   case BotHeightReduce:
1848     Latency = Cand.SU->getHeight();
1849     break;
1850   case BotPathReduce:
1851     Latency = Cand.SU->getDepth();
1852     break;
1853   }
1854   dbgs() << Label << " " << Zone.Available.getName() << " ";
1855   if (P.isValid())
1856     dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1857            << " ";
1858   else
1859     dbgs() << "     ";
1860   if (ResIdx)
1861     dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1862   else
1863     dbgs() << "        ";
1864   if (Latency)
1865     dbgs() << Latency << " cycles ";
1866   else
1867     dbgs() << "         ";
1868   Cand.SU->dump(DAG);
1869 }
1870 #endif
1871
1872 /// Pick the best candidate from the top queue.
1873 ///
1874 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1875 /// DAG building. To adjust for the current scheduling location we need to
1876 /// maintain the number of vreg uses remaining to be top-scheduled.
1877 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1878                                             const RegPressureTracker &RPTracker,
1879                                             SchedCandidate &Cand) {
1880   ReadyQueue &Q = Zone.Available;
1881
1882   DEBUG(Q.dump());
1883
1884   // getMaxPressureDelta temporarily modifies the tracker.
1885   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1886
1887   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
1888
1889     SchedCandidate TryCand(Cand.Policy);
1890     TryCand.SU = *I;
1891     tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1892     if (TryCand.Reason != NoCand) {
1893       // Initialize resource delta if needed in case future heuristics query it.
1894       if (TryCand.ResDelta == SchedResourceDelta())
1895         TryCand.initResourceDelta(DAG, SchedModel);
1896       Cand.setBest(TryCand);
1897       DEBUG(traceCandidate(Cand, Zone));
1898     }
1899     TryCand.SU = *I;
1900   }
1901 }
1902
1903 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1904                       bool IsTop) {
1905   DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1906         << " SU(" << Cand.SU->NodeNum << ") "
1907         << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
1908 }
1909
1910 /// Pick the best candidate node from either the top or bottom queue.
1911 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
1912   // Schedule as far as possible in the direction of no choice. This is most
1913   // efficient, but also provides the best heuristics for CriticalPSets.
1914   if (SUnit *SU = Bot.pickOnlyChoice()) {
1915     IsTopNode = false;
1916     return SU;
1917   }
1918   if (SUnit *SU = Top.pickOnlyChoice()) {
1919     IsTopNode = true;
1920     return SU;
1921   }
1922   CandPolicy NoPolicy;
1923   SchedCandidate BotCand(NoPolicy);
1924   SchedCandidate TopCand(NoPolicy);
1925   checkResourceLimits(TopCand, BotCand);
1926
1927   // Prefer bottom scheduling when heuristics are silent.
1928   pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1929   assert(BotCand.Reason != NoCand && "failed to find the first candidate");
1930
1931   // If either Q has a single candidate that provides the least increase in
1932   // Excess pressure, we can immediately schedule from that Q.
1933   //
1934   // RegionCriticalPSets summarizes the pressure within the scheduled region and
1935   // affects picking from either Q. If scheduling in one direction must
1936   // increase pressure for one of the excess PSets, then schedule in that
1937   // direction first to provide more freedom in the other direction.
1938   if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
1939     IsTopNode = false;
1940     tracePick(BotCand, IsTopNode);
1941     return BotCand.SU;
1942   }
1943   // Check if the top Q has a better candidate.
1944   pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1945   assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1946
1947   // If either Q has a single candidate that minimizes pressure above the
1948   // original region's pressure pick it.
1949   if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1950     if (TopCand.Reason < BotCand.Reason) {
1951       IsTopNode = true;
1952       tracePick(TopCand, IsTopNode);
1953       return TopCand.SU;
1954     }
1955     IsTopNode = false;
1956     tracePick(BotCand, IsTopNode);
1957     return BotCand.SU;
1958   }
1959   // Check for a salient pressure difference and pick the best from either side.
1960   if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
1961     IsTopNode = true;
1962     tracePick(TopCand, IsTopNode);
1963     return TopCand.SU;
1964   }
1965   // Otherwise prefer the bottom candidate, in node order if all else failed.
1966   if (TopCand.Reason < BotCand.Reason) {
1967     IsTopNode = true;
1968     tracePick(TopCand, IsTopNode);
1969     return TopCand.SU;
1970   }
1971   IsTopNode = false;
1972   tracePick(BotCand, IsTopNode);
1973   return BotCand.SU;
1974 }
1975
1976 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
1977 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1978   if (DAG->top() == DAG->bottom()) {
1979     assert(Top.Available.empty() && Top.Pending.empty() &&
1980            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
1981     return NULL;
1982   }
1983   SUnit *SU;
1984   do {
1985     if (ForceTopDown) {
1986       SU = Top.pickOnlyChoice();
1987       if (!SU) {
1988         CandPolicy NoPolicy;
1989         SchedCandidate TopCand(NoPolicy);
1990         pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1991         assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1992         SU = TopCand.SU;
1993       }
1994       IsTopNode = true;
1995     }
1996     else if (ForceBottomUp) {
1997       SU = Bot.pickOnlyChoice();
1998       if (!SU) {
1999         CandPolicy NoPolicy;
2000         SchedCandidate BotCand(NoPolicy);
2001         pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2002         assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2003         SU = BotCand.SU;
2004       }
2005       IsTopNode = false;
2006     }
2007     else {
2008       SU = pickNodeBidirectional(IsTopNode);
2009     }
2010   } while (SU->isScheduled);
2011
2012   if (SU->isTopReady())
2013     Top.removeReady(SU);
2014   if (SU->isBottomReady())
2015     Bot.removeReady(SU);
2016
2017   DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2018         << " Scheduling Instruction in cycle "
2019         << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2020         SU->dump(DAG));
2021   return SU;
2022 }
2023
2024 /// Update the scheduler's state after scheduling a node. This is the same node
2025 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2026 /// it's state based on the current cycle before MachineSchedStrategy does.
2027 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2028   if (IsTopNode) {
2029     SU->TopReadyCycle = Top.CurrCycle;
2030     Top.bumpNode(SU);
2031   }
2032   else {
2033     SU->BotReadyCycle = Bot.CurrCycle;
2034     Bot.bumpNode(SU);
2035   }
2036 }
2037
2038 /// Create the standard converging machine scheduler. This will be used as the
2039 /// default scheduler if the target does not set a default.
2040 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2041   assert((!ForceTopDown || !ForceBottomUp) &&
2042          "-misched-topdown incompatible with -misched-bottomup");
2043   ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2044   // Register DAG post-processors.
2045   if (EnableLoadCluster)
2046     DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2047   if (EnableMacroFusion)
2048     DAG->addMutation(new MacroFusion(DAG->TII));
2049   return DAG;
2050 }
2051 static MachineSchedRegistry
2052 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2053                         createConvergingSched);
2054
2055 //===----------------------------------------------------------------------===//
2056 // ILP Scheduler. Currently for experimental analysis of heuristics.
2057 //===----------------------------------------------------------------------===//
2058
2059 namespace {
2060 /// \brief Order nodes by the ILP metric.
2061 struct ILPOrder {
2062   SchedDFSResult *DFSResult;
2063   BitVector *ScheduledTrees;
2064   bool MaximizeILP;
2065
2066   ILPOrder(SchedDFSResult *dfs, BitVector *schedtrees, bool MaxILP)
2067     : DFSResult(dfs), ScheduledTrees(schedtrees), MaximizeILP(MaxILP) {}
2068
2069   /// \brief Apply a less-than relation on node priority.
2070   ///
2071   /// (Return true if A comes after B in the Q.)
2072   bool operator()(const SUnit *A, const SUnit *B) const {
2073     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2074     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2075     if (SchedTreeA != SchedTreeB) {
2076       // Unscheduled trees have lower priority.
2077       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2078         return ScheduledTrees->test(SchedTreeB);
2079
2080       // Trees with shallower connections have have lower priority.
2081       if (DFSResult->getSubtreeLevel(SchedTreeA)
2082           != DFSResult->getSubtreeLevel(SchedTreeB)) {
2083         return DFSResult->getSubtreeLevel(SchedTreeA)
2084           < DFSResult->getSubtreeLevel(SchedTreeB);
2085       }
2086     }
2087     if (MaximizeILP)
2088       return DFSResult->getILP(A) < DFSResult->getILP(B);
2089     else
2090       return DFSResult->getILP(A) > DFSResult->getILP(B);
2091   }
2092 };
2093
2094 /// \brief Schedule based on the ILP metric.
2095 class ILPScheduler : public MachineSchedStrategy {
2096   /// In case all subtrees are eventually connected to a common root through
2097   /// data dependence (e.g. reduction), place an upper limit on their size.
2098   ///
2099   /// FIXME: A subtree limit is generally good, but in the situation commented
2100   /// above, where multiple similar subtrees feed a common root, we should
2101   /// only split at a point where the resulting subtrees will be balanced.
2102   /// (a motivating test case must be found).
2103   static const unsigned SubtreeLimit = 16;
2104
2105   SchedDFSResult DFSResult;
2106   BitVector ScheduledTrees;
2107   ILPOrder Cmp;
2108
2109   std::vector<SUnit*> ReadyQ;
2110 public:
2111   ILPScheduler(bool MaximizeILP)
2112   : DFSResult(/*BottomUp=*/true, SubtreeLimit),
2113     Cmp(&DFSResult, &ScheduledTrees, MaximizeILP) {}
2114
2115   virtual void initialize(ScheduleDAGMI *DAG) {
2116     ReadyQ.clear();
2117     DFSResult.clear();
2118     DFSResult.resize(DAG->SUnits.size());
2119     ScheduledTrees.clear();
2120   }
2121
2122   virtual void registerRoots() {
2123     DFSResult.compute(ReadyQ);
2124     ScheduledTrees.resize(DFSResult.getNumSubtrees());
2125     // Restore the heap in ReadyQ with the updated DFS results.
2126     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2127   }
2128
2129   /// Implement MachineSchedStrategy interface.
2130   /// -----------------------------------------
2131
2132   /// Callback to select the highest priority node from the ready Q.
2133   virtual SUnit *pickNode(bool &IsTopNode) {
2134     if (ReadyQ.empty()) return NULL;
2135     pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2136     SUnit *SU = ReadyQ.back();
2137     ReadyQ.pop_back();
2138     IsTopNode = false;
2139     DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2140           << *SU->getInstr()
2141           << " ILP: " << DFSResult.getILP(SU)
2142           << " Tree: " << DFSResult.getSubtreeID(SU) << " @"
2143           << DFSResult.getSubtreeLevel(DFSResult.getSubtreeID(SU))<< '\n');
2144     return SU;
2145   }
2146
2147   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2148   /// DFSResults, and resort the priority Q.
2149   virtual void schedNode(SUnit *SU, bool IsTopNode) {
2150     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2151     if (!ScheduledTrees.test(DFSResult.getSubtreeID(SU))) {
2152       ScheduledTrees.set(DFSResult.getSubtreeID(SU));
2153       DFSResult.scheduleTree(DFSResult.getSubtreeID(SU));
2154       std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2155     }
2156   }
2157
2158   virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2159
2160   virtual void releaseBottomNode(SUnit *SU) {
2161     ReadyQ.push_back(SU);
2162     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2163   }
2164 };
2165 } // namespace
2166
2167 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2168   return new ScheduleDAGMI(C, new ILPScheduler(true));
2169 }
2170 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2171   return new ScheduleDAGMI(C, new ILPScheduler(false));
2172 }
2173 static MachineSchedRegistry ILPMaxRegistry(
2174   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2175 static MachineSchedRegistry ILPMinRegistry(
2176   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2177
2178 //===----------------------------------------------------------------------===//
2179 // Machine Instruction Shuffler for Correctness Testing
2180 //===----------------------------------------------------------------------===//
2181
2182 #ifndef NDEBUG
2183 namespace {
2184 /// Apply a less-than relation on the node order, which corresponds to the
2185 /// instruction order prior to scheduling. IsReverse implements greater-than.
2186 template<bool IsReverse>
2187 struct SUnitOrder {
2188   bool operator()(SUnit *A, SUnit *B) const {
2189     if (IsReverse)
2190       return A->NodeNum > B->NodeNum;
2191     else
2192       return A->NodeNum < B->NodeNum;
2193   }
2194 };
2195
2196 /// Reorder instructions as much as possible.
2197 class InstructionShuffler : public MachineSchedStrategy {
2198   bool IsAlternating;
2199   bool IsTopDown;
2200
2201   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2202   // gives nodes with a higher number higher priority causing the latest
2203   // instructions to be scheduled first.
2204   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2205     TopQ;
2206   // When scheduling bottom-up, use greater-than as the queue priority.
2207   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2208     BottomQ;
2209 public:
2210   InstructionShuffler(bool alternate, bool topdown)
2211     : IsAlternating(alternate), IsTopDown(topdown) {}
2212
2213   virtual void initialize(ScheduleDAGMI *) {
2214     TopQ.clear();
2215     BottomQ.clear();
2216   }
2217
2218   /// Implement MachineSchedStrategy interface.
2219   /// -----------------------------------------
2220
2221   virtual SUnit *pickNode(bool &IsTopNode) {
2222     SUnit *SU;
2223     if (IsTopDown) {
2224       do {
2225         if (TopQ.empty()) return NULL;
2226         SU = TopQ.top();
2227         TopQ.pop();
2228       } while (SU->isScheduled);
2229       IsTopNode = true;
2230     }
2231     else {
2232       do {
2233         if (BottomQ.empty()) return NULL;
2234         SU = BottomQ.top();
2235         BottomQ.pop();
2236       } while (SU->isScheduled);
2237       IsTopNode = false;
2238     }
2239     if (IsAlternating)
2240       IsTopDown = !IsTopDown;
2241     return SU;
2242   }
2243
2244   virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2245
2246   virtual void releaseTopNode(SUnit *SU) {
2247     TopQ.push(SU);
2248   }
2249   virtual void releaseBottomNode(SUnit *SU) {
2250     BottomQ.push(SU);
2251   }
2252 };
2253 } // namespace
2254
2255 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2256   bool Alternate = !ForceTopDown && !ForceBottomUp;
2257   bool TopDown = !ForceBottomUp;
2258   assert((TopDown || !ForceTopDown) &&
2259          "-misched-topdown incompatible with -misched-bottomup");
2260   return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2261 }
2262 static MachineSchedRegistry ShufflerRegistry(
2263   "shuffle", "Shuffle machine instructions alternating directions",
2264   createInstructionShuffler);
2265 #endif // !NDEBUG