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