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