Break anti-dependencies using free registers in a round-robin manner to avoid introdu...
[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, bool IgnoreAntiDep);
179     void ReleaseSuccessors(SUnit *SU, bool IgnoreAntiDep);
180     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle, bool IgnoreAntiDep);
181     void ListScheduleTopDown(
182            AntiDepBreaker::CandidateMap *AntiDepCandidates);
183     void StartBlockForKills(MachineBasicBlock *BB);
184     
185     // ToggleKillFlag - Toggle a register operand kill flag. Other
186     // adjustments may be made to the instruction if necessary. Return
187     // true if the operand has been deleted, false if not.
188     bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
189   };
190 }
191
192 /// isSchedulingBoundary - Test if the given instruction should be
193 /// considered a scheduling boundary. This primarily includes labels
194 /// and terminators.
195 ///
196 static bool isSchedulingBoundary(const MachineInstr *MI,
197                                  const MachineFunction &MF) {
198   // Terminators and labels can't be scheduled around.
199   if (MI->getDesc().isTerminator() || MI->isLabel())
200     return true;
201
202   // Don't attempt to schedule around any instruction that modifies
203   // a stack-oriented pointer, as it's unlikely to be profitable. This
204   // saves compile time, because it doesn't require every single
205   // stack slot reference to depend on the instruction that does the
206   // modification.
207   const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
208   if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
209     return true;
210
211   return false;
212 }
213
214 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
215   AA = &getAnalysis<AliasAnalysis>();
216
217   // Check for explicit enable/disable of post-ra scheduling.
218   TargetSubtarget::AntiDepBreakMode AntiDepMode = TargetSubtarget::ANTIDEP_NONE;
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))
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) :
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     AntiDepBreaker::CandidateMap AntiDepCandidates;
325     const bool NeedCandidates = AntiDepBreak->NeedCandidates();
326     
327     for (unsigned i = 0, Trials = AntiDepBreak->GetMaxTrials();
328          i < Trials; ++i) {
329       DEBUG(errs() << "\n********** Break Anti-Deps, Trial " << 
330             i << " **********\n");
331       
332       // If candidates are required, then schedule forward ignoring
333       // anti-dependencies to collect the candidate operands for
334       // anti-dependence breaking. The candidates will be the def
335       // operands for the anti-dependencies that if broken would allow
336       // an improved schedule
337       if (NeedCandidates) {
338         DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
339                 SUnits[su].dumpAll(this));
340
341         AntiDepCandidates.clear();
342         AvailableQueue.initNodes(SUnits);
343         ListScheduleTopDown(&AntiDepCandidates);
344         AvailableQueue.releaseState();
345       }
346
347       unsigned Broken = 
348         AntiDepBreak->BreakAntiDependencies(SUnits, AntiDepCandidates,
349                                             Begin, InsertPos, InsertPosIndex);
350
351       // We made changes. Update the dependency graph.
352       // Theoretically we could update the graph in place:
353       // When a live range is changed to use a different register, remove
354       // the def's anti-dependence *and* output-dependence edges due to
355       // that register, and add new anti-dependence and output-dependence
356       // edges based on the next live range of the register.
357       if ((Broken != 0) || NeedCandidates) {
358         SUnits.clear();
359         Sequence.clear();
360         EntrySU = SUnit();
361         ExitSU = SUnit();
362         BuildSchedGraph(AA);
363       }
364
365       NumFixedAnti += Broken;
366       if (Broken == 0)
367         break;
368     }
369   }
370
371   DEBUG(errs() << "********** List Scheduling **********\n");
372   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
373           SUnits[su].dumpAll(this));
374
375   AvailableQueue.initNodes(SUnits);
376   ListScheduleTopDown(NULL);
377   AvailableQueue.releaseState();
378 }
379
380 /// Observe - Update liveness information to account for the current
381 /// instruction, which will not be scheduled.
382 ///
383 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
384   if (AntiDepBreak != NULL)
385     AntiDepBreak->Observe(MI, Count, InsertPosIndex);
386 }
387
388 /// FinishBlock - Clean up register live-range state.
389 ///
390 void SchedulePostRATDList::FinishBlock() {
391   if (AntiDepBreak != NULL)
392     AntiDepBreak->FinishBlock();
393
394   // Call the superclass.
395   ScheduleDAGInstrs::FinishBlock();
396 }
397
398 /// StartBlockForKills - Initialize register live-range state for updating kills
399 ///
400 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
401   // Initialize the indices to indicate that no registers are live.
402   std::fill(KillIndices, array_endof(KillIndices), ~0u);
403
404   // Determine the live-out physregs for this block.
405   if (!BB->empty() && BB->back().getDesc().isReturn()) {
406     // In a return block, examine the function live-out regs.
407     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
408            E = MRI.liveout_end(); I != E; ++I) {
409       unsigned Reg = *I;
410       KillIndices[Reg] = BB->size();
411       // Repeat, for all subregs.
412       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
413            *Subreg; ++Subreg) {
414         KillIndices[*Subreg] = BB->size();
415       }
416     }
417   }
418   else {
419     // In a non-return block, examine the live-in regs of all successors.
420     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
421            SE = BB->succ_end(); SI != SE; ++SI) {
422       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
423              E = (*SI)->livein_end(); I != E; ++I) {
424         unsigned Reg = *I;
425         KillIndices[Reg] = BB->size();
426         // Repeat, for all subregs.
427         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
428              *Subreg; ++Subreg) {
429           KillIndices[*Subreg] = BB->size();
430         }
431       }
432     }
433   }
434 }
435
436 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
437                                           MachineOperand &MO) {
438   // Setting kill flag...
439   if (!MO.isKill()) {
440     MO.setIsKill(true);
441     return false;
442   }
443   
444   // If MO itself is live, clear the kill flag...
445   if (KillIndices[MO.getReg()] != ~0u) {
446     MO.setIsKill(false);
447     return false;
448   }
449
450   // If any subreg of MO is live, then create an imp-def for that
451   // subreg and keep MO marked as killed.
452   MO.setIsKill(false);
453   bool AllDead = true;
454   const unsigned SuperReg = MO.getReg();
455   for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
456        *Subreg; ++Subreg) {
457     if (KillIndices[*Subreg] != ~0u) {
458       MI->addOperand(MachineOperand::CreateReg(*Subreg,
459                                                true  /*IsDef*/,
460                                                true  /*IsImp*/,
461                                                false /*IsKill*/,
462                                                false /*IsDead*/));
463       AllDead = false;
464     }
465   }
466
467   if(AllDead)
468     MO.setIsKill(true);
469   return false;
470 }
471
472 /// FixupKills - Fix the register kill flags, they may have been made
473 /// incorrect by instruction reordering.
474 ///
475 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
476   DEBUG(errs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
477
478   std::set<unsigned> killedRegs;
479   BitVector ReservedRegs = TRI->getReservedRegs(MF);
480
481   StartBlockForKills(MBB);
482   
483   // Examine block from end to start...
484   unsigned Count = MBB->size();
485   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
486        I != E; --Count) {
487     MachineInstr *MI = --I;
488
489     // Update liveness.  Registers that are defed but not used in this
490     // instruction are now dead. Mark register and all subregs as they
491     // are completely defined.
492     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
493       MachineOperand &MO = MI->getOperand(i);
494       if (!MO.isReg()) continue;
495       unsigned Reg = MO.getReg();
496       if (Reg == 0) continue;
497       if (!MO.isDef()) continue;
498       // Ignore two-addr defs.
499       if (MI->isRegTiedToUseOperand(i)) continue;
500       
501       KillIndices[Reg] = ~0u;
502       
503       // Repeat for all subregs.
504       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
505            *Subreg; ++Subreg) {
506         KillIndices[*Subreg] = ~0u;
507       }
508     }
509
510     // Examine all used registers and set/clear kill flag. When a
511     // register is used multiple times we only set the kill flag on
512     // the first use.
513     killedRegs.clear();
514     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
515       MachineOperand &MO = MI->getOperand(i);
516       if (!MO.isReg() || !MO.isUse()) continue;
517       unsigned Reg = MO.getReg();
518       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
519
520       bool kill = false;
521       if (killedRegs.find(Reg) == killedRegs.end()) {
522         kill = true;
523         // A register is not killed if any subregs are live...
524         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
525              *Subreg; ++Subreg) {
526           if (KillIndices[*Subreg] != ~0u) {
527             kill = false;
528             break;
529           }
530         }
531
532         // If subreg is not live, then register is killed if it became
533         // live in this instruction
534         if (kill)
535           kill = (KillIndices[Reg] == ~0u);
536       }
537       
538       if (MO.isKill() != kill) {
539         bool removed = ToggleKillFlag(MI, MO);
540         if (removed) {
541           DEBUG(errs() << "Fixed <removed> in ");
542         } else {
543           DEBUG(errs() << "Fixed " << MO << " in ");
544         }
545         DEBUG(MI->dump());
546       }
547       
548       killedRegs.insert(Reg);
549     }
550     
551     // Mark any used register (that is not using undef) and subregs as
552     // now live...
553     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
554       MachineOperand &MO = MI->getOperand(i);
555       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
556       unsigned Reg = MO.getReg();
557       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
558
559       KillIndices[Reg] = Count;
560       
561       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
562            *Subreg; ++Subreg) {
563         KillIndices[*Subreg] = Count;
564       }
565     }
566   }
567 }
568
569 //===----------------------------------------------------------------------===//
570 //  Top-Down Scheduling
571 //===----------------------------------------------------------------------===//
572
573 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
574 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
575 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge,
576                                        bool IgnoreAntiDep) {
577   SUnit *SuccSU = SuccEdge->getSUnit();
578
579 #ifndef NDEBUG
580   if (SuccSU->NumPredsLeft == 0) {
581     errs() << "*** Scheduling failed! ***\n";
582     SuccSU->dump(this);
583     errs() << " has been released too many times!\n";
584     llvm_unreachable(0);
585   }
586 #endif
587   --SuccSU->NumPredsLeft;
588
589   // Compute how many cycles it will be before this actually becomes
590   // available.  This is the max of the start time of all predecessors plus
591   // their latencies.
592   SuccSU->setDepthToAtLeast(SU->getDepth(IgnoreAntiDep) +
593                             SuccEdge->getLatency(), IgnoreAntiDep);
594   
595   // If all the node's predecessors are scheduled, this node is ready
596   // to be scheduled. Ignore the special ExitSU node.
597   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
598     PendingQueue.push_back(SuccSU);
599 }
600
601 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
602 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU, bool IgnoreAntiDep) {
603   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
604        I != E; ++I) {
605     if (IgnoreAntiDep && (I->getKind() == SDep::Anti)) continue;
606     ReleaseSucc(SU, &*I, IgnoreAntiDep);
607   }
608 }
609
610 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
611 /// count of its successors. If a successor pending count is zero, add it to
612 /// the Available queue.
613 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle,
614                                                bool IgnoreAntiDep) {
615   DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
616   DEBUG(SU->dump(this));
617   
618   Sequence.push_back(SU);
619   assert(CurCycle >= SU->getDepth(IgnoreAntiDep) && 
620          "Node scheduled above its depth!");
621   SU->setDepthToAtLeast(CurCycle, IgnoreAntiDep);
622
623   ReleaseSuccessors(SU, IgnoreAntiDep);
624   SU->isScheduled = true;
625   AvailableQueue.ScheduledNode(SU);
626 }
627
628 /// ListScheduleTopDown - The main loop of list scheduling for top-down
629 /// schedulers.
630 void SchedulePostRATDList::ListScheduleTopDown(
631                    AntiDepBreaker::CandidateMap *AntiDepCandidates) {
632   unsigned CurCycle = 0;
633   const bool IgnoreAntiDep = (AntiDepCandidates != NULL);
634   
635   // We're scheduling top-down but we're visiting the regions in
636   // bottom-up order, so we don't know the hazards at the start of a
637   // region. So assume no hazards (this should usually be ok as most
638   // blocks are a single region).
639   HazardRec->Reset();
640
641   // If ignoring anti-dependencies, the Schedule DAG still has Anti
642   // dep edges, but we ignore them for scheduling purposes
643   AvailableQueue.setIgnoreAntiDep(IgnoreAntiDep);
644
645   // Release any successors of the special Entry node.
646   ReleaseSuccessors(&EntrySU, IgnoreAntiDep);
647
648   // Add all leaves to Available queue. If ignoring antideps we also
649   // adjust the predecessor count for each node to not include antidep
650   // edges.
651   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
652     // It is available if it has no predecessors.
653     bool available = SUnits[i].Preds.empty();
654     // If we are ignoring anti-dependencies then a node that has only
655     // anti-dep predecessors is available.
656     if (!available && IgnoreAntiDep) {
657       available = true;
658       for (SUnit::const_pred_iterator I = SUnits[i].Preds.begin(),
659              E = SUnits[i].Preds.end(); I != E; ++I) {
660         if (I->getKind() != SDep::Anti) {
661           available = false;
662         } else {
663           SUnits[i].NumPredsLeft -= 1;
664         }
665       }
666     }
667
668     if (available) {
669       AvailableQueue.push(&SUnits[i]);
670       SUnits[i].isAvailable = true;
671     }
672   }
673
674   // In any cycle where we can't schedule any instructions, we must
675   // stall or emit a noop, depending on the target.
676   bool CycleHasInsts = false;
677
678   // While Available queue is not empty, grab the node with the highest
679   // priority. If it is not ready put it back.  Schedule the node.
680   std::vector<SUnit*> NotReady;
681   Sequence.reserve(SUnits.size());
682   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
683     // Check to see if any of the pending instructions are ready to issue.  If
684     // so, add them to the available queue.
685     unsigned MinDepth = ~0u;
686     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
687       if (PendingQueue[i]->getDepth(IgnoreAntiDep) <= CurCycle) {
688         AvailableQueue.push(PendingQueue[i]);
689         PendingQueue[i]->isAvailable = true;
690         PendingQueue[i] = PendingQueue.back();
691         PendingQueue.pop_back();
692         --i; --e;
693       } else if (PendingQueue[i]->getDepth(IgnoreAntiDep) < MinDepth)
694         MinDepth = PendingQueue[i]->getDepth(IgnoreAntiDep);
695     }
696
697     DEBUG(errs() << "\n*** Examining Available\n";
698           LatencyPriorityQueue q = AvailableQueue;
699           while (!q.empty()) {
700             SUnit *su = q.pop();
701             errs() << "Height " << su->getHeight(IgnoreAntiDep) << ": ";
702             su->dump(this);
703           });
704
705     SUnit *FoundSUnit = 0;
706     bool HasNoopHazards = false;
707     while (!AvailableQueue.empty()) {
708       SUnit *CurSUnit = AvailableQueue.pop();
709
710       ScheduleHazardRecognizer::HazardType HT =
711         HazardRec->getHazardType(CurSUnit);
712       if (HT == ScheduleHazardRecognizer::NoHazard) {
713         FoundSUnit = CurSUnit;
714         break;
715       }
716
717       // Remember if this is a noop hazard.
718       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
719
720       NotReady.push_back(CurSUnit);
721     }
722
723     // Add the nodes that aren't ready back onto the available list.
724     if (!NotReady.empty()) {
725       AvailableQueue.push_all(NotReady);
726       NotReady.clear();
727     }
728
729     // If we found a node to schedule...
730     if (FoundSUnit) {
731       // If we are ignoring anti-dependencies and the SUnit we are
732       // scheduling has an antidep predecessor that has not been
733       // scheduled, then we will need to break that antidep if we want
734       // to get this schedule when not ignoring anti-dependencies.
735       if (IgnoreAntiDep) {
736         AntiDepBreaker::AntiDepRegVector AntiDepRegs;
737         for (SUnit::const_pred_iterator I = FoundSUnit->Preds.begin(),
738                E = FoundSUnit->Preds.end(); I != E; ++I) {
739           if ((I->getKind() == SDep::Anti) && !I->getSUnit()->isScheduled)
740             AntiDepRegs.push_back(I->getReg());
741         }
742         
743         if (AntiDepRegs.size() > 0) {
744           DEBUG(errs() << "*** AntiDep Candidate: ");
745           DEBUG(FoundSUnit->dump(this));
746           AntiDepCandidates->insert(
747             AntiDepBreaker::CandidateMap::value_type(FoundSUnit, AntiDepRegs));
748         }
749       }
750
751       // ... schedule the node...
752       ScheduleNodeTopDown(FoundSUnit, CurCycle, IgnoreAntiDep);
753       HazardRec->EmitInstruction(FoundSUnit);
754       CycleHasInsts = true;
755
756       // If we are using the target-specific hazards, then don't
757       // advance the cycle time just because we schedule a node. If
758       // the target allows it we can schedule multiple nodes in the
759       // same cycle.
760       if (!EnablePostRAHazardAvoidance) {
761         if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
762           ++CurCycle;
763       }
764     } else {
765       if (CycleHasInsts) {
766         DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
767         HazardRec->AdvanceCycle();
768       } else if (!HasNoopHazards) {
769         // Otherwise, we have a pipeline stall, but no other problem,
770         // just advance the current cycle and try again.
771         DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
772         HazardRec->AdvanceCycle();
773         if (!IgnoreAntiDep)
774           ++NumStalls;
775       } else {
776         // Otherwise, we have no instructions to issue and we have instructions
777         // that will fault if we don't do this right.  This is the case for
778         // processors without pipeline interlocks and other cases.
779         DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
780         HazardRec->EmitNoop();
781         Sequence.push_back(0);   // NULL here means noop
782         if (!IgnoreAntiDep)
783           ++NumNoops;
784       }
785
786       ++CurCycle;
787       CycleHasInsts = false;
788     }
789   }
790
791 #ifndef NDEBUG
792   VerifySchedule(/*isBottomUp=*/false);
793 #endif
794 }
795
796 //===----------------------------------------------------------------------===//
797 //                         Public Constructor Functions
798 //===----------------------------------------------------------------------===//
799
800 FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
801   return new PostRAScheduler(OptLevel);
802 }