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