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