Stub out a PostMachineScheduler pass.
[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/MachineDominators.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterClassInfo.h"
27 #include "llvm/CodeGen/ScheduleDFS.h"
28 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include <queue>
36
37 using namespace llvm;
38
39 namespace llvm {
40 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
41                            cl::desc("Force top-down list scheduling"));
42 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
43                             cl::desc("Force bottom-up list scheduling"));
44 }
45
46 #ifndef NDEBUG
47 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
48   cl::desc("Pop up a window to show MISched dags after they are processed"));
49
50 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
51   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
52 #else
53 static bool ViewMISchedDAGs = false;
54 #endif // NDEBUG
55
56 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
57   cl::desc("Enable register pressure scheduling."), cl::init(true));
58
59 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
60   cl::desc("Enable cyclic critical path analysis."), cl::init(true));
61
62 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
63   cl::desc("Enable load clustering."), cl::init(true));
64
65 // Experimental heuristics
66 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
67   cl::desc("Enable scheduling for macro fusion."), cl::init(true));
68
69 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
70   cl::desc("Verify machine instrs before and after machine scheduling"));
71
72 // DAG subtrees must have at least this many nodes.
73 static const unsigned MinSubtreeSize = 8;
74
75 // Pin the vtables to this file.
76 void MachineSchedStrategy::anchor() {}
77 void ScheduleDAGMutation::anchor() {}
78
79 //===----------------------------------------------------------------------===//
80 // Machine Instruction Scheduling Pass and Registry
81 //===----------------------------------------------------------------------===//
82
83 MachineSchedContext::MachineSchedContext():
84     MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
85   RegClassInfo = new RegisterClassInfo();
86 }
87
88 MachineSchedContext::~MachineSchedContext() {
89   delete RegClassInfo;
90 }
91
92 namespace {
93 /// Base class for a machine scheduler class that can run at any point.
94 class MachineSchedulerBase : public MachineSchedContext,
95                              public MachineFunctionPass {
96 public:
97   MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
98
99   virtual void print(raw_ostream &O, const Module* = 0) const;
100
101 protected:
102   void scheduleRegions(ScheduleDAGInstrs &Scheduler);
103 };
104
105 /// MachineScheduler runs after coalescing and before register allocation.
106 class MachineScheduler : public MachineSchedulerBase {
107 public:
108   MachineScheduler();
109
110   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
111
112   virtual bool runOnMachineFunction(MachineFunction&);
113
114   static char ID; // Class identification, replacement for typeinfo
115
116 protected:
117   ScheduleDAGInstrs *createMachineScheduler();
118 };
119
120 /// PostMachineScheduler runs after shortly before code emission.
121 class PostMachineScheduler : public MachineSchedulerBase {
122 public:
123   PostMachineScheduler();
124
125   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
126
127   virtual bool runOnMachineFunction(MachineFunction&);
128
129   static char ID; // Class identification, replacement for typeinfo
130
131 protected:
132   ScheduleDAGInstrs *createPostMachineScheduler();
133 };
134 } // namespace
135
136 char MachineScheduler::ID = 0;
137
138 char &llvm::MachineSchedulerID = MachineScheduler::ID;
139
140 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
141                       "Machine Instruction Scheduler", false, false)
142 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
143 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
144 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
145 INITIALIZE_PASS_END(MachineScheduler, "misched",
146                     "Machine Instruction Scheduler", false, false)
147
148 MachineScheduler::MachineScheduler()
149 : MachineSchedulerBase(ID) {
150   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
151 }
152
153 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
154   AU.setPreservesCFG();
155   AU.addRequiredID(MachineDominatorsID);
156   AU.addRequired<MachineLoopInfo>();
157   AU.addRequired<AliasAnalysis>();
158   AU.addRequired<TargetPassConfig>();
159   AU.addRequired<SlotIndexes>();
160   AU.addPreserved<SlotIndexes>();
161   AU.addRequired<LiveIntervals>();
162   AU.addPreserved<LiveIntervals>();
163   MachineFunctionPass::getAnalysisUsage(AU);
164 }
165
166 char PostMachineScheduler::ID = 0;
167
168 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
169
170 INITIALIZE_PASS(PostMachineScheduler, "postmisched",
171                 "PostRA Machine Instruction Scheduler", false, false);
172
173 PostMachineScheduler::PostMachineScheduler()
174 : MachineSchedulerBase(ID) {
175   initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
176 }
177
178 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
179   AU.setPreservesCFG();
180   AU.addRequiredID(MachineDominatorsID);
181   AU.addRequired<MachineLoopInfo>();
182   AU.addRequired<TargetPassConfig>();
183   MachineFunctionPass::getAnalysisUsage(AU);
184 }
185
186 MachinePassRegistry MachineSchedRegistry::Registry;
187
188 /// A dummy default scheduler factory indicates whether the scheduler
189 /// is overridden on the command line.
190 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
191   return 0;
192 }
193
194 /// MachineSchedOpt allows command line selection of the scheduler.
195 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
196                RegisterPassParser<MachineSchedRegistry> >
197 MachineSchedOpt("misched",
198                 cl::init(&useDefaultMachineSched), cl::Hidden,
199                 cl::desc("Machine instruction scheduler to use"));
200
201 static MachineSchedRegistry
202 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
203                      useDefaultMachineSched);
204
205 /// Forward declare the standard machine scheduler. This will be used as the
206 /// default scheduler if the target does not set a default.
207 static ScheduleDAGInstrs *createGenericSched(MachineSchedContext *C);
208 static ScheduleDAGInstrs *createRawGenericSched(MachineSchedContext *C);
209
210 /// Decrement this iterator until reaching the top or a non-debug instr.
211 static MachineBasicBlock::const_iterator
212 priorNonDebug(MachineBasicBlock::const_iterator I,
213               MachineBasicBlock::const_iterator Beg) {
214   assert(I != Beg && "reached the top of the region, cannot decrement");
215   while (--I != Beg) {
216     if (!I->isDebugValue())
217       break;
218   }
219   return I;
220 }
221
222 /// Non-const version.
223 static MachineBasicBlock::iterator
224 priorNonDebug(MachineBasicBlock::iterator I,
225               MachineBasicBlock::const_iterator Beg) {
226   return const_cast<MachineInstr*>(
227     &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
228 }
229
230 /// If this iterator is a debug value, increment until reaching the End or a
231 /// non-debug instruction.
232 static MachineBasicBlock::const_iterator
233 nextIfDebug(MachineBasicBlock::const_iterator I,
234             MachineBasicBlock::const_iterator End) {
235   for(; I != End; ++I) {
236     if (!I->isDebugValue())
237       break;
238   }
239   return I;
240 }
241
242 /// Non-const version.
243 static MachineBasicBlock::iterator
244 nextIfDebug(MachineBasicBlock::iterator I,
245             MachineBasicBlock::const_iterator End) {
246   // Cast the return value to nonconst MachineInstr, then cast to an
247   // instr_iterator, which does not check for null, finally return a
248   // bundle_iterator.
249   return MachineBasicBlock::instr_iterator(
250     const_cast<MachineInstr*>(
251       &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
252 }
253
254 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
255 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
256   // Select the scheduler, or set the default.
257   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
258   if (Ctor != useDefaultMachineSched)
259     return Ctor(this);
260
261   // Get the default scheduler set by the target for this function.
262   ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
263   if (Scheduler)
264     return Scheduler;
265
266   // Default to GenericScheduler.
267   return createGenericSched(this);
268 }
269
270 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
271 /// the caller. We don't have a command line option to override the postRA
272 /// scheduler. The Target must configure it.
273 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
274   // Get the postRA scheduler set by the target for this function.
275   ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
276   if (Scheduler)
277     return Scheduler;
278
279   // Default to GenericScheduler.
280   // return createRawGenericSched(this);
281   return NULL;
282 }
283
284 /// Top-level MachineScheduler pass driver.
285 ///
286 /// Visit blocks in function order. Divide each block into scheduling regions
287 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
288 /// consistent with the DAG builder, which traverses the interior of the
289 /// scheduling regions bottom-up.
290 ///
291 /// This design avoids exposing scheduling boundaries to the DAG builder,
292 /// simplifying the DAG builder's support for "special" target instructions.
293 /// At the same time the design allows target schedulers to operate across
294 /// scheduling boundaries, for example to bundle the boudary instructions
295 /// without reordering them. This creates complexity, because the target
296 /// scheduler must update the RegionBegin and RegionEnd positions cached by
297 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
298 /// design would be to split blocks at scheduling boundaries, but LLVM has a
299 /// general bias against block splitting purely for implementation simplicity.
300 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
301   DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
302
303   // Initialize the context of the pass.
304   MF = &mf;
305   MLI = &getAnalysis<MachineLoopInfo>();
306   MDT = &getAnalysis<MachineDominatorTree>();
307   PassConfig = &getAnalysis<TargetPassConfig>();
308   AA = &getAnalysis<AliasAnalysis>();
309
310   LIS = &getAnalysis<LiveIntervals>();
311
312   if (VerifyScheduling) {
313     DEBUG(LIS->dump());
314     MF->verify(this, "Before machine scheduling.");
315   }
316   RegClassInfo->runOnMachineFunction(*MF);
317
318   // Instantiate the selected scheduler for this target, function, and
319   // optimization level.
320   OwningPtr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
321   scheduleRegions(*Scheduler);
322
323   DEBUG(LIS->dump());
324   if (VerifyScheduling)
325     MF->verify(this, "After machine scheduling.");
326   return true;
327 }
328
329 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
330   DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
331
332   // Initialize the context of the pass.
333   MF = &mf;
334   PassConfig = &getAnalysis<TargetPassConfig>();
335
336   if (VerifyScheduling)
337     MF->verify(this, "Before post machine scheduling.");
338
339   // Instantiate the selected scheduler for this target, function, and
340   // optimization level.
341   OwningPtr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
342   scheduleRegions(*Scheduler);
343
344   if (VerifyScheduling)
345     MF->verify(this, "After post machine scheduling.");
346   return true;
347 }
348
349 /// Main driver for both MachineScheduler and PostMachineScheduler.
350 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
351   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
352
353   // Visit all machine basic blocks.
354   //
355   // TODO: Visit blocks in global postorder or postorder within the bottom-up
356   // loop tree. Then we can optionally compute global RegPressure.
357   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
358        MBB != MBBEnd; ++MBB) {
359
360     Scheduler.startBlock(MBB);
361
362     // Break the block into scheduling regions [I, RegionEnd), and schedule each
363     // region as soon as it is discovered. RegionEnd points the scheduling
364     // boundary at the bottom of the region. The DAG does not include RegionEnd,
365     // but the region does (i.e. the next RegionEnd is above the previous
366     // RegionBegin). If the current block has no terminator then RegionEnd ==
367     // MBB->end() for the bottom region.
368     //
369     // The Scheduler may insert instructions during either schedule() or
370     // exitRegion(), even for empty regions. So the local iterators 'I' and
371     // 'RegionEnd' are invalid across these calls.
372     unsigned RemainingInstrs = MBB->size();
373     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
374         RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
375
376       // Avoid decrementing RegionEnd for blocks with no terminator.
377       if (RegionEnd != MBB->end()
378           || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
379         --RegionEnd;
380         // Count the boundary instruction.
381         --RemainingInstrs;
382       }
383
384       // The next region starts above the previous region. Look backward in the
385       // instruction stream until we find the nearest boundary.
386       unsigned NumRegionInstrs = 0;
387       MachineBasicBlock::iterator I = RegionEnd;
388       for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
389         if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
390           break;
391       }
392       // Notify the scheduler of the region, even if we may skip scheduling
393       // it. Perhaps it still needs to be bundled.
394       Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
395
396       // Skip empty scheduling regions (0 or 1 schedulable instructions).
397       if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
398         // Close the current region. Bundle the terminator if needed.
399         // This invalidates 'RegionEnd' and 'I'.
400         Scheduler.exitRegion();
401         continue;
402       }
403       DEBUG(dbgs() << "********** MI Scheduling **********\n");
404       DEBUG(dbgs() << MF->getName()
405             << ":BB#" << MBB->getNumber() << " " << MBB->getName()
406             << "\n  From: " << *I << "    To: ";
407             if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
408             else dbgs() << "End";
409             dbgs() << " RegionInstrs: " << NumRegionInstrs
410             << " Remaining: " << RemainingInstrs << "\n");
411
412       // Schedule a region: possibly reorder instructions.
413       // This invalidates 'RegionEnd' and 'I'.
414       Scheduler.schedule();
415
416       // Close the current region.
417       Scheduler.exitRegion();
418
419       // Scheduling has invalidated the current iterator 'I'. Ask the
420       // scheduler for the top of it's scheduled region.
421       RegionEnd = Scheduler.begin();
422     }
423     assert(RemainingInstrs == 0 && "Instruction count mismatch!");
424     Scheduler.finishBlock();
425   }
426   Scheduler.finalizeSchedule();
427 }
428
429 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
430   // unimplemented
431 }
432
433 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
434 void ReadyQueue::dump() {
435   dbgs() << Name << ": ";
436   for (unsigned i = 0, e = Queue.size(); i < e; ++i)
437     dbgs() << Queue[i]->NodeNum << " ";
438   dbgs() << "\n";
439 }
440 #endif
441
442 //===----------------------------------------------------------------------===//
443 // ScheduleDAGMI - Basic machine instruction scheduling. This is
444 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
445 // virtual registers.
446 // ===----------------------------------------------------------------------===/
447
448 ScheduleDAGMI::~ScheduleDAGMI() {
449   DeleteContainerPointers(Mutations);
450   delete SchedImpl;
451 }
452
453 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
454   return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
455 }
456
457 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
458   if (SuccSU != &ExitSU) {
459     // Do not use WillCreateCycle, it assumes SD scheduling.
460     // If Pred is reachable from Succ, then the edge creates a cycle.
461     if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
462       return false;
463     Topo.AddPred(SuccSU, PredDep.getSUnit());
464   }
465   SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
466   // Return true regardless of whether a new edge needed to be inserted.
467   return true;
468 }
469
470 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
471 /// NumPredsLeft reaches zero, release the successor node.
472 ///
473 /// FIXME: Adjust SuccSU height based on MinLatency.
474 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
475   SUnit *SuccSU = SuccEdge->getSUnit();
476
477   if (SuccEdge->isWeak()) {
478     --SuccSU->WeakPredsLeft;
479     if (SuccEdge->isCluster())
480       NextClusterSucc = SuccSU;
481     return;
482   }
483 #ifndef NDEBUG
484   if (SuccSU->NumPredsLeft == 0) {
485     dbgs() << "*** Scheduling failed! ***\n";
486     SuccSU->dump(this);
487     dbgs() << " has been released too many times!\n";
488     llvm_unreachable(0);
489   }
490 #endif
491   --SuccSU->NumPredsLeft;
492   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
493     SchedImpl->releaseTopNode(SuccSU);
494 }
495
496 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
497 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
498   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
499        I != E; ++I) {
500     releaseSucc(SU, &*I);
501   }
502 }
503
504 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
505 /// NumSuccsLeft reaches zero, release the predecessor node.
506 ///
507 /// FIXME: Adjust PredSU height based on MinLatency.
508 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
509   SUnit *PredSU = PredEdge->getSUnit();
510
511   if (PredEdge->isWeak()) {
512     --PredSU->WeakSuccsLeft;
513     if (PredEdge->isCluster())
514       NextClusterPred = PredSU;
515     return;
516   }
517 #ifndef NDEBUG
518   if (PredSU->NumSuccsLeft == 0) {
519     dbgs() << "*** Scheduling failed! ***\n";
520     PredSU->dump(this);
521     dbgs() << " has been released too many times!\n";
522     llvm_unreachable(0);
523   }
524 #endif
525   --PredSU->NumSuccsLeft;
526   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
527     SchedImpl->releaseBottomNode(PredSU);
528 }
529
530 /// releasePredecessors - Call releasePred on each of SU's predecessors.
531 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
532   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
533        I != E; ++I) {
534     releasePred(SU, &*I);
535   }
536 }
537
538 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
539 /// crossing a scheduling boundary. [begin, end) includes all instructions in
540 /// the region, including the boundary itself and single-instruction regions
541 /// that don't get scheduled.
542 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
543                                      MachineBasicBlock::iterator begin,
544                                      MachineBasicBlock::iterator end,
545                                      unsigned regioninstrs)
546 {
547   ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
548
549   SchedImpl->initPolicy(begin, end, regioninstrs);
550 }
551
552 /// This is normally called from the main scheduler loop but may also be invoked
553 /// by the scheduling strategy to perform additional code motion.
554 void ScheduleDAGMI::moveInstruction(
555   MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
556   // Advance RegionBegin if the first instruction moves down.
557   if (&*RegionBegin == MI)
558     ++RegionBegin;
559
560   // Update the instruction stream.
561   BB->splice(InsertPos, BB, MI);
562
563   // Update LiveIntervals
564   if (LIS)
565     LIS->handleMove(MI, /*UpdateFlags=*/true);
566
567   // Recede RegionBegin if an instruction moves above the first.
568   if (RegionBegin == InsertPos)
569     RegionBegin = MI;
570 }
571
572 bool ScheduleDAGMI::checkSchedLimit() {
573 #ifndef NDEBUG
574   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
575     CurrentTop = CurrentBottom;
576     return false;
577   }
578   ++NumInstrsScheduled;
579 #endif
580   return true;
581 }
582
583 /// Per-region scheduling driver, called back from
584 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
585 /// does not consider liveness or register pressure. It is useful for PostRA
586 /// scheduling and potentially other custom schedulers.
587 void ScheduleDAGMI::schedule() {
588   // Build the DAG.
589   buildSchedGraph(AA);
590
591   Topo.InitDAGTopologicalSorting();
592
593   postprocessDAG();
594
595   SmallVector<SUnit*, 8> TopRoots, BotRoots;
596   findRootsAndBiasEdges(TopRoots, BotRoots);
597
598   // Initialize the strategy before modifying the DAG.
599   // This may initialize a DFSResult to be used for queue priority.
600   SchedImpl->initialize(this);
601
602   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
603           SUnits[su].dumpAll(this));
604   if (ViewMISchedDAGs) viewGraph();
605
606   // Initialize ready queues now that the DAG and priority data are finalized.
607   initQueues(TopRoots, BotRoots);
608
609   bool IsTopNode = false;
610   while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
611     assert(!SU->isScheduled && "Node already scheduled");
612     if (!checkSchedLimit())
613       break;
614
615     MachineInstr *MI = SU->getInstr();
616     if (IsTopNode) {
617       assert(SU->isTopReady() && "node still has unscheduled dependencies");
618       if (&*CurrentTop == MI)
619         CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
620       else
621         moveInstruction(MI, CurrentTop);
622     }
623     else {
624       assert(SU->isBottomReady() && "node still has unscheduled dependencies");
625       MachineBasicBlock::iterator priorII =
626         priorNonDebug(CurrentBottom, CurrentTop);
627       if (&*priorII == MI)
628         CurrentBottom = priorII;
629       else {
630         if (&*CurrentTop == MI)
631           CurrentTop = nextIfDebug(++CurrentTop, priorII);
632         moveInstruction(MI, CurrentBottom);
633         CurrentBottom = MI;
634       }
635     }
636     updateQueues(SU, IsTopNode);
637
638     // Notify the scheduling strategy after updating the DAG.
639     SchedImpl->schedNode(SU, IsTopNode);
640   }
641   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
642
643   placeDebugValues();
644
645   DEBUG({
646       unsigned BBNum = begin()->getParent()->getNumber();
647       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
648       dumpSchedule();
649       dbgs() << '\n';
650     });
651 }
652
653 /// Apply each ScheduleDAGMutation step in order.
654 void ScheduleDAGMI::postprocessDAG() {
655   for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
656     Mutations[i]->apply(this);
657   }
658 }
659
660 void ScheduleDAGMI::
661 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
662                       SmallVectorImpl<SUnit*> &BotRoots) {
663   for (std::vector<SUnit>::iterator
664          I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
665     SUnit *SU = &(*I);
666     assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
667
668     // Order predecessors so DFSResult follows the critical path.
669     SU->biasCriticalPath();
670
671     // A SUnit is ready to top schedule if it has no predecessors.
672     if (!I->NumPredsLeft)
673       TopRoots.push_back(SU);
674     // A SUnit is ready to bottom schedule if it has no successors.
675     if (!I->NumSuccsLeft)
676       BotRoots.push_back(SU);
677   }
678   ExitSU.biasCriticalPath();
679 }
680
681 /// Identify DAG roots and setup scheduler queues.
682 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
683                                ArrayRef<SUnit*> BotRoots) {
684   NextClusterSucc = NULL;
685   NextClusterPred = NULL;
686
687   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
688   //
689   // Nodes with unreleased weak edges can still be roots.
690   // Release top roots in forward order.
691   for (SmallVectorImpl<SUnit*>::const_iterator
692          I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
693     SchedImpl->releaseTopNode(*I);
694   }
695   // Release bottom roots in reverse order so the higher priority nodes appear
696   // first. This is more natural and slightly more efficient.
697   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
698          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
699     SchedImpl->releaseBottomNode(*I);
700   }
701
702   releaseSuccessors(&EntrySU);
703   releasePredecessors(&ExitSU);
704
705   SchedImpl->registerRoots();
706
707   // Advance past initial DebugValues.
708   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
709   CurrentBottom = RegionEnd;
710 }
711
712 /// Update scheduler queues after scheduling an instruction.
713 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
714   // Release dependent instructions for scheduling.
715   if (IsTopNode)
716     releaseSuccessors(SU);
717   else
718     releasePredecessors(SU);
719
720   SU->isScheduled = true;
721 }
722
723 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
724 void ScheduleDAGMI::placeDebugValues() {
725   // If first instruction was a DBG_VALUE then put it back.
726   if (FirstDbgValue) {
727     BB->splice(RegionBegin, BB, FirstDbgValue);
728     RegionBegin = FirstDbgValue;
729   }
730
731   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
732          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
733     std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
734     MachineInstr *DbgValue = P.first;
735     MachineBasicBlock::iterator OrigPrevMI = P.second;
736     if (&*RegionBegin == DbgValue)
737       ++RegionBegin;
738     BB->splice(++OrigPrevMI, BB, DbgValue);
739     if (OrigPrevMI == llvm::prior(RegionEnd))
740       RegionEnd = DbgValue;
741   }
742   DbgValues.clear();
743   FirstDbgValue = NULL;
744 }
745
746 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
747 void ScheduleDAGMI::dumpSchedule() const {
748   for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
749     if (SUnit *SU = getSUnit(&(*MI)))
750       SU->dump(this);
751     else
752       dbgs() << "Missing SUnit\n";
753   }
754 }
755 #endif
756
757 //===----------------------------------------------------------------------===//
758 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
759 // preservation.
760 //===----------------------------------------------------------------------===//
761
762 ScheduleDAGMILive::~ScheduleDAGMILive() {
763   delete DFSResult;
764 }
765
766 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
767 /// crossing a scheduling boundary. [begin, end) includes all instructions in
768 /// the region, including the boundary itself and single-instruction regions
769 /// that don't get scheduled.
770 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
771                                 MachineBasicBlock::iterator begin,
772                                 MachineBasicBlock::iterator end,
773                                 unsigned regioninstrs)
774 {
775   // ScheduleDAGMI initializes SchedImpl's per-region policy.
776   ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
777
778   // For convenience remember the end of the liveness region.
779   LiveRegionEnd =
780     (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
781
782   SUPressureDiffs.clear();
783
784   ShouldTrackPressure = SchedImpl->shouldTrackPressure();
785 }
786
787 // Setup the register pressure trackers for the top scheduled top and bottom
788 // scheduled regions.
789 void ScheduleDAGMILive::initRegPressure() {
790   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
791   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
792
793   // Close the RPTracker to finalize live ins.
794   RPTracker.closeRegion();
795
796   DEBUG(RPTracker.dump());
797
798   // Initialize the live ins and live outs.
799   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
800   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
801
802   // Close one end of the tracker so we can call
803   // getMaxUpward/DownwardPressureDelta before advancing across any
804   // instructions. This converts currently live regs into live ins/outs.
805   TopRPTracker.closeTop();
806   BotRPTracker.closeBottom();
807
808   BotRPTracker.initLiveThru(RPTracker);
809   if (!BotRPTracker.getLiveThru().empty()) {
810     TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
811     DEBUG(dbgs() << "Live Thru: ";
812           dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
813   };
814
815   // For each live out vreg reduce the pressure change associated with other
816   // uses of the same vreg below the live-out reaching def.
817   updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
818
819   // Account for liveness generated by the region boundary.
820   if (LiveRegionEnd != RegionEnd) {
821     SmallVector<unsigned, 8> LiveUses;
822     BotRPTracker.recede(&LiveUses);
823     updatePressureDiffs(LiveUses);
824   }
825
826   assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
827
828   // Cache the list of excess pressure sets in this region. This will also track
829   // the max pressure in the scheduled code for these sets.
830   RegionCriticalPSets.clear();
831   const std::vector<unsigned> &RegionPressure =
832     RPTracker.getPressure().MaxSetPressure;
833   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
834     unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
835     if (RegionPressure[i] > Limit) {
836       DEBUG(dbgs() << TRI->getRegPressureSetName(i)
837             << " Limit " << Limit
838             << " Actual " << RegionPressure[i] << "\n");
839       RegionCriticalPSets.push_back(PressureChange(i));
840     }
841   }
842   DEBUG(dbgs() << "Excess PSets: ";
843         for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
844           dbgs() << TRI->getRegPressureSetName(
845             RegionCriticalPSets[i].getPSet()) << " ";
846         dbgs() << "\n");
847 }
848
849 void ScheduleDAGMILive::
850 updateScheduledPressure(const SUnit *SU,
851                         const std::vector<unsigned> &NewMaxPressure) {
852   const PressureDiff &PDiff = getPressureDiff(SU);
853   unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
854   for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
855        I != E; ++I) {
856     if (!I->isValid())
857       break;
858     unsigned ID = I->getPSet();
859     while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
860       ++CritIdx;
861     if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
862       if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
863           && NewMaxPressure[ID] <= INT16_MAX)
864         RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
865     }
866     unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
867     if (NewMaxPressure[ID] >= Limit - 2) {
868       DEBUG(dbgs() << "  " << TRI->getRegPressureSetName(ID) << ": "
869             << NewMaxPressure[ID] << " > " << Limit << "(+ "
870             << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
871     }
872   }
873 }
874
875 /// Update the PressureDiff array for liveness after scheduling this
876 /// instruction.
877 void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
878   for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
879     /// FIXME: Currently assuming single-use physregs.
880     unsigned Reg = LiveUses[LUIdx];
881     DEBUG(dbgs() << "  LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
882     if (!TRI->isVirtualRegister(Reg))
883       continue;
884
885     // This may be called before CurrentBottom has been initialized. However,
886     // BotRPTracker must have a valid position. We want the value live into the
887     // instruction or live out of the block, so ask for the previous
888     // instruction's live-out.
889     const LiveInterval &LI = LIS->getInterval(Reg);
890     VNInfo *VNI;
891     MachineBasicBlock::const_iterator I =
892       nextIfDebug(BotRPTracker.getPos(), BB->end());
893     if (I == BB->end())
894       VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
895     else {
896       LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
897       VNI = LRQ.valueIn();
898     }
899     // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
900     assert(VNI && "No live value at use.");
901     for (VReg2UseMap::iterator
902            UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
903       SUnit *SU = UI->SU;
904       DEBUG(dbgs() << "  UpdateRegP: SU(" << SU->NodeNum << ") "
905             << *SU->getInstr());
906       // If this use comes before the reaching def, it cannot be a last use, so
907       // descrease its pressure change.
908       if (!SU->isScheduled && SU != &ExitSU) {
909         LiveQueryResult LRQ
910           = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
911         if (LRQ.valueIn() == VNI)
912           getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
913       }
914     }
915   }
916 }
917
918 /// schedule - Called back from MachineScheduler::runOnMachineFunction
919 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
920 /// only includes instructions that have DAG nodes, not scheduling boundaries.
921 ///
922 /// This is a skeletal driver, with all the functionality pushed into helpers,
923 /// so that it can be easilly extended by experimental schedulers. Generally,
924 /// implementing MachineSchedStrategy should be sufficient to implement a new
925 /// scheduling algorithm. However, if a scheduler further subclasses
926 /// ScheduleDAGMILive then it will want to override this virtual method in order
927 /// to update any specialized state.
928 void ScheduleDAGMILive::schedule() {
929   buildDAGWithRegPressure();
930
931   Topo.InitDAGTopologicalSorting();
932
933   postprocessDAG();
934
935   SmallVector<SUnit*, 8> TopRoots, BotRoots;
936   findRootsAndBiasEdges(TopRoots, BotRoots);
937
938   // Initialize the strategy before modifying the DAG.
939   // This may initialize a DFSResult to be used for queue priority.
940   SchedImpl->initialize(this);
941
942   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
943           SUnits[su].dumpAll(this));
944   if (ViewMISchedDAGs) viewGraph();
945
946   // Initialize ready queues now that the DAG and priority data are finalized.
947   initQueues(TopRoots, BotRoots);
948
949   if (ShouldTrackPressure) {
950     assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
951     TopRPTracker.setPos(CurrentTop);
952   }
953
954   bool IsTopNode = false;
955   while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
956     assert(!SU->isScheduled && "Node already scheduled");
957     if (!checkSchedLimit())
958       break;
959
960     scheduleMI(SU, IsTopNode);
961
962     updateQueues(SU, IsTopNode);
963
964     if (DFSResult) {
965       unsigned SubtreeID = DFSResult->getSubtreeID(SU);
966       if (!ScheduledTrees.test(SubtreeID)) {
967         ScheduledTrees.set(SubtreeID);
968         DFSResult->scheduleTree(SubtreeID);
969         SchedImpl->scheduleTree(SubtreeID);
970       }
971     }
972
973     // Notify the scheduling strategy after updating the DAG.
974     SchedImpl->schedNode(SU, IsTopNode);
975   }
976   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
977
978   placeDebugValues();
979
980   DEBUG({
981       unsigned BBNum = begin()->getParent()->getNumber();
982       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
983       dumpSchedule();
984       dbgs() << '\n';
985     });
986 }
987
988 /// Build the DAG and setup three register pressure trackers.
989 void ScheduleDAGMILive::buildDAGWithRegPressure() {
990   if (!ShouldTrackPressure) {
991     RPTracker.reset();
992     RegionCriticalPSets.clear();
993     buildSchedGraph(AA);
994     return;
995   }
996
997   // Initialize the register pressure tracker used by buildSchedGraph.
998   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
999                  /*TrackUntiedDefs=*/true);
1000
1001   // Account for liveness generate by the region boundary.
1002   if (LiveRegionEnd != RegionEnd)
1003     RPTracker.recede();
1004
1005   // Build the DAG, and compute current register pressure.
1006   buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
1007
1008   // Initialize top/bottom trackers after computing region pressure.
1009   initRegPressure();
1010 }
1011
1012 void ScheduleDAGMILive::computeDFSResult() {
1013   if (!DFSResult)
1014     DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1015   DFSResult->clear();
1016   ScheduledTrees.clear();
1017   DFSResult->resize(SUnits.size());
1018   DFSResult->compute(SUnits);
1019   ScheduledTrees.resize(DFSResult->getNumSubtrees());
1020 }
1021
1022 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1023 /// only provides the critical path for single block loops. To handle loops that
1024 /// span blocks, we could use the vreg path latencies provided by
1025 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1026 /// available for use in the scheduler.
1027 ///
1028 /// The cyclic path estimation identifies a def-use pair that crosses the back
1029 /// edge and considers the depth and height of the nodes. For example, consider
1030 /// the following instruction sequence where each instruction has unit latency
1031 /// and defines an epomymous virtual register:
1032 ///
1033 /// a->b(a,c)->c(b)->d(c)->exit
1034 ///
1035 /// The cyclic critical path is a two cycles: b->c->b
1036 /// The acyclic critical path is four cycles: a->b->c->d->exit
1037 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1038 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1039 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1040 /// LiveInDepth = depth(b) = len(a->b) = 1
1041 ///
1042 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1043 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1044 /// CyclicCriticalPath = min(2, 2) = 2
1045 ///
1046 /// This could be relevant to PostRA scheduling, but is currently implemented
1047 /// assuming LiveIntervals.
1048 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1049   // This only applies to single block loop.
1050   if (!BB->isSuccessor(BB))
1051     return 0;
1052
1053   unsigned MaxCyclicLatency = 0;
1054   // Visit each live out vreg def to find def/use pairs that cross iterations.
1055   ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1056   for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1057        RI != RE; ++RI) {
1058     unsigned Reg = *RI;
1059     if (!TRI->isVirtualRegister(Reg))
1060         continue;
1061     const LiveInterval &LI = LIS->getInterval(Reg);
1062     const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1063     if (!DefVNI)
1064       continue;
1065
1066     MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1067     const SUnit *DefSU = getSUnit(DefMI);
1068     if (!DefSU)
1069       continue;
1070
1071     unsigned LiveOutHeight = DefSU->getHeight();
1072     unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1073     // Visit all local users of the vreg def.
1074     for (VReg2UseMap::iterator
1075            UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1076       if (UI->SU == &ExitSU)
1077         continue;
1078
1079       // Only consider uses of the phi.
1080       LiveQueryResult LRQ =
1081         LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
1082       if (!LRQ.valueIn()->isPHIDef())
1083         continue;
1084
1085       // Assume that a path spanning two iterations is a cycle, which could
1086       // overestimate in strange cases. This allows cyclic latency to be
1087       // estimated as the minimum slack of the vreg's depth or height.
1088       unsigned CyclicLatency = 0;
1089       if (LiveOutDepth > UI->SU->getDepth())
1090         CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1091
1092       unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1093       if (LiveInHeight > LiveOutHeight) {
1094         if (LiveInHeight - LiveOutHeight < CyclicLatency)
1095           CyclicLatency = LiveInHeight - LiveOutHeight;
1096       }
1097       else
1098         CyclicLatency = 0;
1099
1100       DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1101             << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1102       if (CyclicLatency > MaxCyclicLatency)
1103         MaxCyclicLatency = CyclicLatency;
1104     }
1105   }
1106   DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1107   return MaxCyclicLatency;
1108 }
1109
1110 /// Move an instruction and update register pressure.
1111 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1112   // Move the instruction to its new location in the instruction stream.
1113   MachineInstr *MI = SU->getInstr();
1114
1115   if (IsTopNode) {
1116     assert(SU->isTopReady() && "node still has unscheduled dependencies");
1117     if (&*CurrentTop == MI)
1118       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1119     else {
1120       moveInstruction(MI, CurrentTop);
1121       TopRPTracker.setPos(MI);
1122     }
1123
1124     if (ShouldTrackPressure) {
1125       // Update top scheduled pressure.
1126       TopRPTracker.advance();
1127       assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1128       updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1129     }
1130   }
1131   else {
1132     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1133     MachineBasicBlock::iterator priorII =
1134       priorNonDebug(CurrentBottom, CurrentTop);
1135     if (&*priorII == MI)
1136       CurrentBottom = priorII;
1137     else {
1138       if (&*CurrentTop == MI) {
1139         CurrentTop = nextIfDebug(++CurrentTop, priorII);
1140         TopRPTracker.setPos(CurrentTop);
1141       }
1142       moveInstruction(MI, CurrentBottom);
1143       CurrentBottom = MI;
1144     }
1145     if (ShouldTrackPressure) {
1146       // Update bottom scheduled pressure.
1147       SmallVector<unsigned, 8> LiveUses;
1148       BotRPTracker.recede(&LiveUses);
1149       assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1150       updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1151       updatePressureDiffs(LiveUses);
1152     }
1153   }
1154 }
1155
1156 //===----------------------------------------------------------------------===//
1157 // LoadClusterMutation - DAG post-processing to cluster loads.
1158 //===----------------------------------------------------------------------===//
1159
1160 namespace {
1161 /// \brief Post-process the DAG to create cluster edges between neighboring
1162 /// loads.
1163 class LoadClusterMutation : public ScheduleDAGMutation {
1164   struct LoadInfo {
1165     SUnit *SU;
1166     unsigned BaseReg;
1167     unsigned Offset;
1168     LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1169       : SU(su), BaseReg(reg), Offset(ofs) {}
1170   };
1171   static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
1172                            const LoadClusterMutation::LoadInfo &RHS);
1173
1174   const TargetInstrInfo *TII;
1175   const TargetRegisterInfo *TRI;
1176 public:
1177   LoadClusterMutation(const TargetInstrInfo *tii,
1178                       const TargetRegisterInfo *tri)
1179     : TII(tii), TRI(tri) {}
1180
1181   virtual void apply(ScheduleDAGMI *DAG);
1182 protected:
1183   void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1184 };
1185 } // anonymous
1186
1187 bool LoadClusterMutation::LoadInfoLess(
1188   const LoadClusterMutation::LoadInfo &LHS,
1189   const LoadClusterMutation::LoadInfo &RHS) {
1190   if (LHS.BaseReg != RHS.BaseReg)
1191     return LHS.BaseReg < RHS.BaseReg;
1192   return LHS.Offset < RHS.Offset;
1193 }
1194
1195 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1196                                                   ScheduleDAGMI *DAG) {
1197   SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1198   for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1199     SUnit *SU = Loads[Idx];
1200     unsigned BaseReg;
1201     unsigned Offset;
1202     if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1203       LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1204   }
1205   if (LoadRecords.size() < 2)
1206     return;
1207   std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
1208   unsigned ClusterLength = 1;
1209   for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1210     if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1211       ClusterLength = 1;
1212       continue;
1213     }
1214
1215     SUnit *SUa = LoadRecords[Idx].SU;
1216     SUnit *SUb = LoadRecords[Idx+1].SU;
1217     if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
1218         && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1219
1220       DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1221             << SUb->NodeNum << ")\n");
1222       // Copy successor edges from SUa to SUb. Interleaving computation
1223       // dependent on SUa can prevent load combining due to register reuse.
1224       // Predecessor edges do not need to be copied from SUb to SUa since nearby
1225       // loads should have effectively the same inputs.
1226       for (SUnit::const_succ_iterator
1227              SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1228         if (SI->getSUnit() == SUb)
1229           continue;
1230         DEBUG(dbgs() << "  Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1231         DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1232       }
1233       ++ClusterLength;
1234     }
1235     else
1236       ClusterLength = 1;
1237   }
1238 }
1239
1240 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1241 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1242   // Map DAG NodeNum to store chain ID.
1243   DenseMap<unsigned, unsigned> StoreChainIDs;
1244   // Map each store chain to a set of dependent loads.
1245   SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1246   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1247     SUnit *SU = &DAG->SUnits[Idx];
1248     if (!SU->getInstr()->mayLoad())
1249       continue;
1250     unsigned ChainPredID = DAG->SUnits.size();
1251     for (SUnit::const_pred_iterator
1252            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1253       if (PI->isCtrl()) {
1254         ChainPredID = PI->getSUnit()->NodeNum;
1255         break;
1256       }
1257     }
1258     // Check if this chain-like pred has been seen
1259     // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1260     unsigned NumChains = StoreChainDependents.size();
1261     std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1262       StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1263     if (Result.second)
1264       StoreChainDependents.resize(NumChains + 1);
1265     StoreChainDependents[Result.first->second].push_back(SU);
1266   }
1267   // Iterate over the store chains.
1268   for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1269     clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1270 }
1271
1272 //===----------------------------------------------------------------------===//
1273 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1274 //===----------------------------------------------------------------------===//
1275
1276 namespace {
1277 /// \brief Post-process the DAG to create cluster edges between instructions
1278 /// that may be fused by the processor into a single operation.
1279 class MacroFusion : public ScheduleDAGMutation {
1280   const TargetInstrInfo *TII;
1281 public:
1282   MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1283
1284   virtual void apply(ScheduleDAGMI *DAG);
1285 };
1286 } // anonymous
1287
1288 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1289 /// fused operations.
1290 void MacroFusion::apply(ScheduleDAGMI *DAG) {
1291   // For now, assume targets can only fuse with the branch.
1292   MachineInstr *Branch = DAG->ExitSU.getInstr();
1293   if (!Branch)
1294     return;
1295
1296   for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1297     SUnit *SU = &DAG->SUnits[--Idx];
1298     if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1299       continue;
1300
1301     // Create a single weak edge from SU to ExitSU. The only effect is to cause
1302     // bottom-up scheduling to heavily prioritize the clustered SU.  There is no
1303     // need to copy predecessor edges from ExitSU to SU, since top-down
1304     // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1305     // of SU, we could create an artificial edge from the deepest root, but it
1306     // hasn't been needed yet.
1307     bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1308     (void)Success;
1309     assert(Success && "No DAG nodes should be reachable from ExitSU");
1310
1311     DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1312     break;
1313   }
1314 }
1315
1316 //===----------------------------------------------------------------------===//
1317 // CopyConstrain - DAG post-processing to encourage copy elimination.
1318 //===----------------------------------------------------------------------===//
1319
1320 namespace {
1321 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1322 /// the one use that defines the copy's source vreg, most likely an induction
1323 /// variable increment.
1324 class CopyConstrain : public ScheduleDAGMutation {
1325   // Transient state.
1326   SlotIndex RegionBeginIdx;
1327   // RegionEndIdx is the slot index of the last non-debug instruction in the
1328   // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1329   SlotIndex RegionEndIdx;
1330 public:
1331   CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1332
1333   virtual void apply(ScheduleDAGMI *DAG);
1334
1335 protected:
1336   void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1337 };
1338 } // anonymous
1339
1340 /// constrainLocalCopy handles two possibilities:
1341 /// 1) Local src:
1342 /// I0:     = dst
1343 /// I1: src = ...
1344 /// I2:     = dst
1345 /// I3: dst = src (copy)
1346 /// (create pred->succ edges I0->I1, I2->I1)
1347 ///
1348 /// 2) Local copy:
1349 /// I0: dst = src (copy)
1350 /// I1:     = dst
1351 /// I2: src = ...
1352 /// I3:     = dst
1353 /// (create pred->succ edges I1->I2, I3->I2)
1354 ///
1355 /// Although the MachineScheduler is currently constrained to single blocks,
1356 /// this algorithm should handle extended blocks. An EBB is a set of
1357 /// contiguously numbered blocks such that the previous block in the EBB is
1358 /// always the single predecessor.
1359 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1360   LiveIntervals *LIS = DAG->getLIS();
1361   MachineInstr *Copy = CopySU->getInstr();
1362
1363   // Check for pure vreg copies.
1364   unsigned SrcReg = Copy->getOperand(1).getReg();
1365   if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1366     return;
1367
1368   unsigned DstReg = Copy->getOperand(0).getReg();
1369   if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1370     return;
1371
1372   // Check if either the dest or source is local. If it's live across a back
1373   // edge, it's not local. Note that if both vregs are live across the back
1374   // edge, we cannot successfully contrain the copy without cyclic scheduling.
1375   unsigned LocalReg = DstReg;
1376   unsigned GlobalReg = SrcReg;
1377   LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1378   if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1379     LocalReg = SrcReg;
1380     GlobalReg = DstReg;
1381     LocalLI = &LIS->getInterval(LocalReg);
1382     if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1383       return;
1384   }
1385   LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1386
1387   // Find the global segment after the start of the local LI.
1388   LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1389   // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1390   // local live range. We could create edges from other global uses to the local
1391   // start, but the coalescer should have already eliminated these cases, so
1392   // don't bother dealing with it.
1393   if (GlobalSegment == GlobalLI->end())
1394     return;
1395
1396   // If GlobalSegment is killed at the LocalLI->start, the call to find()
1397   // returned the next global segment. But if GlobalSegment overlaps with
1398   // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1399   // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1400   if (GlobalSegment->contains(LocalLI->beginIndex()))
1401     ++GlobalSegment;
1402
1403   if (GlobalSegment == GlobalLI->end())
1404     return;
1405
1406   // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1407   if (GlobalSegment != GlobalLI->begin()) {
1408     // Two address defs have no hole.
1409     if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1410                                GlobalSegment->start)) {
1411       return;
1412     }
1413     // If the prior global segment may be defined by the same two-address
1414     // instruction that also defines LocalLI, then can't make a hole here.
1415     if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1416                                LocalLI->beginIndex())) {
1417       return;
1418     }
1419     // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1420     // it would be a disconnected component in the live range.
1421     assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1422            "Disconnected LRG within the scheduling region.");
1423   }
1424   MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1425   if (!GlobalDef)
1426     return;
1427
1428   SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1429   if (!GlobalSU)
1430     return;
1431
1432   // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1433   // constraining the uses of the last local def to precede GlobalDef.
1434   SmallVector<SUnit*,8> LocalUses;
1435   const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1436   MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1437   SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1438   for (SUnit::const_succ_iterator
1439          I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1440        I != E; ++I) {
1441     if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1442       continue;
1443     if (I->getSUnit() == GlobalSU)
1444       continue;
1445     if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1446       return;
1447     LocalUses.push_back(I->getSUnit());
1448   }
1449   // Open the top of the GlobalLI hole by constraining any earlier global uses
1450   // to precede the start of LocalLI.
1451   SmallVector<SUnit*,8> GlobalUses;
1452   MachineInstr *FirstLocalDef =
1453     LIS->getInstructionFromIndex(LocalLI->beginIndex());
1454   SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1455   for (SUnit::const_pred_iterator
1456          I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1457     if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1458       continue;
1459     if (I->getSUnit() == FirstLocalSU)
1460       continue;
1461     if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1462       return;
1463     GlobalUses.push_back(I->getSUnit());
1464   }
1465   DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1466   // Add the weak edges.
1467   for (SmallVectorImpl<SUnit*>::const_iterator
1468          I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1469     DEBUG(dbgs() << "  Local use SU(" << (*I)->NodeNum << ") -> SU("
1470           << GlobalSU->NodeNum << ")\n");
1471     DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1472   }
1473   for (SmallVectorImpl<SUnit*>::const_iterator
1474          I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1475     DEBUG(dbgs() << "  Global use SU(" << (*I)->NodeNum << ") -> SU("
1476           << FirstLocalSU->NodeNum << ")\n");
1477     DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1478   }
1479 }
1480
1481 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1482 /// copy elimination.
1483 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1484   assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1485
1486   MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1487   if (FirstPos == DAG->end())
1488     return;
1489   RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1490   RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1491     &*priorNonDebug(DAG->end(), DAG->begin()));
1492
1493   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1494     SUnit *SU = &DAG->SUnits[Idx];
1495     if (!SU->getInstr()->isCopy())
1496       continue;
1497
1498     constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1499   }
1500 }
1501
1502 //===----------------------------------------------------------------------===//
1503 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1504 // and possibly other custom schedulers.
1505 // ===----------------------------------------------------------------------===/
1506
1507 static const unsigned InvalidCycle = ~0U;
1508
1509 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1510
1511 void SchedBoundary::reset() {
1512   // A new HazardRec is created for each DAG and owned by SchedBoundary.
1513   // Destroying and reconstructing it is very expensive though. So keep
1514   // invalid, placeholder HazardRecs.
1515   if (HazardRec && HazardRec->isEnabled()) {
1516     delete HazardRec;
1517     HazardRec = 0;
1518   }
1519   Available.clear();
1520   Pending.clear();
1521   CheckPending = false;
1522   NextSUs.clear();
1523   CurrCycle = 0;
1524   CurrMOps = 0;
1525   MinReadyCycle = UINT_MAX;
1526   ExpectedLatency = 0;
1527   DependentLatency = 0;
1528   RetiredMOps = 0;
1529   MaxExecutedResCount = 0;
1530   ZoneCritResIdx = 0;
1531   IsResourceLimited = false;
1532   ReservedCycles.clear();
1533 #ifndef NDEBUG
1534   MaxObservedLatency = 0;
1535 #endif
1536   // Reserve a zero-count for invalid CritResIdx.
1537   ExecutedResCounts.resize(1);
1538   assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1539 }
1540
1541 void SchedRemainder::
1542 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1543   reset();
1544   if (!SchedModel->hasInstrSchedModel())
1545     return;
1546   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1547   for (std::vector<SUnit>::iterator
1548          I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1549     const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1550     RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1551       * SchedModel->getMicroOpFactor();
1552     for (TargetSchedModel::ProcResIter
1553            PI = SchedModel->getWriteProcResBegin(SC),
1554            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1555       unsigned PIdx = PI->ProcResourceIdx;
1556       unsigned Factor = SchedModel->getResourceFactor(PIdx);
1557       RemainingCounts[PIdx] += (Factor * PI->Cycles);
1558     }
1559   }
1560 }
1561
1562 void SchedBoundary::
1563 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1564   reset();
1565   DAG = dag;
1566   SchedModel = smodel;
1567   Rem = rem;
1568   if (SchedModel->hasInstrSchedModel()) {
1569     ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1570     ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1571   }
1572 }
1573
1574 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1575 /// these "soft stalls" differently than the hard stall cycles based on CPU
1576 /// resources and computed by checkHazard(). A fully in-order model
1577 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1578 /// available for scheduling until they are ready. However, a weaker in-order
1579 /// model may use this for heuristics. For example, if a processor has in-order
1580 /// behavior when reading certain resources, this may come into play.
1581 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1582   if (!SU->isUnbuffered)
1583     return 0;
1584
1585   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1586   if (ReadyCycle > CurrCycle)
1587     return ReadyCycle - CurrCycle;
1588   return 0;
1589 }
1590
1591 /// Compute the next cycle at which the given processor resource can be
1592 /// scheduled.
1593 unsigned SchedBoundary::
1594 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1595   unsigned NextUnreserved = ReservedCycles[PIdx];
1596   // If this resource has never been used, always return cycle zero.
1597   if (NextUnreserved == InvalidCycle)
1598     return 0;
1599   // For bottom-up scheduling add the cycles needed for the current operation.
1600   if (!isTop())
1601     NextUnreserved += Cycles;
1602   return NextUnreserved;
1603 }
1604
1605 /// Does this SU have a hazard within the current instruction group.
1606 ///
1607 /// The scheduler supports two modes of hazard recognition. The first is the
1608 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1609 /// supports highly complicated in-order reservation tables
1610 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1611 ///
1612 /// The second is a streamlined mechanism that checks for hazards based on
1613 /// simple counters that the scheduler itself maintains. It explicitly checks
1614 /// for instruction dispatch limitations, including the number of micro-ops that
1615 /// can dispatch per cycle.
1616 ///
1617 /// TODO: Also check whether the SU must start a new group.
1618 bool SchedBoundary::checkHazard(SUnit *SU) {
1619   if (HazardRec->isEnabled())
1620     return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1621
1622   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1623   if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1624     DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
1625           << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1626     return true;
1627   }
1628   if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1629     const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1630     for (TargetSchedModel::ProcResIter
1631            PI = SchedModel->getWriteProcResBegin(SC),
1632            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1633       if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1634         return true;
1635     }
1636   }
1637   return false;
1638 }
1639
1640 // Find the unscheduled node in ReadySUs with the highest latency.
1641 unsigned SchedBoundary::
1642 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1643   SUnit *LateSU = 0;
1644   unsigned RemLatency = 0;
1645   for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1646        I != E; ++I) {
1647     unsigned L = getUnscheduledLatency(*I);
1648     if (L > RemLatency) {
1649       RemLatency = L;
1650       LateSU = *I;
1651     }
1652   }
1653   if (LateSU) {
1654     DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1655           << LateSU->NodeNum << ") " << RemLatency << "c\n");
1656   }
1657   return RemLatency;
1658 }
1659
1660 // Count resources in this zone and the remaining unscheduled
1661 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1662 // resource index, or zero if the zone is issue limited.
1663 unsigned SchedBoundary::
1664 getOtherResourceCount(unsigned &OtherCritIdx) {
1665   OtherCritIdx = 0;
1666   if (!SchedModel->hasInstrSchedModel())
1667     return 0;
1668
1669   unsigned OtherCritCount = Rem->RemIssueCount
1670     + (RetiredMOps * SchedModel->getMicroOpFactor());
1671   DEBUG(dbgs() << "  " << Available.getName() << " + Remain MOps: "
1672         << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1673   for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1674        PIdx != PEnd; ++PIdx) {
1675     unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1676     if (OtherCount > OtherCritCount) {
1677       OtherCritCount = OtherCount;
1678       OtherCritIdx = PIdx;
1679     }
1680   }
1681   if (OtherCritIdx) {
1682     DEBUG(dbgs() << "  " << Available.getName() << " + Remain CritRes: "
1683           << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1684           << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1685   }
1686   return OtherCritCount;
1687 }
1688
1689 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1690   if (ReadyCycle < MinReadyCycle)
1691     MinReadyCycle = ReadyCycle;
1692
1693   // Check for interlocks first. For the purpose of other heuristics, an
1694   // instruction that cannot issue appears as if it's not in the ReadyQueue.
1695   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1696   if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1697     Pending.push(SU);
1698   else
1699     Available.push(SU);
1700
1701   // Record this node as an immediate dependent of the scheduled node.
1702   NextSUs.insert(SU);
1703 }
1704
1705 void SchedBoundary::releaseTopNode(SUnit *SU) {
1706   if (SU->isScheduled)
1707     return;
1708
1709   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1710        I != E; ++I) {
1711     if (I->isWeak())
1712       continue;
1713     unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1714     unsigned Latency = I->getLatency();
1715 #ifndef NDEBUG
1716     MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1717 #endif
1718     if (SU->TopReadyCycle < PredReadyCycle + Latency)
1719       SU->TopReadyCycle = PredReadyCycle + Latency;
1720   }
1721   releaseNode(SU, SU->TopReadyCycle);
1722 }
1723
1724 void SchedBoundary::releaseBottomNode(SUnit *SU) {
1725   if (SU->isScheduled)
1726     return;
1727
1728   assert(SU->getInstr() && "Scheduled SUnit must have instr");
1729
1730   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1731        I != E; ++I) {
1732     if (I->isWeak())
1733       continue;
1734     unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1735     unsigned Latency = I->getLatency();
1736 #ifndef NDEBUG
1737     MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1738 #endif
1739     if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1740       SU->BotReadyCycle = SuccReadyCycle + Latency;
1741   }
1742   releaseNode(SU, SU->BotReadyCycle);
1743 }
1744
1745 /// Move the boundary of scheduled code by one cycle.
1746 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1747   if (SchedModel->getMicroOpBufferSize() == 0) {
1748     assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1749     if (MinReadyCycle > NextCycle)
1750       NextCycle = MinReadyCycle;
1751   }
1752   // Update the current micro-ops, which will issue in the next cycle.
1753   unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1754   CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1755
1756   // Decrement DependentLatency based on the next cycle.
1757   if ((NextCycle - CurrCycle) > DependentLatency)
1758     DependentLatency = 0;
1759   else
1760     DependentLatency -= (NextCycle - CurrCycle);
1761
1762   if (!HazardRec->isEnabled()) {
1763     // Bypass HazardRec virtual calls.
1764     CurrCycle = NextCycle;
1765   }
1766   else {
1767     // Bypass getHazardType calls in case of long latency.
1768     for (; CurrCycle != NextCycle; ++CurrCycle) {
1769       if (isTop())
1770         HazardRec->AdvanceCycle();
1771       else
1772         HazardRec->RecedeCycle();
1773     }
1774   }
1775   CheckPending = true;
1776   unsigned LFactor = SchedModel->getLatencyFactor();
1777   IsResourceLimited =
1778     (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1779     > (int)LFactor;
1780
1781   DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1782 }
1783
1784 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
1785   ExecutedResCounts[PIdx] += Count;
1786   if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1787     MaxExecutedResCount = ExecutedResCounts[PIdx];
1788 }
1789
1790 /// Add the given processor resource to this scheduled zone.
1791 ///
1792 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1793 /// during which this resource is consumed.
1794 ///
1795 /// \return the next cycle at which the instruction may execute without
1796 /// oversubscribing resources.
1797 unsigned SchedBoundary::
1798 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
1799   unsigned Factor = SchedModel->getResourceFactor(PIdx);
1800   unsigned Count = Factor * Cycles;
1801   DEBUG(dbgs() << "  " << SchedModel->getResourceName(PIdx)
1802         << " +" << Cycles << "x" << Factor << "u\n");
1803
1804   // Update Executed resources counts.
1805   incExecutedResources(PIdx, Count);
1806   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1807   Rem->RemainingCounts[PIdx] -= Count;
1808
1809   // Check if this resource exceeds the current critical resource. If so, it
1810   // becomes the critical resource.
1811   if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1812     ZoneCritResIdx = PIdx;
1813     DEBUG(dbgs() << "  *** Critical resource "
1814           << SchedModel->getResourceName(PIdx) << ": "
1815           << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1816   }
1817   // For reserved resources, record the highest cycle using the resource.
1818   unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1819   if (NextAvailable > CurrCycle) {
1820     DEBUG(dbgs() << "  Resource conflict: "
1821           << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1822           << NextAvailable << "\n");
1823   }
1824   return NextAvailable;
1825 }
1826
1827 /// Move the boundary of scheduled code by one SUnit.
1828 void SchedBoundary::bumpNode(SUnit *SU) {
1829   // Update the reservation table.
1830   if (HazardRec->isEnabled()) {
1831     if (!isTop() && SU->isCall) {
1832       // Calls are scheduled with their preceding instructions. For bottom-up
1833       // scheduling, clear the pipeline state before emitting.
1834       HazardRec->Reset();
1835     }
1836     HazardRec->EmitInstruction(SU);
1837   }
1838   // checkHazard should prevent scheduling multiple instructions per cycle that
1839   // exceed the issue width.
1840   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1841   unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1842   assert(
1843       (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
1844       "Cannot schedule this instruction's MicroOps in the current cycle.");
1845
1846   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1847   DEBUG(dbgs() << "  Ready @" << ReadyCycle << "c\n");
1848
1849   unsigned NextCycle = CurrCycle;
1850   switch (SchedModel->getMicroOpBufferSize()) {
1851   case 0:
1852     assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1853     break;
1854   case 1:
1855     if (ReadyCycle > NextCycle) {
1856       NextCycle = ReadyCycle;
1857       DEBUG(dbgs() << "  *** Stall until: " << ReadyCycle << "\n");
1858     }
1859     break;
1860   default:
1861     // We don't currently model the OOO reorder buffer, so consider all
1862     // scheduled MOps to be "retired". We do loosely model in-order resource
1863     // latency. If this instruction uses an in-order resource, account for any
1864     // likely stall cycles.
1865     if (SU->isUnbuffered && ReadyCycle > NextCycle)
1866       NextCycle = ReadyCycle;
1867     break;
1868   }
1869   RetiredMOps += IncMOps;
1870
1871   // Update resource counts and critical resource.
1872   if (SchedModel->hasInstrSchedModel()) {
1873     unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1874     assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1875     Rem->RemIssueCount -= DecRemIssue;
1876     if (ZoneCritResIdx) {
1877       // Scale scheduled micro-ops for comparing with the critical resource.
1878       unsigned ScaledMOps =
1879         RetiredMOps * SchedModel->getMicroOpFactor();
1880
1881       // If scaled micro-ops are now more than the previous critical resource by
1882       // a full cycle, then micro-ops issue becomes critical.
1883       if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1884           >= (int)SchedModel->getLatencyFactor()) {
1885         ZoneCritResIdx = 0;
1886         DEBUG(dbgs() << "  *** Critical resource NumMicroOps: "
1887               << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1888       }
1889     }
1890     for (TargetSchedModel::ProcResIter
1891            PI = SchedModel->getWriteProcResBegin(SC),
1892            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1893       unsigned RCycle =
1894         countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
1895       if (RCycle > NextCycle)
1896         NextCycle = RCycle;
1897     }
1898     if (SU->hasReservedResource) {
1899       // For reserved resources, record the highest cycle using the resource.
1900       // For top-down scheduling, this is the cycle in which we schedule this
1901       // instruction plus the number of cycles the operations reserves the
1902       // resource. For bottom-up is it simply the instruction's cycle.
1903       for (TargetSchedModel::ProcResIter
1904              PI = SchedModel->getWriteProcResBegin(SC),
1905              PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1906         unsigned PIdx = PI->ProcResourceIdx;
1907         if (SchedModel->getProcResource(PIdx)->BufferSize == 0)
1908           ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
1909       }
1910     }
1911   }
1912   // Update ExpectedLatency and DependentLatency.
1913   unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1914   unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1915   if (SU->getDepth() > TopLatency) {
1916     TopLatency = SU->getDepth();
1917     DEBUG(dbgs() << "  " << Available.getName()
1918           << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1919   }
1920   if (SU->getHeight() > BotLatency) {
1921     BotLatency = SU->getHeight();
1922     DEBUG(dbgs() << "  " << Available.getName()
1923           << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1924   }
1925   // If we stall for any reason, bump the cycle.
1926   if (NextCycle > CurrCycle) {
1927     bumpCycle(NextCycle);
1928   }
1929   else {
1930     // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1931     // resource limited. If a stall occured, bumpCycle does this.
1932     unsigned LFactor = SchedModel->getLatencyFactor();
1933     IsResourceLimited =
1934       (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1935       > (int)LFactor;
1936   }
1937   // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1938   // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1939   // one cycle.  Since we commonly reach the max MOps here, opportunistically
1940   // bump the cycle to avoid uselessly checking everything in the readyQ.
1941   CurrMOps += IncMOps;
1942   while (CurrMOps >= SchedModel->getIssueWidth()) {
1943     bumpCycle(++NextCycle);
1944     DEBUG(dbgs() << "  *** Max MOps " << CurrMOps
1945           << " at cycle " << CurrCycle << '\n');
1946   }
1947   DEBUG(dumpScheduledState());
1948 }
1949
1950 /// Release pending ready nodes in to the available queue. This makes them
1951 /// visible to heuristics.
1952 void SchedBoundary::releasePending() {
1953   // If the available queue is empty, it is safe to reset MinReadyCycle.
1954   if (Available.empty())
1955     MinReadyCycle = UINT_MAX;
1956
1957   // Check to see if any of the pending instructions are ready to issue.  If
1958   // so, add them to the available queue.
1959   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1960   for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1961     SUnit *SU = *(Pending.begin()+i);
1962     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1963
1964     if (ReadyCycle < MinReadyCycle)
1965       MinReadyCycle = ReadyCycle;
1966
1967     if (!IsBuffered && ReadyCycle > CurrCycle)
1968       continue;
1969
1970     if (checkHazard(SU))
1971       continue;
1972
1973     Available.push(SU);
1974     Pending.remove(Pending.begin()+i);
1975     --i; --e;
1976   }
1977   DEBUG(if (!Pending.empty()) Pending.dump());
1978   CheckPending = false;
1979 }
1980
1981 /// Remove SU from the ready set for this boundary.
1982 void SchedBoundary::removeReady(SUnit *SU) {
1983   if (Available.isInQueue(SU))
1984     Available.remove(Available.find(SU));
1985   else {
1986     assert(Pending.isInQueue(SU) && "bad ready count");
1987     Pending.remove(Pending.find(SU));
1988   }
1989 }
1990
1991 /// If this queue only has one ready candidate, return it. As a side effect,
1992 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1993 /// one node is ready. If multiple instructions are ready, return NULL.
1994 SUnit *SchedBoundary::pickOnlyChoice() {
1995   if (CheckPending)
1996     releasePending();
1997
1998   if (CurrMOps > 0) {
1999     // Defer any ready instrs that now have a hazard.
2000     for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2001       if (checkHazard(*I)) {
2002         Pending.push(*I);
2003         I = Available.remove(I);
2004         continue;
2005       }
2006       ++I;
2007     }
2008   }
2009   for (unsigned i = 0; Available.empty(); ++i) {
2010     assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
2011            "permanent hazard"); (void)i;
2012     bumpCycle(CurrCycle + 1);
2013     releasePending();
2014   }
2015   if (Available.size() == 1)
2016     return *Available.begin();
2017   return NULL;
2018 }
2019
2020 #ifndef NDEBUG
2021 // This is useful information to dump after bumpNode.
2022 // Note that the Queue contents are more useful before pickNodeFromQueue.
2023 void SchedBoundary::dumpScheduledState() {
2024   unsigned ResFactor;
2025   unsigned ResCount;
2026   if (ZoneCritResIdx) {
2027     ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2028     ResCount = getResourceCount(ZoneCritResIdx);
2029   }
2030   else {
2031     ResFactor = SchedModel->getMicroOpFactor();
2032     ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2033   }
2034   unsigned LFactor = SchedModel->getLatencyFactor();
2035   dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2036          << "  Retired: " << RetiredMOps;
2037   dbgs() << "\n  Executed: " << getExecutedCount() / LFactor << "c";
2038   dbgs() << "\n  Critical: " << ResCount / LFactor << "c, "
2039          << ResCount / ResFactor << " "
2040          << SchedModel->getResourceName(ZoneCritResIdx)
2041          << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
2042          << (IsResourceLimited ? "  - Resource" : "  - Latency")
2043          << " limited.\n";
2044 }
2045 #endif
2046
2047 //===----------------------------------------------------------------------===//
2048 // GenericScheduler - Implementation of the generic MachineSchedStrategy.
2049 //===----------------------------------------------------------------------===//
2050
2051 namespace {
2052 /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
2053 /// the schedule.
2054 class GenericScheduler : public MachineSchedStrategy {
2055 public:
2056   /// Represent the type of SchedCandidate found within a single queue.
2057   /// pickNodeBidirectional depends on these listed by decreasing priority.
2058   enum CandReason {
2059     NoCand, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak, RegMax,
2060     ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
2061     TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
2062
2063 #ifndef NDEBUG
2064   static const char *getReasonStr(GenericScheduler::CandReason Reason);
2065 #endif
2066
2067   /// Policy for scheduling the next instruction in the candidate's zone.
2068   struct CandPolicy {
2069     bool ReduceLatency;
2070     unsigned ReduceResIdx;
2071     unsigned DemandResIdx;
2072
2073     CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
2074   };
2075
2076   /// Status of an instruction's critical resource consumption.
2077   struct SchedResourceDelta {
2078     // Count critical resources in the scheduled region required by SU.
2079     unsigned CritResources;
2080
2081     // Count critical resources from another region consumed by SU.
2082     unsigned DemandedResources;
2083
2084     SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
2085
2086     bool operator==(const SchedResourceDelta &RHS) const {
2087       return CritResources == RHS.CritResources
2088         && DemandedResources == RHS.DemandedResources;
2089     }
2090     bool operator!=(const SchedResourceDelta &RHS) const {
2091       return !operator==(RHS);
2092     }
2093   };
2094
2095   /// Store the state used by GenericScheduler heuristics, required for the
2096   /// lifetime of one invocation of pickNode().
2097   struct SchedCandidate {
2098     CandPolicy Policy;
2099
2100     // The best SUnit candidate.
2101     SUnit *SU;
2102
2103     // The reason for this candidate.
2104     CandReason Reason;
2105
2106     // Set of reasons that apply to multiple candidates.
2107     uint32_t RepeatReasonSet;
2108
2109     // Register pressure values for the best candidate.
2110     RegPressureDelta RPDelta;
2111
2112     // Critical resource consumption of the best candidate.
2113     SchedResourceDelta ResDelta;
2114
2115     SchedCandidate(const CandPolicy &policy)
2116       : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
2117
2118     bool isValid() const { return SU; }
2119
2120     // Copy the status of another candidate without changing policy.
2121     void setBest(SchedCandidate &Best) {
2122       assert(Best.Reason != NoCand && "uninitialized Sched candidate");
2123       SU = Best.SU;
2124       Reason = Best.Reason;
2125       RPDelta = Best.RPDelta;
2126       ResDelta = Best.ResDelta;
2127     }
2128
2129     bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
2130     void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
2131
2132     void initResourceDelta(const ScheduleDAGMILive *DAG,
2133                            const TargetSchedModel *SchedModel);
2134   };
2135
2136 private:
2137   const MachineSchedContext *Context;
2138   ScheduleDAGMILive *DAG;
2139   const TargetSchedModel *SchedModel;
2140   const TargetRegisterInfo *TRI;
2141
2142   // State of the top and bottom scheduled instruction boundaries.
2143   SchedRemainder Rem;
2144   SchedBoundary Top;
2145   SchedBoundary Bot;
2146
2147   MachineSchedPolicy RegionPolicy;
2148 public:
2149   GenericScheduler(const MachineSchedContext *C):
2150     Context(C), DAG(0), SchedModel(0), TRI(0),
2151     Top(SchedBoundary::TopQID, "TopQ"), Bot(SchedBoundary::BotQID, "BotQ") {}
2152
2153   virtual void initPolicy(MachineBasicBlock::iterator Begin,
2154                           MachineBasicBlock::iterator End,
2155                           unsigned NumRegionInstrs);
2156
2157   bool shouldTrackPressure() const { return RegionPolicy.ShouldTrackPressure; }
2158
2159   virtual void initialize(ScheduleDAGMI *dag);
2160
2161   virtual SUnit *pickNode(bool &IsTopNode);
2162
2163   virtual void schedNode(SUnit *SU, bool IsTopNode);
2164
2165   virtual void releaseTopNode(SUnit *SU) { Top.releaseTopNode(SU); }
2166
2167   virtual void releaseBottomNode(SUnit *SU) { Bot.releaseBottomNode(SU); }
2168
2169   virtual void registerRoots();
2170
2171 protected:
2172   void checkAcyclicLatency();
2173
2174   void setPolicy(CandPolicy &Policy, SchedBoundary &CurrZone,
2175                  SchedBoundary &OtherZone);
2176
2177   void tryCandidate(SchedCandidate &Cand,
2178                     SchedCandidate &TryCand,
2179                     SchedBoundary &Zone,
2180                     const RegPressureTracker &RPTracker,
2181                     RegPressureTracker &TempTracker);
2182
2183   SUnit *pickNodeBidirectional(bool &IsTopNode);
2184
2185   void pickNodeFromQueue(SchedBoundary &Zone,
2186                          const RegPressureTracker &RPTracker,
2187                          SchedCandidate &Candidate);
2188
2189   void reschedulePhysRegCopies(SUnit *SU, bool isTop);
2190
2191 #ifndef NDEBUG
2192   void traceCandidate(const SchedCandidate &Cand);
2193 #endif
2194 };
2195 } // namespace
2196
2197 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2198   assert(dag->hasVRegLiveness() &&
2199          "(PreRA)GenericScheduler needs vreg liveness");
2200   DAG = static_cast<ScheduleDAGMILive*>(dag);
2201   SchedModel = DAG->getSchedModel();
2202   TRI = DAG->TRI;
2203
2204   Rem.init(DAG, SchedModel);
2205   Top.init(DAG, SchedModel, &Rem);
2206   Bot.init(DAG, SchedModel, &Rem);
2207
2208   // Initialize resource counts.
2209
2210   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2211   // are disabled, then these HazardRecs will be disabled.
2212   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2213   const TargetMachine &TM = DAG->MF.getTarget();
2214   if (!Top.HazardRec) {
2215     Top.HazardRec =
2216       TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2217   }
2218   if (!Bot.HazardRec) {
2219     Bot.HazardRec =
2220       TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2221   }
2222 }
2223
2224 /// Initialize the per-region scheduling policy.
2225 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2226                                   MachineBasicBlock::iterator End,
2227                                   unsigned NumRegionInstrs) {
2228   const TargetMachine &TM = Context->MF->getTarget();
2229
2230   // Avoid setting up the register pressure tracker for small regions to save
2231   // compile time. As a rough heuristic, only track pressure when the number of
2232   // schedulable instructions exceeds half the integer register file.
2233   unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2234     TM.getTargetLowering()->getRegClassFor(MVT::i32));
2235
2236   RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2237
2238   // For generic targets, we default to bottom-up, because it's simpler and more
2239   // compile-time optimizations have been implemented in that direction.
2240   RegionPolicy.OnlyBottomUp = true;
2241
2242   // Allow the subtarget to override default policy.
2243   const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2244   ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2245
2246   // After subtarget overrides, apply command line options.
2247   if (!EnableRegPressure)
2248     RegionPolicy.ShouldTrackPressure = false;
2249
2250   // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2251   // e.g. -misched-bottomup=false allows scheduling in both directions.
2252   assert((!ForceTopDown || !ForceBottomUp) &&
2253          "-misched-topdown incompatible with -misched-bottomup");
2254   if (ForceBottomUp.getNumOccurrences() > 0) {
2255     RegionPolicy.OnlyBottomUp = ForceBottomUp;
2256     if (RegionPolicy.OnlyBottomUp)
2257       RegionPolicy.OnlyTopDown = false;
2258   }
2259   if (ForceTopDown.getNumOccurrences() > 0) {
2260     RegionPolicy.OnlyTopDown = ForceTopDown;
2261     if (RegionPolicy.OnlyTopDown)
2262       RegionPolicy.OnlyBottomUp = false;
2263   }
2264 }
2265
2266 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2267 /// critical path by more cycles than it takes to drain the instruction buffer.
2268 /// We estimate an upper bounds on in-flight instructions as:
2269 ///
2270 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2271 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2272 /// InFlightResources = InFlightIterations * LoopResources
2273 ///
2274 /// TODO: Check execution resources in addition to IssueCount.
2275 void GenericScheduler::checkAcyclicLatency() {
2276   if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2277     return;
2278
2279   // Scaled number of cycles per loop iteration.
2280   unsigned IterCount =
2281     std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2282              Rem.RemIssueCount);
2283   // Scaled acyclic critical path.
2284   unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2285   // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2286   unsigned InFlightCount =
2287     (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2288   unsigned BufferLimit =
2289     SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2290
2291   Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2292
2293   DEBUG(dbgs() << "IssueCycles="
2294         << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2295         << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2296         << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2297         << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2298         << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2299         if (Rem.IsAcyclicLatencyLimited)
2300           dbgs() << "  ACYCLIC LATENCY LIMIT\n");
2301 }
2302
2303 void GenericScheduler::registerRoots() {
2304   Rem.CriticalPath = DAG->ExitSU.getDepth();
2305
2306   // Some roots may not feed into ExitSU. Check all of them in case.
2307   for (std::vector<SUnit*>::const_iterator
2308          I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2309     if ((*I)->getDepth() > Rem.CriticalPath)
2310       Rem.CriticalPath = (*I)->getDepth();
2311   }
2312   DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2313
2314   if (EnableCyclicPath) {
2315     Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2316     checkAcyclicLatency();
2317   }
2318 }
2319
2320 /// Set the CandPolicy given a scheduling zone given the current resources and
2321 /// latencies inside and outside the zone.
2322 void GenericScheduler::setPolicy(CandPolicy &Policy, SchedBoundary &CurrZone,
2323                                  SchedBoundary &OtherZone) {
2324   // Apply preemptive heuristics based on the the total latency and resources
2325   // inside and outside this zone. Potential stalls should be considered before
2326   // following this policy.
2327
2328   // Compute remaining latency. We need this both to determine whether the
2329   // overall schedule has become latency-limited and whether the instructions
2330   // outside this zone are resource or latency limited.
2331   //
2332   // The "dependent" latency is updated incrementally during scheduling as the
2333   // max height/depth of scheduled nodes minus the cycles since it was
2334   // scheduled:
2335   //   DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2336   //
2337   // The "independent" latency is the max ready queue depth:
2338   //   ILat = max N.depth for N in Available|Pending
2339   //
2340   // RemainingLatency is the greater of independent and dependent latency.
2341   unsigned RemLatency = CurrZone.getDependentLatency();
2342   RemLatency = std::max(RemLatency,
2343                         CurrZone.findMaxLatency(CurrZone.Available.elements()));
2344   RemLatency = std::max(RemLatency,
2345                         CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2346
2347   // Compute the critical resource outside the zone.
2348   unsigned OtherCritIdx;
2349   unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
2350
2351   bool OtherResLimited = false;
2352   if (SchedModel->hasInstrSchedModel()) {
2353     unsigned LFactor = SchedModel->getLatencyFactor();
2354     OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2355   }
2356   if (!OtherResLimited
2357       && (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2358     Policy.ReduceLatency |= true;
2359     DEBUG(dbgs() << "  " << CurrZone.Available.getName() << " RemainingLatency "
2360           << RemLatency << " + " << CurrZone.getCurrCycle() << "c > CritPath "
2361           << Rem.CriticalPath << "\n");
2362   }
2363   // If the same resource is limiting inside and outside the zone, do nothing.
2364   if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2365     return;
2366
2367   DEBUG(
2368     if (CurrZone.isResourceLimited()) {
2369       dbgs() << "  " << CurrZone.Available.getName() << " ResourceLimited: "
2370              << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2371              << "\n";
2372     }
2373     if (OtherResLimited)
2374       dbgs() << "  RemainingLimit: "
2375              << SchedModel->getResourceName(OtherCritIdx) << "\n";
2376     if (!CurrZone.isResourceLimited() && !OtherResLimited)
2377       dbgs() << "  Latency limited both directions.\n");
2378
2379   if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2380     Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2381
2382   if (OtherResLimited)
2383     Policy.DemandResIdx = OtherCritIdx;
2384 }
2385
2386 void GenericScheduler::SchedCandidate::
2387 initResourceDelta(const ScheduleDAGMILive *DAG,
2388                   const TargetSchedModel *SchedModel) {
2389   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2390     return;
2391
2392   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2393   for (TargetSchedModel::ProcResIter
2394          PI = SchedModel->getWriteProcResBegin(SC),
2395          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2396     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2397       ResDelta.CritResources += PI->Cycles;
2398     if (PI->ProcResourceIdx == Policy.DemandResIdx)
2399       ResDelta.DemandedResources += PI->Cycles;
2400   }
2401 }
2402
2403 /// Return true if this heuristic determines order.
2404 static bool tryLess(int TryVal, int CandVal,
2405                     GenericScheduler::SchedCandidate &TryCand,
2406                     GenericScheduler::SchedCandidate &Cand,
2407                     GenericScheduler::CandReason Reason) {
2408   if (TryVal < CandVal) {
2409     TryCand.Reason = Reason;
2410     return true;
2411   }
2412   if (TryVal > CandVal) {
2413     if (Cand.Reason > Reason)
2414       Cand.Reason = Reason;
2415     return true;
2416   }
2417   Cand.setRepeat(Reason);
2418   return false;
2419 }
2420
2421 static bool tryGreater(int TryVal, int CandVal,
2422                        GenericScheduler::SchedCandidate &TryCand,
2423                        GenericScheduler::SchedCandidate &Cand,
2424                        GenericScheduler::CandReason Reason) {
2425   if (TryVal > CandVal) {
2426     TryCand.Reason = Reason;
2427     return true;
2428   }
2429   if (TryVal < CandVal) {
2430     if (Cand.Reason > Reason)
2431       Cand.Reason = Reason;
2432     return true;
2433   }
2434   Cand.setRepeat(Reason);
2435   return false;
2436 }
2437
2438 static bool tryPressure(const PressureChange &TryP,
2439                         const PressureChange &CandP,
2440                         GenericScheduler::SchedCandidate &TryCand,
2441                         GenericScheduler::SchedCandidate &Cand,
2442                         GenericScheduler::CandReason Reason) {
2443   int TryRank = TryP.getPSetOrMax();
2444   int CandRank = CandP.getPSetOrMax();
2445   // If both candidates affect the same set, go with the smallest increase.
2446   if (TryRank == CandRank) {
2447     return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2448                    Reason);
2449   }
2450   // If one candidate decreases and the other increases, go with it.
2451   // Invalid candidates have UnitInc==0.
2452   if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2453               Reason)) {
2454     return true;
2455   }
2456   // If the candidates are decreasing pressure, reverse priority.
2457   if (TryP.getUnitInc() < 0)
2458     std::swap(TryRank, CandRank);
2459   return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2460 }
2461
2462 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2463   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2464 }
2465
2466 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2467 /// their physreg def/use.
2468 ///
2469 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2470 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2471 /// with the operation that produces or consumes the physreg. We'll do this when
2472 /// regalloc has support for parallel copies.
2473 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2474   const MachineInstr *MI = SU->getInstr();
2475   if (!MI->isCopy())
2476     return 0;
2477
2478   unsigned ScheduledOper = isTop ? 1 : 0;
2479   unsigned UnscheduledOper = isTop ? 0 : 1;
2480   // If we have already scheduled the physreg produce/consumer, immediately
2481   // schedule the copy.
2482   if (TargetRegisterInfo::isPhysicalRegister(
2483         MI->getOperand(ScheduledOper).getReg()))
2484     return 1;
2485   // If the physreg is at the boundary, defer it. Otherwise schedule it
2486   // immediately to free the dependent. We can hoist the copy later.
2487   bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2488   if (TargetRegisterInfo::isPhysicalRegister(
2489         MI->getOperand(UnscheduledOper).getReg()))
2490     return AtBoundary ? -1 : 1;
2491   return 0;
2492 }
2493
2494 static bool tryLatency(GenericScheduler::SchedCandidate &TryCand,
2495                        GenericScheduler::SchedCandidate &Cand,
2496                        SchedBoundary &Zone) {
2497   if (Zone.isTop()) {
2498     if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2499       if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2500                   TryCand, Cand, GenericScheduler::TopDepthReduce))
2501         return true;
2502     }
2503     if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2504                    TryCand, Cand, GenericScheduler::TopPathReduce))
2505       return true;
2506   }
2507   else {
2508     if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2509       if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2510                   TryCand, Cand, GenericScheduler::BotHeightReduce))
2511         return true;
2512     }
2513     if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2514                    TryCand, Cand, GenericScheduler::BotPathReduce))
2515       return true;
2516   }
2517   return false;
2518 }
2519
2520 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2521 /// hierarchical. This may be more efficient than a graduated cost model because
2522 /// we don't need to evaluate all aspects of the model for each node in the
2523 /// queue. But it's really done to make the heuristics easier to debug and
2524 /// statistically analyze.
2525 ///
2526 /// \param Cand provides the policy and current best candidate.
2527 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2528 /// \param Zone describes the scheduled zone that we are extending.
2529 /// \param RPTracker describes reg pressure within the scheduled zone.
2530 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2531 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2532                                     SchedCandidate &TryCand,
2533                                     SchedBoundary &Zone,
2534                                     const RegPressureTracker &RPTracker,
2535                                     RegPressureTracker &TempTracker) {
2536
2537   if (DAG->isTrackingPressure()) {
2538     // Always initialize TryCand's RPDelta.
2539     if (Zone.isTop()) {
2540       TempTracker.getMaxDownwardPressureDelta(
2541         TryCand.SU->getInstr(),
2542         TryCand.RPDelta,
2543         DAG->getRegionCriticalPSets(),
2544         DAG->getRegPressure().MaxSetPressure);
2545     }
2546     else {
2547       if (VerifyScheduling) {
2548         TempTracker.getMaxUpwardPressureDelta(
2549           TryCand.SU->getInstr(),
2550           &DAG->getPressureDiff(TryCand.SU),
2551           TryCand.RPDelta,
2552           DAG->getRegionCriticalPSets(),
2553           DAG->getRegPressure().MaxSetPressure);
2554       }
2555       else {
2556         RPTracker.getUpwardPressureDelta(
2557           TryCand.SU->getInstr(),
2558           DAG->getPressureDiff(TryCand.SU),
2559           TryCand.RPDelta,
2560           DAG->getRegionCriticalPSets(),
2561           DAG->getRegPressure().MaxSetPressure);
2562       }
2563     }
2564   }
2565   DEBUG(if (TryCand.RPDelta.Excess.isValid())
2566           dbgs() << "  SU(" << TryCand.SU->NodeNum << ") "
2567                  << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2568                  << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
2569
2570   // Initialize the candidate if needed.
2571   if (!Cand.isValid()) {
2572     TryCand.Reason = NodeOrder;
2573     return;
2574   }
2575
2576   if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2577                  biasPhysRegCopy(Cand.SU, Zone.isTop()),
2578                  TryCand, Cand, PhysRegCopy))
2579     return;
2580
2581   // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2582   // invalid; convert it to INT_MAX to give it lowest priority.
2583   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2584                                                Cand.RPDelta.Excess,
2585                                                TryCand, Cand, RegExcess))
2586     return;
2587
2588   // Avoid increasing the max critical pressure in the scheduled region.
2589   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2590                                                Cand.RPDelta.CriticalMax,
2591                                                TryCand, Cand, RegCritical))
2592     return;
2593
2594   // For loops that are acyclic path limited, aggressively schedule for latency.
2595   // This can result in very long dependence chains scheduled in sequence, so
2596   // once every cycle (when CurrMOps == 0), switch to normal heuristics.
2597   if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
2598       && tryLatency(TryCand, Cand, Zone))
2599     return;
2600
2601   // Prioritize instructions that read unbuffered resources by stall cycles.
2602   if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2603               Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2604     return;
2605
2606   // Keep clustered nodes together to encourage downstream peephole
2607   // optimizations which may reduce resource requirements.
2608   //
2609   // This is a best effort to set things up for a post-RA pass. Optimizations
2610   // like generating loads of multiple registers should ideally be done within
2611   // the scheduler pass by combining the loads during DAG postprocessing.
2612   const SUnit *NextClusterSU =
2613     Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2614   if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2615                  TryCand, Cand, Cluster))
2616     return;
2617
2618   // Weak edges are for clustering and other constraints.
2619   if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2620               getWeakLeft(Cand.SU, Zone.isTop()),
2621               TryCand, Cand, Weak)) {
2622     return;
2623   }
2624   // Avoid increasing the max pressure of the entire region.
2625   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2626                                                Cand.RPDelta.CurrentMax,
2627                                                TryCand, Cand, RegMax))
2628     return;
2629
2630   // Avoid critical resource consumption and balance the schedule.
2631   TryCand.initResourceDelta(DAG, SchedModel);
2632   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2633               TryCand, Cand, ResourceReduce))
2634     return;
2635   if (tryGreater(TryCand.ResDelta.DemandedResources,
2636                  Cand.ResDelta.DemandedResources,
2637                  TryCand, Cand, ResourceDemand))
2638     return;
2639
2640   // Avoid serializing long latency dependence chains.
2641   // For acyclic path limited loops, latency was already checked above.
2642   if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2643       && tryLatency(TryCand, Cand, Zone)) {
2644     return;
2645   }
2646
2647   // Prefer immediate defs/users of the last scheduled instruction. This is a
2648   // local pressure avoidance strategy that also makes the machine code
2649   // readable.
2650   if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
2651                  TryCand, Cand, NextDefUse))
2652     return;
2653
2654   // Fall through to original instruction order.
2655   if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2656       || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2657     TryCand.Reason = NodeOrder;
2658   }
2659 }
2660
2661 #ifndef NDEBUG
2662 const char *GenericScheduler::getReasonStr(
2663   GenericScheduler::CandReason Reason) {
2664   switch (Reason) {
2665   case NoCand:         return "NOCAND    ";
2666   case PhysRegCopy:    return "PREG-COPY";
2667   case RegExcess:      return "REG-EXCESS";
2668   case RegCritical:    return "REG-CRIT  ";
2669   case Stall:          return "STALL     ";
2670   case Cluster:        return "CLUSTER   ";
2671   case Weak:           return "WEAK      ";
2672   case RegMax:         return "REG-MAX   ";
2673   case ResourceReduce: return "RES-REDUCE";
2674   case ResourceDemand: return "RES-DEMAND";
2675   case TopDepthReduce: return "TOP-DEPTH ";
2676   case TopPathReduce:  return "TOP-PATH  ";
2677   case BotHeightReduce:return "BOT-HEIGHT";
2678   case BotPathReduce:  return "BOT-PATH  ";
2679   case NextDefUse:     return "DEF-USE   ";
2680   case NodeOrder:      return "ORDER     ";
2681   };
2682   llvm_unreachable("Unknown reason!");
2683 }
2684
2685 void GenericScheduler::traceCandidate(const SchedCandidate &Cand) {
2686   PressureChange P;
2687   unsigned ResIdx = 0;
2688   unsigned Latency = 0;
2689   switch (Cand.Reason) {
2690   default:
2691     break;
2692   case RegExcess:
2693     P = Cand.RPDelta.Excess;
2694     break;
2695   case RegCritical:
2696     P = Cand.RPDelta.CriticalMax;
2697     break;
2698   case RegMax:
2699     P = Cand.RPDelta.CurrentMax;
2700     break;
2701   case ResourceReduce:
2702     ResIdx = Cand.Policy.ReduceResIdx;
2703     break;
2704   case ResourceDemand:
2705     ResIdx = Cand.Policy.DemandResIdx;
2706     break;
2707   case TopDepthReduce:
2708     Latency = Cand.SU->getDepth();
2709     break;
2710   case TopPathReduce:
2711     Latency = Cand.SU->getHeight();
2712     break;
2713   case BotHeightReduce:
2714     Latency = Cand.SU->getHeight();
2715     break;
2716   case BotPathReduce:
2717     Latency = Cand.SU->getDepth();
2718     break;
2719   }
2720   dbgs() << "  SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2721   if (P.isValid())
2722     dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2723            << ":" << P.getUnitInc() << " ";
2724   else
2725     dbgs() << "      ";
2726   if (ResIdx)
2727     dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2728   else
2729     dbgs() << "         ";
2730   if (Latency)
2731     dbgs() << " " << Latency << " cycles ";
2732   else
2733     dbgs() << "          ";
2734   dbgs() << '\n';
2735 }
2736 #endif
2737
2738 /// Pick the best candidate from the queue.
2739 ///
2740 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2741 /// DAG building. To adjust for the current scheduling location we need to
2742 /// maintain the number of vreg uses remaining to be top-scheduled.
2743 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2744                                          const RegPressureTracker &RPTracker,
2745                                          SchedCandidate &Cand) {
2746   ReadyQueue &Q = Zone.Available;
2747
2748   DEBUG(Q.dump());
2749
2750   // getMaxPressureDelta temporarily modifies the tracker.
2751   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2752
2753   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2754
2755     SchedCandidate TryCand(Cand.Policy);
2756     TryCand.SU = *I;
2757     tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2758     if (TryCand.Reason != NoCand) {
2759       // Initialize resource delta if needed in case future heuristics query it.
2760       if (TryCand.ResDelta == SchedResourceDelta())
2761         TryCand.initResourceDelta(DAG, SchedModel);
2762       Cand.setBest(TryCand);
2763       DEBUG(traceCandidate(Cand));
2764     }
2765   }
2766 }
2767
2768 static void tracePick(const GenericScheduler::SchedCandidate &Cand,
2769                       bool IsTop) {
2770   DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2771         << GenericScheduler::getReasonStr(Cand.Reason) << '\n');
2772 }
2773
2774 /// Pick the best candidate node from either the top or bottom queue.
2775 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2776   // Schedule as far as possible in the direction of no choice. This is most
2777   // efficient, but also provides the best heuristics for CriticalPSets.
2778   if (SUnit *SU = Bot.pickOnlyChoice()) {
2779     IsTopNode = false;
2780     DEBUG(dbgs() << "Pick Bot NOCAND\n");
2781     return SU;
2782   }
2783   if (SUnit *SU = Top.pickOnlyChoice()) {
2784     IsTopNode = true;
2785     DEBUG(dbgs() << "Pick Top NOCAND\n");
2786     return SU;
2787   }
2788   CandPolicy NoPolicy;
2789   SchedCandidate BotCand(NoPolicy);
2790   SchedCandidate TopCand(NoPolicy);
2791   // Set the bottom-up policy based on the state of the current bottom zone and
2792   // the instructions outside the zone, including the top zone.
2793   setPolicy(BotCand.Policy, Bot, Top);
2794   // Set the top-down policy based on the state of the current top zone and
2795   // the instructions outside the zone, including the bottom zone.
2796   setPolicy(TopCand.Policy, Top, Bot);
2797
2798   // Prefer bottom scheduling when heuristics are silent.
2799   pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2800   assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2801
2802   // If either Q has a single candidate that provides the least increase in
2803   // Excess pressure, we can immediately schedule from that Q.
2804   //
2805   // RegionCriticalPSets summarizes the pressure within the scheduled region and
2806   // affects picking from either Q. If scheduling in one direction must
2807   // increase pressure for one of the excess PSets, then schedule in that
2808   // direction first to provide more freedom in the other direction.
2809   if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2810       || (BotCand.Reason == RegCritical
2811           && !BotCand.isRepeat(RegCritical)))
2812   {
2813     IsTopNode = false;
2814     tracePick(BotCand, IsTopNode);
2815     return BotCand.SU;
2816   }
2817   // Check if the top Q has a better candidate.
2818   pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2819   assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2820
2821   // Choose the queue with the most important (lowest enum) reason.
2822   if (TopCand.Reason < BotCand.Reason) {
2823     IsTopNode = true;
2824     tracePick(TopCand, IsTopNode);
2825     return TopCand.SU;
2826   }
2827   // Otherwise prefer the bottom candidate, in node order if all else failed.
2828   IsTopNode = false;
2829   tracePick(BotCand, IsTopNode);
2830   return BotCand.SU;
2831 }
2832
2833 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2834 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2835   if (DAG->top() == DAG->bottom()) {
2836     assert(Top.Available.empty() && Top.Pending.empty() &&
2837            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2838     return NULL;
2839   }
2840   SUnit *SU;
2841   do {
2842     if (RegionPolicy.OnlyTopDown) {
2843       SU = Top.pickOnlyChoice();
2844       if (!SU) {
2845         CandPolicy NoPolicy;
2846         SchedCandidate TopCand(NoPolicy);
2847         pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2848         assert(TopCand.Reason != NoCand && "failed to find a candidate");
2849         tracePick(TopCand, true);
2850         SU = TopCand.SU;
2851       }
2852       IsTopNode = true;
2853     }
2854     else if (RegionPolicy.OnlyBottomUp) {
2855       SU = Bot.pickOnlyChoice();
2856       if (!SU) {
2857         CandPolicy NoPolicy;
2858         SchedCandidate BotCand(NoPolicy);
2859         pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2860         assert(BotCand.Reason != NoCand && "failed to find a candidate");
2861         tracePick(BotCand, false);
2862         SU = BotCand.SU;
2863       }
2864       IsTopNode = false;
2865     }
2866     else {
2867       SU = pickNodeBidirectional(IsTopNode);
2868     }
2869   } while (SU->isScheduled);
2870
2871   if (SU->isTopReady())
2872     Top.removeReady(SU);
2873   if (SU->isBottomReady())
2874     Bot.removeReady(SU);
2875
2876   DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2877   return SU;
2878 }
2879
2880 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2881
2882   MachineBasicBlock::iterator InsertPos = SU->getInstr();
2883   if (!isTop)
2884     ++InsertPos;
2885   SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2886
2887   // Find already scheduled copies with a single physreg dependence and move
2888   // them just above the scheduled instruction.
2889   for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2890        I != E; ++I) {
2891     if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2892       continue;
2893     SUnit *DepSU = I->getSUnit();
2894     if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2895       continue;
2896     MachineInstr *Copy = DepSU->getInstr();
2897     if (!Copy->isCopy())
2898       continue;
2899     DEBUG(dbgs() << "  Rescheduling physreg copy ";
2900           I->getSUnit()->dump(DAG));
2901     DAG->moveInstruction(Copy, InsertPos);
2902   }
2903 }
2904
2905 /// Update the scheduler's state after scheduling a node. This is the same node
2906 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to update
2907 /// it's state based on the current cycle before MachineSchedStrategy does.
2908 ///
2909 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2910 /// them here. See comments in biasPhysRegCopy.
2911 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2912   if (IsTopNode) {
2913     SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2914     Top.bumpNode(SU);
2915     if (SU->hasPhysRegUses)
2916       reschedulePhysRegCopies(SU, true);
2917   }
2918   else {
2919     SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
2920     Bot.bumpNode(SU);
2921     if (SU->hasPhysRegDefs)
2922       reschedulePhysRegCopies(SU, false);
2923   }
2924 }
2925
2926 /// Create a generic scheduler with no DAG mutation passes.
2927 static ScheduleDAGInstrs *createRawGenericSched(MachineSchedContext *C) {
2928   return new ScheduleDAGMILive(C, new GenericScheduler(C));
2929 }
2930
2931 /// Create the standard converging machine scheduler. This will be used as the
2932 /// default scheduler if the target does not set a default.
2933 static ScheduleDAGInstrs *createGenericSched(MachineSchedContext *C) {
2934   ScheduleDAGMILive *DAG =
2935     static_cast<ScheduleDAGMILive*>(createRawGenericSched(C));
2936   // Register DAG post-processors.
2937   //
2938   // FIXME: extend the mutation API to allow earlier mutations to instantiate
2939   // data and pass it to later mutations. Have a single mutation that gathers
2940   // the interesting nodes in one pass.
2941   DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
2942   if (EnableLoadCluster && DAG->TII->enableClusterLoads())
2943     DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2944   if (EnableMacroFusion)
2945     DAG->addMutation(new MacroFusion(DAG->TII));
2946   return DAG;
2947 }
2948 static MachineSchedRegistry
2949 GenericSchedRegistry("converge", "Standard converging scheduler.",
2950                      createGenericSched);
2951
2952 //===----------------------------------------------------------------------===//
2953 // ILP Scheduler. Currently for experimental analysis of heuristics.
2954 //===----------------------------------------------------------------------===//
2955
2956 namespace {
2957 /// \brief Order nodes by the ILP metric.
2958 struct ILPOrder {
2959   const SchedDFSResult *DFSResult;
2960   const BitVector *ScheduledTrees;
2961   bool MaximizeILP;
2962
2963   ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2964
2965   /// \brief Apply a less-than relation on node priority.
2966   ///
2967   /// (Return true if A comes after B in the Q.)
2968   bool operator()(const SUnit *A, const SUnit *B) const {
2969     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2970     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2971     if (SchedTreeA != SchedTreeB) {
2972       // Unscheduled trees have lower priority.
2973       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2974         return ScheduledTrees->test(SchedTreeB);
2975
2976       // Trees with shallower connections have have lower priority.
2977       if (DFSResult->getSubtreeLevel(SchedTreeA)
2978           != DFSResult->getSubtreeLevel(SchedTreeB)) {
2979         return DFSResult->getSubtreeLevel(SchedTreeA)
2980           < DFSResult->getSubtreeLevel(SchedTreeB);
2981       }
2982     }
2983     if (MaximizeILP)
2984       return DFSResult->getILP(A) < DFSResult->getILP(B);
2985     else
2986       return DFSResult->getILP(A) > DFSResult->getILP(B);
2987   }
2988 };
2989
2990 /// \brief Schedule based on the ILP metric.
2991 class ILPScheduler : public MachineSchedStrategy {
2992   ScheduleDAGMILive *DAG;
2993   ILPOrder Cmp;
2994
2995   std::vector<SUnit*> ReadyQ;
2996 public:
2997   ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2998
2999   virtual void initialize(ScheduleDAGMI *dag) {
3000     assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3001     DAG = static_cast<ScheduleDAGMILive*>(dag);
3002     DAG->computeDFSResult();
3003     Cmp.DFSResult = DAG->getDFSResult();
3004     Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3005     ReadyQ.clear();
3006   }
3007
3008   virtual void registerRoots() {
3009     // Restore the heap in ReadyQ with the updated DFS results.
3010     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3011   }
3012
3013   /// Implement MachineSchedStrategy interface.
3014   /// -----------------------------------------
3015
3016   /// Callback to select the highest priority node from the ready Q.
3017   virtual SUnit *pickNode(bool &IsTopNode) {
3018     if (ReadyQ.empty()) return NULL;
3019     std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3020     SUnit *SU = ReadyQ.back();
3021     ReadyQ.pop_back();
3022     IsTopNode = false;
3023     DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3024           << " ILP: " << DAG->getDFSResult()->getILP(SU)
3025           << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3026           << DAG->getDFSResult()->getSubtreeLevel(
3027             DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3028           << "Scheduling " << *SU->getInstr());
3029     return SU;
3030   }
3031
3032   /// \brief Scheduler callback to notify that a new subtree is scheduled.
3033   virtual void scheduleTree(unsigned SubtreeID) {
3034     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3035   }
3036
3037   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3038   /// DFSResults, and resort the priority Q.
3039   virtual void schedNode(SUnit *SU, bool IsTopNode) {
3040     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3041   }
3042
3043   virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
3044
3045   virtual void releaseBottomNode(SUnit *SU) {
3046     ReadyQ.push_back(SU);
3047     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3048   }
3049 };
3050 } // namespace
3051
3052 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3053   return new ScheduleDAGMILive(C, new ILPScheduler(true));
3054 }
3055 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3056   return new ScheduleDAGMILive(C, new ILPScheduler(false));
3057 }
3058 static MachineSchedRegistry ILPMaxRegistry(
3059   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3060 static MachineSchedRegistry ILPMinRegistry(
3061   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3062
3063 //===----------------------------------------------------------------------===//
3064 // Machine Instruction Shuffler for Correctness Testing
3065 //===----------------------------------------------------------------------===//
3066
3067 #ifndef NDEBUG
3068 namespace {
3069 /// Apply a less-than relation on the node order, which corresponds to the
3070 /// instruction order prior to scheduling. IsReverse implements greater-than.
3071 template<bool IsReverse>
3072 struct SUnitOrder {
3073   bool operator()(SUnit *A, SUnit *B) const {
3074     if (IsReverse)
3075       return A->NodeNum > B->NodeNum;
3076     else
3077       return A->NodeNum < B->NodeNum;
3078   }
3079 };
3080
3081 /// Reorder instructions as much as possible.
3082 class InstructionShuffler : public MachineSchedStrategy {
3083   bool IsAlternating;
3084   bool IsTopDown;
3085
3086   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3087   // gives nodes with a higher number higher priority causing the latest
3088   // instructions to be scheduled first.
3089   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3090     TopQ;
3091   // When scheduling bottom-up, use greater-than as the queue priority.
3092   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3093     BottomQ;
3094 public:
3095   InstructionShuffler(bool alternate, bool topdown)
3096     : IsAlternating(alternate), IsTopDown(topdown) {}
3097
3098   virtual void initialize(ScheduleDAGMI*) {
3099     TopQ.clear();
3100     BottomQ.clear();
3101   }
3102
3103   /// Implement MachineSchedStrategy interface.
3104   /// -----------------------------------------
3105
3106   virtual SUnit *pickNode(bool &IsTopNode) {
3107     SUnit *SU;
3108     if (IsTopDown) {
3109       do {
3110         if (TopQ.empty()) return NULL;
3111         SU = TopQ.top();
3112         TopQ.pop();
3113       } while (SU->isScheduled);
3114       IsTopNode = true;
3115     }
3116     else {
3117       do {
3118         if (BottomQ.empty()) return NULL;
3119         SU = BottomQ.top();
3120         BottomQ.pop();
3121       } while (SU->isScheduled);
3122       IsTopNode = false;
3123     }
3124     if (IsAlternating)
3125       IsTopDown = !IsTopDown;
3126     return SU;
3127   }
3128
3129   virtual void schedNode(SUnit *SU, bool IsTopNode) {}
3130
3131   virtual void releaseTopNode(SUnit *SU) {
3132     TopQ.push(SU);
3133   }
3134   virtual void releaseBottomNode(SUnit *SU) {
3135     BottomQ.push(SU);
3136   }
3137 };
3138 } // namespace
3139
3140 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3141   bool Alternate = !ForceTopDown && !ForceBottomUp;
3142   bool TopDown = !ForceBottomUp;
3143   assert((TopDown || !ForceTopDown) &&
3144          "-misched-topdown incompatible with -misched-bottomup");
3145   return new ScheduleDAGMILive(C, new InstructionShuffler(Alternate, TopDown));
3146 }
3147 static MachineSchedRegistry ShufflerRegistry(
3148   "shuffle", "Shuffle machine instructions alternating directions",
3149   createInstructionShuffler);
3150 #endif // !NDEBUG
3151
3152 //===----------------------------------------------------------------------===//
3153 // GraphWriter support for ScheduleDAGMILive.
3154 //===----------------------------------------------------------------------===//
3155
3156 #ifndef NDEBUG
3157 namespace llvm {
3158
3159 template<> struct GraphTraits<
3160   ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3161
3162 template<>
3163 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3164
3165   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3166
3167   static std::string getGraphName(const ScheduleDAG *G) {
3168     return G->MF.getName();
3169   }
3170
3171   static bool renderGraphFromBottomUp() {
3172     return true;
3173   }
3174
3175   static bool isNodeHidden(const SUnit *Node) {
3176     return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
3177   }
3178
3179   static bool hasNodeAddressLabel(const SUnit *Node,
3180                                   const ScheduleDAG *Graph) {
3181     return false;
3182   }
3183
3184   /// If you want to override the dot attributes printed for a particular
3185   /// edge, override this method.
3186   static std::string getEdgeAttributes(const SUnit *Node,
3187                                        SUnitIterator EI,
3188                                        const ScheduleDAG *Graph) {
3189     if (EI.isArtificialDep())
3190       return "color=cyan,style=dashed";
3191     if (EI.isCtrlDep())
3192       return "color=blue,style=dashed";
3193     return "";
3194   }
3195
3196   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3197     std::string Str;
3198     raw_string_ostream SS(Str);
3199     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3200     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3201       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3202     SS << "SU:" << SU->NodeNum;
3203     if (DFS)
3204       SS << " I:" << DFS->getNumInstrs(SU);
3205     return SS.str();
3206   }
3207   static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3208     return G->getGraphNodeLabel(SU);
3209   }
3210
3211   static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3212     std::string Str("shape=Mrecord");
3213     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3214     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3215       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3216     if (DFS) {
3217       Str += ",style=filled,fillcolor=\"#";
3218       Str += DOT::getColorString(DFS->getSubtreeID(N));
3219       Str += '"';
3220     }
3221     return Str;
3222   }
3223 };
3224 } // namespace llvm
3225 #endif // NDEBUG
3226
3227 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3228 /// rendered using 'dot'.
3229 ///
3230 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3231 #ifndef NDEBUG
3232   ViewGraph(this, Name, false, Title);
3233 #else
3234   errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3235          << "systems with Graphviz or gv!\n";
3236 #endif  // NDEBUG
3237 }
3238
3239 /// Out-of-line implementation with no arguments is handy for gdb.
3240 void ScheduleDAGMI::viewGraph() {
3241   viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3242 }