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