- Do away with SimpleHazardRecognizer.h. It's not used and offers little value.
[oota-llvm.git] / lib / CodeGen / PostRASchedulerList.cpp
1 //===----- SchedulePostRAList.cpp - list 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 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // order), checked for legality to schedule, and emitted if legal.
14 //
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "post-RA-sched"
22 #include "AntiDepBreaker.h"
23 #include "AggressiveAntiDepBreaker.h"
24 #include "CriticalAntiDepBreaker.h"
25 #include "ScheduleDAGInstrs.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/LatencyPriorityQueue.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtarget.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/ADT/BitVector.h"
46 #include "llvm/ADT/Statistic.h"
47 #include <set>
48 using namespace llvm;
49
50 STATISTIC(NumNoops, "Number of noops inserted");
51 STATISTIC(NumStalls, "Number of pipeline stalls");
52 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
53
54 // Post-RA scheduling is enabled with
55 // TargetSubtarget.enablePostRAScheduler(). This flag can be used to
56 // override the target.
57 static cl::opt<bool>
58 EnablePostRAScheduler("post-RA-scheduler",
59                        cl::desc("Enable scheduling after register allocation"),
60                        cl::init(false), cl::Hidden);
61 static cl::opt<std::string>
62 EnableAntiDepBreaking("break-anti-dependencies",
63                       cl::desc("Break post-RA scheduling anti-dependencies: "
64                                "\"critical\", \"all\", or \"none\""),
65                       cl::init("none"), cl::Hidden);
66
67 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
68 static cl::opt<int>
69 DebugDiv("postra-sched-debugdiv",
70                       cl::desc("Debug control MBBs that are scheduled"),
71                       cl::init(0), cl::Hidden);
72 static cl::opt<int>
73 DebugMod("postra-sched-debugmod",
74                       cl::desc("Debug control MBBs that are scheduled"),
75                       cl::init(0), cl::Hidden);
76
77 AntiDepBreaker::~AntiDepBreaker() { }
78
79 namespace {
80   class PostRAScheduler : public MachineFunctionPass {
81     AliasAnalysis *AA;
82     CodeGenOpt::Level OptLevel;
83
84   public:
85     static char ID;
86     PostRAScheduler(CodeGenOpt::Level ol) :
87       MachineFunctionPass(&ID), OptLevel(ol) {}
88
89     void getAnalysisUsage(AnalysisUsage &AU) const {
90       AU.setPreservesCFG();
91       AU.addRequired<AliasAnalysis>();
92       AU.addRequired<MachineDominatorTree>();
93       AU.addPreserved<MachineDominatorTree>();
94       AU.addRequired<MachineLoopInfo>();
95       AU.addPreserved<MachineLoopInfo>();
96       MachineFunctionPass::getAnalysisUsage(AU);
97     }
98
99     const char *getPassName() const {
100       return "Post RA top-down list latency scheduler";
101     }
102
103     bool runOnMachineFunction(MachineFunction &Fn);
104   };
105   char PostRAScheduler::ID = 0;
106
107   class SchedulePostRATDList : public ScheduleDAGInstrs {
108     /// AvailableQueue - The priority queue to use for the available SUnits.
109     ///
110     LatencyPriorityQueue AvailableQueue;
111
112     /// PendingQueue - This contains all of the instructions whose operands have
113     /// been issued, but their results are not ready yet (due to the latency of
114     /// the operation).  Once the operands becomes available, the instruction is
115     /// added to the AvailableQueue.
116     std::vector<SUnit*> PendingQueue;
117
118     /// Topo - A topological ordering for SUnits.
119     ScheduleDAGTopologicalSort Topo;
120
121     /// HazardRec - The hazard recognizer to use.
122     ScheduleHazardRecognizer *HazardRec;
123
124     /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
125     AntiDepBreaker *AntiDepBreak;
126
127     /// AA - AliasAnalysis for making memory reference queries.
128     AliasAnalysis *AA;
129
130     /// KillIndices - The index of the most recent kill (proceding bottom-up),
131     /// or ~0u if the register is not live.
132     unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
133
134   public:
135     SchedulePostRATDList(MachineFunction &MF,
136                          const MachineLoopInfo &MLI,
137                          const MachineDominatorTree &MDT,
138                          ScheduleHazardRecognizer *HR,
139                          AntiDepBreaker *ADB,
140                          AliasAnalysis *aa)
141       : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
142       HazardRec(HR), AntiDepBreak(ADB), AA(aa) {}
143
144     ~SchedulePostRATDList() {
145     }
146
147     /// StartBlock - Initialize register live-range state for scheduling in
148     /// this block.
149     ///
150     void StartBlock(MachineBasicBlock *BB);
151
152     /// Schedule - Schedule the instruction range using list scheduling.
153     ///
154     void Schedule();
155
156     /// Observe - Update liveness information to account for the current
157     /// instruction, which will not be scheduled.
158     ///
159     void Observe(MachineInstr *MI, unsigned Count);
160
161     /// FinishBlock - Clean up register live-range state.
162     ///
163     void FinishBlock();
164
165     /// FixupKills - Fix register kill flags that have been made
166     /// invalid due to scheduling
167     ///
168     void FixupKills(MachineBasicBlock *MBB);
169
170   private:
171     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
172     void ReleaseSuccessors(SUnit *SU);
173     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
174     void ListScheduleTopDown();
175     void StartBlockForKills(MachineBasicBlock *BB);
176
177     // ToggleKillFlag - Toggle a register operand kill flag. Other
178     // adjustments may be made to the instruction if necessary. Return
179     // true if the operand has been deleted, false if not.
180     bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
181   };
182 }
183
184 /// isSchedulingBoundary - Test if the given instruction should be
185 /// considered a scheduling boundary. This primarily includes labels
186 /// and terminators.
187 ///
188 static bool isSchedulingBoundary(const MachineInstr *MI,
189                                  const MachineFunction &MF) {
190   // Terminators and labels can't be scheduled around.
191   if (MI->getDesc().isTerminator() || MI->isLabel())
192     return true;
193
194   // Don't attempt to schedule around any instruction that defines
195   // a stack-oriented pointer, as it's unlikely to be profitable. This
196   // saves compile time, because it doesn't require every single
197   // stack slot reference to depend on the instruction that does the
198   // modification.
199   const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
200   if (MI->definesRegister(TLI.getStackPointerRegisterToSaveRestore()))
201     return true;
202
203   return false;
204 }
205
206 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
207   AA = &getAnalysis<AliasAnalysis>();
208
209   // Check for explicit enable/disable of post-ra scheduling.
210   TargetSubtarget::AntiDepBreakMode AntiDepMode = TargetSubtarget::ANTIDEP_NONE;
211   SmallVector<TargetRegisterClass*, 4> CriticalPathRCs;
212   if (EnablePostRAScheduler.getPosition() > 0) {
213     if (!EnablePostRAScheduler)
214       return false;
215   } else {
216     // Check that post-RA scheduling is enabled for this target.
217     const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
218     if (!ST.enablePostRAScheduler(OptLevel, AntiDepMode, CriticalPathRCs))
219       return false;
220   }
221
222   // Check for antidep breaking override...
223   if (EnableAntiDepBreaking.getPosition() > 0) {
224     AntiDepMode = (EnableAntiDepBreaking == "all") ?
225       TargetSubtarget::ANTIDEP_ALL :
226         (EnableAntiDepBreaking == "critical")
227            ? TargetSubtarget::ANTIDEP_CRITICAL : TargetSubtarget::ANTIDEP_NONE;
228   }
229
230   DEBUG(dbgs() << "PostRAScheduler\n");
231
232   const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
233   const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
234   const TargetMachine &TM = Fn.getTarget();
235   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
236   ScheduleHazardRecognizer *HR =
237     TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins);
238   AntiDepBreaker *ADB =
239     ((AntiDepMode == TargetSubtarget::ANTIDEP_ALL) ?
240      (AntiDepBreaker *)new AggressiveAntiDepBreaker(Fn, CriticalPathRCs) :
241      ((AntiDepMode == TargetSubtarget::ANTIDEP_CRITICAL) ?
242       (AntiDepBreaker *)new CriticalAntiDepBreaker(Fn) : NULL));
243
244   SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR, ADB, AA);
245
246   // Loop over all of the basic blocks
247   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
248        MBB != MBBe; ++MBB) {
249 #ifndef NDEBUG
250     // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
251     if (DebugDiv > 0) {
252       static int bbcnt = 0;
253       if (bbcnt++ % DebugDiv != DebugMod)
254         continue;
255       dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
256         ":BB#" << MBB->getNumber() << " ***\n";
257     }
258 #endif
259
260     // Initialize register live-range state for scheduling in this block.
261     Scheduler.StartBlock(MBB);
262
263     // Schedule each sequence of instructions not interrupted by a label
264     // or anything else that effectively needs to shut down scheduling.
265     MachineBasicBlock::iterator Current = MBB->end();
266     unsigned Count = MBB->size(), CurrentCount = Count;
267     for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
268       MachineInstr *MI = prior(I);
269       if (isSchedulingBoundary(MI, Fn)) {
270         Scheduler.Run(MBB, I, Current, CurrentCount);
271         Scheduler.EmitSchedule();
272         Current = MI;
273         CurrentCount = Count - 1;
274         Scheduler.Observe(MI, CurrentCount);
275       }
276       I = MI;
277       --Count;
278     }
279     assert(Count == 0 && "Instruction count mismatch!");
280     assert((MBB->begin() == Current || CurrentCount != 0) &&
281            "Instruction count mismatch!");
282     Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
283     Scheduler.EmitSchedule();
284
285     // Clean up register live-range state.
286     Scheduler.FinishBlock();
287
288     // Update register kills
289     Scheduler.FixupKills(MBB);
290   }
291
292   delete HR;
293   delete ADB;
294
295   return true;
296 }
297
298 /// StartBlock - Initialize register live-range state for scheduling in
299 /// this block.
300 ///
301 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
302   // Call the superclass.
303   ScheduleDAGInstrs::StartBlock(BB);
304
305   // Reset the hazard recognizer and anti-dep breaker.
306   HazardRec->Reset();
307   if (AntiDepBreak != NULL)
308     AntiDepBreak->StartBlock(BB);
309 }
310
311 /// Schedule - Schedule the instruction range using list scheduling.
312 ///
313 void SchedulePostRATDList::Schedule() {
314   // Build the scheduling graph.
315   BuildSchedGraph(AA);
316
317   if (AntiDepBreak != NULL) {
318     unsigned Broken =
319       AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
320                                           InsertPosIndex);
321
322     if (Broken != 0) {
323       // We made changes. Update the dependency graph.
324       // Theoretically we could update the graph in place:
325       // When a live range is changed to use a different register, remove
326       // the def's anti-dependence *and* output-dependence edges due to
327       // that register, and add new anti-dependence and output-dependence
328       // edges based on the next live range of the register.
329       SUnits.clear();
330       Sequence.clear();
331       EntrySU = SUnit();
332       ExitSU = SUnit();
333       BuildSchedGraph(AA);
334
335       NumFixedAnti += Broken;
336     }
337   }
338
339   DEBUG(dbgs() << "********** List Scheduling **********\n");
340   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
341           SUnits[su].dumpAll(this));
342
343   AvailableQueue.initNodes(SUnits);
344   ListScheduleTopDown();
345   AvailableQueue.releaseState();
346 }
347
348 /// Observe - Update liveness information to account for the current
349 /// instruction, which will not be scheduled.
350 ///
351 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
352   if (AntiDepBreak != NULL)
353     AntiDepBreak->Observe(MI, Count, InsertPosIndex);
354 }
355
356 /// FinishBlock - Clean up register live-range state.
357 ///
358 void SchedulePostRATDList::FinishBlock() {
359   if (AntiDepBreak != NULL)
360     AntiDepBreak->FinishBlock();
361
362   // Call the superclass.
363   ScheduleDAGInstrs::FinishBlock();
364 }
365
366 /// StartBlockForKills - Initialize register live-range state for updating kills
367 ///
368 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
369   // Initialize the indices to indicate that no registers are live.
370   for (unsigned i = 0; i < TRI->getNumRegs(); ++i)
371     KillIndices[i] = ~0u;
372
373   // Determine the live-out physregs for this block.
374   if (!BB->empty() && BB->back().getDesc().isReturn()) {
375     // In a return block, examine the function live-out regs.
376     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
377            E = MRI.liveout_end(); I != E; ++I) {
378       unsigned Reg = *I;
379       KillIndices[Reg] = BB->size();
380       // Repeat, for all subregs.
381       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
382            *Subreg; ++Subreg) {
383         KillIndices[*Subreg] = BB->size();
384       }
385     }
386   }
387   else {
388     // In a non-return block, examine the live-in regs of all successors.
389     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
390            SE = BB->succ_end(); SI != SE; ++SI) {
391       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
392              E = (*SI)->livein_end(); I != E; ++I) {
393         unsigned Reg = *I;
394         KillIndices[Reg] = BB->size();
395         // Repeat, for all subregs.
396         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
397              *Subreg; ++Subreg) {
398           KillIndices[*Subreg] = BB->size();
399         }
400       }
401     }
402   }
403 }
404
405 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
406                                           MachineOperand &MO) {
407   // Setting kill flag...
408   if (!MO.isKill()) {
409     MO.setIsKill(true);
410     return false;
411   }
412
413   // If MO itself is live, clear the kill flag...
414   if (KillIndices[MO.getReg()] != ~0u) {
415     MO.setIsKill(false);
416     return false;
417   }
418
419   // If any subreg of MO is live, then create an imp-def for that
420   // subreg and keep MO marked as killed.
421   MO.setIsKill(false);
422   bool AllDead = true;
423   const unsigned SuperReg = MO.getReg();
424   for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
425        *Subreg; ++Subreg) {
426     if (KillIndices[*Subreg] != ~0u) {
427       MI->addOperand(MachineOperand::CreateReg(*Subreg,
428                                                true  /*IsDef*/,
429                                                true  /*IsImp*/,
430                                                false /*IsKill*/,
431                                                false /*IsDead*/));
432       AllDead = false;
433     }
434   }
435
436   if(AllDead)
437     MO.setIsKill(true);
438   return false;
439 }
440
441 /// FixupKills - Fix the register kill flags, they may have been made
442 /// incorrect by instruction reordering.
443 ///
444 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
445   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
446
447   std::set<unsigned> killedRegs;
448   BitVector ReservedRegs = TRI->getReservedRegs(MF);
449
450   StartBlockForKills(MBB);
451
452   // Examine block from end to start...
453   unsigned Count = MBB->size();
454   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
455        I != E; --Count) {
456     MachineInstr *MI = --I;
457     if (MI->isDebugValue())
458       continue;
459
460     // Update liveness.  Registers that are defed but not used in this
461     // instruction are now dead. Mark register and all subregs as they
462     // are completely defined.
463     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
464       MachineOperand &MO = MI->getOperand(i);
465       if (!MO.isReg()) continue;
466       unsigned Reg = MO.getReg();
467       if (Reg == 0) continue;
468       if (!MO.isDef()) continue;
469       // Ignore two-addr defs.
470       if (MI->isRegTiedToUseOperand(i)) continue;
471
472       KillIndices[Reg] = ~0u;
473
474       // Repeat for all subregs.
475       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
476            *Subreg; ++Subreg) {
477         KillIndices[*Subreg] = ~0u;
478       }
479     }
480
481     // Examine all used registers and set/clear kill flag. When a
482     // register is used multiple times we only set the kill flag on
483     // the first use.
484     killedRegs.clear();
485     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
486       MachineOperand &MO = MI->getOperand(i);
487       if (!MO.isReg() || !MO.isUse()) continue;
488       unsigned Reg = MO.getReg();
489       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
490
491       bool kill = false;
492       if (killedRegs.find(Reg) == killedRegs.end()) {
493         kill = true;
494         // A register is not killed if any subregs are live...
495         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
496              *Subreg; ++Subreg) {
497           if (KillIndices[*Subreg] != ~0u) {
498             kill = false;
499             break;
500           }
501         }
502
503         // If subreg is not live, then register is killed if it became
504         // live in this instruction
505         if (kill)
506           kill = (KillIndices[Reg] == ~0u);
507       }
508
509       if (MO.isKill() != kill) {
510         DEBUG(dbgs() << "Fixing " << MO << " in ");
511         // Warning: ToggleKillFlag may invalidate MO.
512         ToggleKillFlag(MI, MO);
513         DEBUG(MI->dump());
514       }
515
516       killedRegs.insert(Reg);
517     }
518
519     // Mark any used register (that is not using undef) and subregs as
520     // now live...
521     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
522       MachineOperand &MO = MI->getOperand(i);
523       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
524       unsigned Reg = MO.getReg();
525       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
526
527       KillIndices[Reg] = Count;
528
529       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
530            *Subreg; ++Subreg) {
531         KillIndices[*Subreg] = Count;
532       }
533     }
534   }
535 }
536
537 //===----------------------------------------------------------------------===//
538 //  Top-Down Scheduling
539 //===----------------------------------------------------------------------===//
540
541 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
542 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
543 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
544   SUnit *SuccSU = SuccEdge->getSUnit();
545
546 #ifndef NDEBUG
547   if (SuccSU->NumPredsLeft == 0) {
548     dbgs() << "*** Scheduling failed! ***\n";
549     SuccSU->dump(this);
550     dbgs() << " has been released too many times!\n";
551     llvm_unreachable(0);
552   }
553 #endif
554   --SuccSU->NumPredsLeft;
555
556   // Compute how many cycles it will be before this actually becomes
557   // available.  This is the max of the start time of all predecessors plus
558   // their latencies.
559   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
560
561   // If all the node's predecessors are scheduled, this node is ready
562   // to be scheduled. Ignore the special ExitSU node.
563   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
564     PendingQueue.push_back(SuccSU);
565 }
566
567 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
568 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
569   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
570        I != E; ++I) {
571     ReleaseSucc(SU, &*I);
572   }
573 }
574
575 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
576 /// count of its successors. If a successor pending count is zero, add it to
577 /// the Available queue.
578 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
579   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
580   DEBUG(SU->dump(this));
581
582   Sequence.push_back(SU);
583   assert(CurCycle >= SU->getDepth() &&
584          "Node scheduled above its depth!");
585   SU->setDepthToAtLeast(CurCycle);
586
587   ReleaseSuccessors(SU);
588   SU->isScheduled = true;
589   AvailableQueue.ScheduledNode(SU);
590 }
591
592 /// ListScheduleTopDown - The main loop of list scheduling for top-down
593 /// schedulers.
594 void SchedulePostRATDList::ListScheduleTopDown() {
595   unsigned CurCycle = 0;
596
597   // We're scheduling top-down but we're visiting the regions in
598   // bottom-up order, so we don't know the hazards at the start of a
599   // region. So assume no hazards (this should usually be ok as most
600   // blocks are a single region).
601   HazardRec->Reset();
602
603   // Release any successors of the special Entry node.
604   ReleaseSuccessors(&EntrySU);
605
606   // Add all leaves to Available queue.
607   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
608     // It is available if it has no predecessors.
609     bool available = SUnits[i].Preds.empty();
610     if (available) {
611       AvailableQueue.push(&SUnits[i]);
612       SUnits[i].isAvailable = true;
613     }
614   }
615
616   // In any cycle where we can't schedule any instructions, we must
617   // stall or emit a noop, depending on the target.
618   bool CycleHasInsts = false;
619
620   // While Available queue is not empty, grab the node with the highest
621   // priority. If it is not ready put it back.  Schedule the node.
622   std::vector<SUnit*> NotReady;
623   Sequence.reserve(SUnits.size());
624   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
625     // Check to see if any of the pending instructions are ready to issue.  If
626     // so, add them to the available queue.
627     unsigned MinDepth = ~0u;
628     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
629       if (PendingQueue[i]->getDepth() <= CurCycle) {
630         AvailableQueue.push(PendingQueue[i]);
631         PendingQueue[i]->isAvailable = true;
632         PendingQueue[i] = PendingQueue.back();
633         PendingQueue.pop_back();
634         --i; --e;
635       } else if (PendingQueue[i]->getDepth() < MinDepth)
636         MinDepth = PendingQueue[i]->getDepth();
637     }
638
639     DEBUG(dbgs() << "\n*** Examining Available\n";
640           LatencyPriorityQueue q = AvailableQueue;
641           while (!q.empty()) {
642             SUnit *su = q.pop();
643             dbgs() << "Height " << su->getHeight() << ": ";
644             su->dump(this);
645           });
646
647     SUnit *FoundSUnit = 0;
648     bool HasNoopHazards = false;
649     while (!AvailableQueue.empty()) {
650       SUnit *CurSUnit = AvailableQueue.pop();
651
652       ScheduleHazardRecognizer::HazardType HT =
653         HazardRec->getHazardType(CurSUnit);
654       if (HT == ScheduleHazardRecognizer::NoHazard) {
655         FoundSUnit = CurSUnit;
656         break;
657       }
658
659       // Remember if this is a noop hazard.
660       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
661
662       NotReady.push_back(CurSUnit);
663     }
664
665     // Add the nodes that aren't ready back onto the available list.
666     if (!NotReady.empty()) {
667       AvailableQueue.push_all(NotReady);
668       NotReady.clear();
669     }
670
671     // If we found a node to schedule...
672     if (FoundSUnit) {
673       // ... schedule the node...
674       ScheduleNodeTopDown(FoundSUnit, CurCycle);
675       HazardRec->EmitInstruction(FoundSUnit);
676       CycleHasInsts = true;
677     } else {
678       if (CycleHasInsts) {
679         DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
680         HazardRec->AdvanceCycle();
681       } else if (!HasNoopHazards) {
682         // Otherwise, we have a pipeline stall, but no other problem,
683         // just advance the current cycle and try again.
684         DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
685         HazardRec->AdvanceCycle();
686         ++NumStalls;
687       } else {
688         // Otherwise, we have no instructions to issue and we have instructions
689         // that will fault if we don't do this right.  This is the case for
690         // processors without pipeline interlocks and other cases.
691         DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
692         HazardRec->EmitNoop();
693         Sequence.push_back(0);   // NULL here means noop
694         ++NumNoops;
695       }
696
697       ++CurCycle;
698       CycleHasInsts = false;
699     }
700   }
701
702 #ifndef NDEBUG
703   VerifySchedule(/*isBottomUp=*/false);
704 #endif
705 }
706
707 //===----------------------------------------------------------------------===//
708 //                         Public Constructor Functions
709 //===----------------------------------------------------------------------===//
710
711 FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
712   return new PostRAScheduler(OptLevel);
713 }