cedb41273cdd375a717706b426456fa8702b99b0
[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 "RegisterClassInfo.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/ScheduleDAGInstrs.h"
35 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/ADT/BitVector.h"
47 #include "llvm/ADT/Statistic.h"
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 // TargetSubtargetInfo.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     const TargetInstrInfo *TII;
83     RegisterClassInfo RegClassInfo;
84
85   public:
86     static char ID;
87     PostRAScheduler() : MachineFunctionPass(ID) {}
88
89     void getAnalysisUsage(AnalysisUsage &AU) const {
90       AU.setPreservesCFG();
91       AU.addRequired<AliasAnalysis>();
92       AU.addRequired<TargetPassConfig>();
93       AU.addRequired<MachineDominatorTree>();
94       AU.addPreserved<MachineDominatorTree>();
95       AU.addRequired<MachineLoopInfo>();
96       AU.addPreserved<MachineLoopInfo>();
97       MachineFunctionPass::getAnalysisUsage(AU);
98     }
99
100     bool runOnMachineFunction(MachineFunction &Fn);
101   };
102   char PostRAScheduler::ID = 0;
103
104   class SchedulePostRATDList : public ScheduleDAGInstrs {
105     /// AvailableQueue - The priority queue to use for the available SUnits.
106     ///
107     LatencyPriorityQueue AvailableQueue;
108
109     /// PendingQueue - This contains all of the instructions whose operands have
110     /// been issued, but their results are not ready yet (due to the latency of
111     /// the operation).  Once the operands becomes available, the instruction is
112     /// added to the AvailableQueue.
113     std::vector<SUnit*> PendingQueue;
114
115     /// Topo - A topological ordering for SUnits.
116     ScheduleDAGTopologicalSort Topo;
117
118     /// HazardRec - The hazard recognizer to use.
119     ScheduleHazardRecognizer *HazardRec;
120
121     /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
122     AntiDepBreaker *AntiDepBreak;
123
124     /// AA - AliasAnalysis for making memory reference queries.
125     AliasAnalysis *AA;
126
127     /// LiveRegs - true if the register is live.
128     BitVector LiveRegs;
129
130     /// The schedule. Null SUnit*'s represent noop instructions.
131     std::vector<SUnit*> Sequence;
132
133   public:
134     SchedulePostRATDList(
135       MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
136       AliasAnalysis *AA, const RegisterClassInfo&,
137       TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
138       SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
139
140     ~SchedulePostRATDList();
141
142     /// startBlock - Initialize register live-range state for scheduling in
143     /// this block.
144     ///
145     void startBlock(MachineBasicBlock *BB);
146
147     /// Initialize the scheduler state for the next scheduling region.
148     virtual void enterRegion(MachineBasicBlock *bb,
149                              MachineBasicBlock::iterator begin,
150                              MachineBasicBlock::iterator end,
151                              unsigned endcount);
152
153     /// Notify that the scheduler has finished scheduling the current region.
154     virtual void exitRegion();
155
156     /// Schedule - Schedule the instruction range using list scheduling.
157     ///
158     void schedule();
159
160     void EmitSchedule();
161
162     /// Observe - Update liveness information to account for the current
163     /// instruction, which will not be scheduled.
164     ///
165     void Observe(MachineInstr *MI, unsigned Count);
166
167     /// finishBlock - Clean up register live-range state.
168     ///
169     void finishBlock();
170
171     /// FixupKills - Fix register kill flags that have been made
172     /// invalid due to scheduling
173     ///
174     void FixupKills(MachineBasicBlock *MBB);
175
176   private:
177     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
178     void ReleaseSuccessors(SUnit *SU);
179     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
180     void ListScheduleTopDown();
181     void StartBlockForKills(MachineBasicBlock *BB);
182
183     // ToggleKillFlag - Toggle a register operand kill flag. Other
184     // adjustments may be made to the instruction if necessary. Return
185     // true if the operand has been deleted, false if not.
186     bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
187
188     void dumpSchedule() const;
189   };
190 }
191
192 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
193
194 INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
195                 "Post RA top-down list latency scheduler", false, false)
196
197 SchedulePostRATDList::SchedulePostRATDList(
198   MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
199   AliasAnalysis *AA, const RegisterClassInfo &RCI,
200   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
201   SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs)
202   : ScheduleDAGInstrs(MF, MLI, MDT, /*IsPostRA=*/true), Topo(SUnits), AA(AA),
203     LiveRegs(TRI->getNumRegs())
204 {
205   const TargetMachine &TM = MF.getTarget();
206   const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
207   HazardRec =
208     TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins, this);
209
210   assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE ||
211           MRI.tracksLiveness()) &&
212          "Live-ins must be accurate for anti-dependency breaking");
213   AntiDepBreak =
214     ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
215      (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
216      ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
217       (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : NULL));
218 }
219
220 SchedulePostRATDList::~SchedulePostRATDList() {
221   delete HazardRec;
222   delete AntiDepBreak;
223 }
224
225 /// Initialize state associated with the next scheduling region.
226 void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
227                  MachineBasicBlock::iterator begin,
228                  MachineBasicBlock::iterator end,
229                  unsigned endcount) {
230   ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
231   Sequence.clear();
232 }
233
234 /// Print the schedule before exiting the region.
235 void SchedulePostRATDList::exitRegion() {
236   DEBUG({
237       dbgs() << "*** Final schedule ***\n";
238       dumpSchedule();
239       dbgs() << '\n';
240     });
241   ScheduleDAGInstrs::exitRegion();
242 }
243
244 /// dumpSchedule - dump the scheduled Sequence.
245 void SchedulePostRATDList::dumpSchedule() const {
246   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
247     if (SUnit *SU = Sequence[i])
248       SU->dump(this);
249     else
250       dbgs() << "**** NOOP ****\n";
251   }
252 }
253
254 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
255   TII = Fn.getTarget().getInstrInfo();
256   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
257   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
258   AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
259   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
260
261   RegClassInfo.runOnMachineFunction(Fn);
262
263   // Check for explicit enable/disable of post-ra scheduling.
264   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
265     TargetSubtargetInfo::ANTIDEP_NONE;
266   SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
267   if (EnablePostRAScheduler.getPosition() > 0) {
268     if (!EnablePostRAScheduler)
269       return false;
270   } else {
271     // Check that post-RA scheduling is enabled for this target.
272     // This may upgrade the AntiDepMode.
273     const TargetSubtargetInfo &ST = Fn.getTarget().getSubtarget<TargetSubtargetInfo>();
274     if (!ST.enablePostRAScheduler(PassConfig->getOptLevel(), AntiDepMode,
275                                   CriticalPathRCs))
276       return false;
277   }
278
279   // Check for antidep breaking override...
280   if (EnableAntiDepBreaking.getPosition() > 0) {
281     AntiDepMode = (EnableAntiDepBreaking == "all")
282       ? TargetSubtargetInfo::ANTIDEP_ALL
283       : ((EnableAntiDepBreaking == "critical")
284          ? TargetSubtargetInfo::ANTIDEP_CRITICAL
285          : TargetSubtargetInfo::ANTIDEP_NONE);
286   }
287
288   DEBUG(dbgs() << "PostRAScheduler\n");
289
290   SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
291                                  CriticalPathRCs);
292
293   // Loop over all of the basic blocks
294   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
295        MBB != MBBe; ++MBB) {
296 #ifndef NDEBUG
297     // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
298     if (DebugDiv > 0) {
299       static int bbcnt = 0;
300       if (bbcnt++ % DebugDiv != DebugMod)
301         continue;
302       dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getName()
303              << ":BB#" << MBB->getNumber() << " ***\n";
304     }
305 #endif
306
307     // Initialize register live-range state for scheduling in this block.
308     Scheduler.startBlock(MBB);
309
310     // Schedule each sequence of instructions not interrupted by a label
311     // or anything else that effectively needs to shut down scheduling.
312     MachineBasicBlock::iterator Current = MBB->end();
313     unsigned Count = MBB->size(), CurrentCount = Count;
314     for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
315       MachineInstr *MI = llvm::prior(I);
316       // Calls are not scheduling boundaries before register allocation, but
317       // post-ra we don't gain anything by scheduling across calls since we
318       // don't need to worry about register pressure.
319       if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
320         Scheduler.enterRegion(MBB, I, Current, CurrentCount);
321         Scheduler.schedule();
322         Scheduler.exitRegion();
323         Scheduler.EmitSchedule();
324         Current = MI;
325         CurrentCount = Count - 1;
326         Scheduler.Observe(MI, CurrentCount);
327       }
328       I = MI;
329       --Count;
330       if (MI->isBundle())
331         Count -= MI->getBundleSize();
332     }
333     assert(Count == 0 && "Instruction count mismatch!");
334     assert((MBB->begin() == Current || CurrentCount != 0) &&
335            "Instruction count mismatch!");
336     Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
337     Scheduler.schedule();
338     Scheduler.exitRegion();
339     Scheduler.EmitSchedule();
340
341     // Clean up register live-range state.
342     Scheduler.finishBlock();
343
344     // Update register kills
345     Scheduler.FixupKills(MBB);
346   }
347
348   return true;
349 }
350
351 /// StartBlock - Initialize register live-range state for scheduling in
352 /// this block.
353 ///
354 void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
355   // Call the superclass.
356   ScheduleDAGInstrs::startBlock(BB);
357
358   // Reset the hazard recognizer and anti-dep breaker.
359   HazardRec->Reset();
360   if (AntiDepBreak != NULL)
361     AntiDepBreak->StartBlock(BB);
362 }
363
364 /// Schedule - Schedule the instruction range using list scheduling.
365 ///
366 void SchedulePostRATDList::schedule() {
367   // Build the scheduling graph.
368   buildSchedGraph(AA);
369
370   if (AntiDepBreak != NULL) {
371     unsigned Broken =
372       AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
373                                           EndIndex, DbgValues);
374
375     if (Broken != 0) {
376       // We made changes. Update the dependency graph.
377       // Theoretically we could update the graph in place:
378       // When a live range is changed to use a different register, remove
379       // the def's anti-dependence *and* output-dependence edges due to
380       // that register, and add new anti-dependence and output-dependence
381       // edges based on the next live range of the register.
382       ScheduleDAG::clearDAG();
383       buildSchedGraph(AA);
384
385       NumFixedAnti += Broken;
386     }
387   }
388
389   DEBUG(dbgs() << "********** List Scheduling **********\n");
390   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
391           SUnits[su].dumpAll(this));
392
393   AvailableQueue.initNodes(SUnits);
394   ListScheduleTopDown();
395   AvailableQueue.releaseState();
396 }
397
398 /// Observe - Update liveness information to account for the current
399 /// instruction, which will not be scheduled.
400 ///
401 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
402   if (AntiDepBreak != NULL)
403     AntiDepBreak->Observe(MI, Count, EndIndex);
404 }
405
406 /// FinishBlock - Clean up register live-range state.
407 ///
408 void SchedulePostRATDList::finishBlock() {
409   if (AntiDepBreak != NULL)
410     AntiDepBreak->FinishBlock();
411
412   // Call the superclass.
413   ScheduleDAGInstrs::finishBlock();
414 }
415
416 /// StartBlockForKills - Initialize register live-range state for updating kills
417 ///
418 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
419   // Start with no live registers.
420   LiveRegs.reset();
421
422   // Determine the live-out physregs for this block.
423   if (!BB->empty() && BB->back().isReturn()) {
424     // In a return block, examine the function live-out regs.
425     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
426            E = MRI.liveout_end(); I != E; ++I) {
427       unsigned Reg = *I;
428       LiveRegs.set(Reg);
429       // Repeat, for all subregs.
430       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
431         LiveRegs.set(*SubRegs);
432     }
433   }
434   else {
435     // In a non-return block, examine the live-in regs of all successors.
436     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
437            SE = BB->succ_end(); SI != SE; ++SI) {
438       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
439              E = (*SI)->livein_end(); I != E; ++I) {
440         unsigned Reg = *I;
441         LiveRegs.set(Reg);
442         // Repeat, for all subregs.
443         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
444           LiveRegs.set(*SubRegs);
445       }
446     }
447   }
448 }
449
450 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
451                                           MachineOperand &MO) {
452   // Setting kill flag...
453   if (!MO.isKill()) {
454     MO.setIsKill(true);
455     return false;
456   }
457
458   // If MO itself is live, clear the kill flag...
459   if (LiveRegs.test(MO.getReg())) {
460     MO.setIsKill(false);
461     return false;
462   }
463
464   // If any subreg of MO is live, then create an imp-def for that
465   // subreg and keep MO marked as killed.
466   MO.setIsKill(false);
467   bool AllDead = true;
468   const unsigned SuperReg = MO.getReg();
469   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
470     if (LiveRegs.test(*SubRegs)) {
471       MI->addOperand(MachineOperand::CreateReg(*SubRegs,
472                                                true  /*IsDef*/,
473                                                true  /*IsImp*/,
474                                                false /*IsKill*/,
475                                                false /*IsDead*/));
476       AllDead = false;
477     }
478   }
479
480   if(AllDead)
481     MO.setIsKill(true);
482   return false;
483 }
484
485 /// FixupKills - Fix the register kill flags, they may have been made
486 /// incorrect by instruction reordering.
487 ///
488 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
489   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
490
491   BitVector killedRegs(TRI->getNumRegs());
492   BitVector ReservedRegs = TRI->getReservedRegs(MF);
493
494   StartBlockForKills(MBB);
495
496   // Examine block from end to start...
497   unsigned Count = MBB->size();
498   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
499        I != E; --Count) {
500     MachineInstr *MI = --I;
501     if (MI->isDebugValue())
502       continue;
503
504     // Update liveness.  Registers that are defed but not used in this
505     // instruction are now dead. Mark register and all subregs as they
506     // are completely defined.
507     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
508       MachineOperand &MO = MI->getOperand(i);
509       if (MO.isRegMask())
510         LiveRegs.clearBitsNotInMask(MO.getRegMask());
511       if (!MO.isReg()) continue;
512       unsigned Reg = MO.getReg();
513       if (Reg == 0) continue;
514       if (!MO.isDef()) continue;
515       // Ignore two-addr defs.
516       if (MI->isRegTiedToUseOperand(i)) continue;
517
518       LiveRegs.reset(Reg);
519
520       // Repeat for all subregs.
521       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
522         LiveRegs.reset(*SubRegs);
523     }
524
525     // Examine all used registers and set/clear kill flag. When a
526     // register is used multiple times we only set the kill flag on
527     // the first use.
528     killedRegs.reset();
529     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
530       MachineOperand &MO = MI->getOperand(i);
531       if (!MO.isReg() || !MO.isUse()) continue;
532       unsigned Reg = MO.getReg();
533       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
534
535       bool kill = false;
536       if (!killedRegs.test(Reg)) {
537         kill = true;
538         // A register is not killed if any subregs are live...
539         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
540           if (LiveRegs.test(*SubRegs)) {
541             kill = false;
542             break;
543           }
544         }
545
546         // If subreg is not live, then register is killed if it became
547         // live in this instruction
548         if (kill)
549           kill = !LiveRegs.test(Reg);
550       }
551
552       if (MO.isKill() != kill) {
553         DEBUG(dbgs() << "Fixing " << MO << " in ");
554         // Warning: ToggleKillFlag may invalidate MO.
555         ToggleKillFlag(MI, MO);
556         DEBUG(MI->dump());
557       }
558
559       killedRegs.set(Reg);
560     }
561
562     // Mark any used register (that is not using undef) and subregs as
563     // now live...
564     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
565       MachineOperand &MO = MI->getOperand(i);
566       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
567       unsigned Reg = MO.getReg();
568       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
569
570       LiveRegs.set(Reg);
571
572       for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
573         LiveRegs.set(*SubRegs);
574     }
575   }
576 }
577
578 //===----------------------------------------------------------------------===//
579 //  Top-Down Scheduling
580 //===----------------------------------------------------------------------===//
581
582 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
583 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
584 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
585   SUnit *SuccSU = SuccEdge->getSUnit();
586
587 #ifndef NDEBUG
588   if (SuccSU->NumPredsLeft == 0) {
589     dbgs() << "*** Scheduling failed! ***\n";
590     SuccSU->dump(this);
591     dbgs() << " has been released too many times!\n";
592     llvm_unreachable(0);
593   }
594 #endif
595   --SuccSU->NumPredsLeft;
596
597   // Standard scheduler algorithms will recompute the depth of the successor
598   // here as such:
599   //   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
600   //
601   // However, we lazily compute node depth instead. Note that
602   // ScheduleNodeTopDown has already updated the depth of this node which causes
603   // all descendents to be marked dirty. Setting the successor depth explicitly
604   // here would cause depth to be recomputed for all its ancestors. If the
605   // successor is not yet ready (because of a transitively redundant edge) then
606   // this causes depth computation to be quadratic in the size of the DAG.
607
608   // If all the node's predecessors are scheduled, this node is ready
609   // to be scheduled. Ignore the special ExitSU node.
610   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
611     PendingQueue.push_back(SuccSU);
612 }
613
614 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
615 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
616   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
617        I != E; ++I) {
618     ReleaseSucc(SU, &*I);
619   }
620 }
621
622 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
623 /// count of its successors. If a successor pending count is zero, add it to
624 /// the Available queue.
625 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
626   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
627   DEBUG(SU->dump(this));
628
629   Sequence.push_back(SU);
630   assert(CurCycle >= SU->getDepth() &&
631          "Node scheduled above its depth!");
632   SU->setDepthToAtLeast(CurCycle);
633
634   ReleaseSuccessors(SU);
635   SU->isScheduled = true;
636   AvailableQueue.scheduledNode(SU);
637 }
638
639 /// ListScheduleTopDown - The main loop of list scheduling for top-down
640 /// schedulers.
641 void SchedulePostRATDList::ListScheduleTopDown() {
642   unsigned CurCycle = 0;
643
644   // We're scheduling top-down but we're visiting the regions in
645   // bottom-up order, so we don't know the hazards at the start of a
646   // region. So assume no hazards (this should usually be ok as most
647   // blocks are a single region).
648   HazardRec->Reset();
649
650   // Release any successors of the special Entry node.
651   ReleaseSuccessors(&EntrySU);
652
653   // Add all leaves to Available queue.
654   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
655     // It is available if it has no predecessors.
656     bool available = SUnits[i].Preds.empty();
657     if (available) {
658       AvailableQueue.push(&SUnits[i]);
659       SUnits[i].isAvailable = true;
660     }
661   }
662
663   // In any cycle where we can't schedule any instructions, we must
664   // stall or emit a noop, depending on the target.
665   bool CycleHasInsts = false;
666
667   // While Available queue is not empty, grab the node with the highest
668   // priority. If it is not ready put it back.  Schedule the node.
669   std::vector<SUnit*> NotReady;
670   Sequence.reserve(SUnits.size());
671   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
672     // Check to see if any of the pending instructions are ready to issue.  If
673     // so, add them to the available queue.
674     unsigned MinDepth = ~0u;
675     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
676       if (PendingQueue[i]->getDepth() <= CurCycle) {
677         AvailableQueue.push(PendingQueue[i]);
678         PendingQueue[i]->isAvailable = true;
679         PendingQueue[i] = PendingQueue.back();
680         PendingQueue.pop_back();
681         --i; --e;
682       } else if (PendingQueue[i]->getDepth() < MinDepth)
683         MinDepth = PendingQueue[i]->getDepth();
684     }
685
686     DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
687
688     SUnit *FoundSUnit = 0;
689     bool HasNoopHazards = false;
690     while (!AvailableQueue.empty()) {
691       SUnit *CurSUnit = AvailableQueue.pop();
692
693       ScheduleHazardRecognizer::HazardType HT =
694         HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
695       if (HT == ScheduleHazardRecognizer::NoHazard) {
696         FoundSUnit = CurSUnit;
697         break;
698       }
699
700       // Remember if this is a noop hazard.
701       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
702
703       NotReady.push_back(CurSUnit);
704     }
705
706     // Add the nodes that aren't ready back onto the available list.
707     if (!NotReady.empty()) {
708       AvailableQueue.push_all(NotReady);
709       NotReady.clear();
710     }
711
712     // If we found a node to schedule...
713     if (FoundSUnit) {
714       // ... schedule the node...
715       ScheduleNodeTopDown(FoundSUnit, CurCycle);
716       HazardRec->EmitInstruction(FoundSUnit);
717       CycleHasInsts = true;
718       if (HazardRec->atIssueLimit()) {
719         DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
720         HazardRec->AdvanceCycle();
721         ++CurCycle;
722         CycleHasInsts = false;
723       }
724     } else {
725       if (CycleHasInsts) {
726         DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
727         HazardRec->AdvanceCycle();
728       } else if (!HasNoopHazards) {
729         // Otherwise, we have a pipeline stall, but no other problem,
730         // just advance the current cycle and try again.
731         DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
732         HazardRec->AdvanceCycle();
733         ++NumStalls;
734       } else {
735         // Otherwise, we have no instructions to issue and we have instructions
736         // that will fault if we don't do this right.  This is the case for
737         // processors without pipeline interlocks and other cases.
738         DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
739         HazardRec->EmitNoop();
740         Sequence.push_back(0);   // NULL here means noop
741         ++NumNoops;
742       }
743
744       ++CurCycle;
745       CycleHasInsts = false;
746     }
747   }
748
749 #ifndef NDEBUG
750   unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
751   unsigned Noops = 0;
752   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
753     if (!Sequence[i])
754       ++Noops;
755   assert(Sequence.size() - Noops == ScheduledNodes &&
756          "The number of nodes scheduled doesn't match the expected number!");
757 #endif // NDEBUG
758 }
759
760 // EmitSchedule - Emit the machine code in scheduled order.
761 void SchedulePostRATDList::EmitSchedule() {
762   RegionBegin = RegionEnd;
763
764   // If first instruction was a DBG_VALUE then put it back.
765   if (FirstDbgValue)
766     BB->splice(RegionEnd, BB, FirstDbgValue);
767
768   // Then re-insert them according to the given schedule.
769   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
770     if (SUnit *SU = Sequence[i])
771       BB->splice(RegionEnd, BB, SU->getInstr());
772     else
773       // Null SUnit* is a noop.
774       TII->insertNoop(*BB, RegionEnd);
775
776     // Update the Begin iterator, as the first instruction in the block
777     // may have been scheduled later.
778     if (i == 0)
779       RegionBegin = prior(RegionEnd);
780   }
781
782   // Reinsert any remaining debug_values.
783   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
784          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
785     std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
786     MachineInstr *DbgValue = P.first;
787     MachineBasicBlock::iterator OrigPrivMI = P.second;
788     BB->splice(++OrigPrivMI, BB, DbgValue);
789   }
790   DbgValues.clear();
791   FirstDbgValue = NULL;
792 }