1 //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
19 //===----------------------------------------------------------------------===//
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"
50 STATISTIC(NumNoops, "Number of noops inserted");
51 STATISTIC(NumStalls, "Number of pipeline stalls");
52 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
54 // Post-RA scheduling is enabled with
55 // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
56 // override the target.
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);
67 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
69 DebugDiv("postra-sched-debugdiv",
70 cl::desc("Debug control MBBs that are scheduled"),
71 cl::init(0), cl::Hidden);
73 DebugMod("postra-sched-debugmod",
74 cl::desc("Debug control MBBs that are scheduled"),
75 cl::init(0), cl::Hidden);
77 AntiDepBreaker::~AntiDepBreaker() { }
80 class PostRAScheduler : public MachineFunctionPass {
82 const TargetInstrInfo *TII;
83 RegisterClassInfo RegClassInfo;
87 PostRAScheduler() : MachineFunctionPass(ID) {}
89 void getAnalysisUsage(AnalysisUsage &AU) const {
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);
100 bool runOnMachineFunction(MachineFunction &Fn);
102 char PostRAScheduler::ID = 0;
104 class SchedulePostRATDList : public ScheduleDAGInstrs {
105 /// AvailableQueue - The priority queue to use for the available SUnits.
107 LatencyPriorityQueue AvailableQueue;
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;
115 /// Topo - A topological ordering for SUnits.
116 ScheduleDAGTopologicalSort Topo;
118 /// HazardRec - The hazard recognizer to use.
119 ScheduleHazardRecognizer *HazardRec;
121 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
122 AntiDepBreaker *AntiDepBreak;
124 /// AA - AliasAnalysis for making memory reference queries.
127 /// LiveRegs - true if the register is live.
130 /// The schedule. Null SUnit*'s represent noop instructions.
131 std::vector<SUnit*> Sequence;
134 SchedulePostRATDList(
135 MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
136 AliasAnalysis *AA, const RegisterClassInfo&,
137 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
138 SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
140 ~SchedulePostRATDList();
142 /// startBlock - Initialize register live-range state for scheduling in
145 void startBlock(MachineBasicBlock *BB);
147 /// Initialize the scheduler state for the next scheduling region.
148 virtual void enterRegion(MachineBasicBlock *bb,
149 MachineBasicBlock::iterator begin,
150 MachineBasicBlock::iterator end,
153 /// Notify that the scheduler has finished scheduling the current region.
154 virtual void exitRegion();
156 /// Schedule - Schedule the instruction range using list scheduling.
162 /// Observe - Update liveness information to account for the current
163 /// instruction, which will not be scheduled.
165 void Observe(MachineInstr *MI, unsigned Count);
167 /// finishBlock - Clean up register live-range state.
171 /// FixupKills - Fix register kill flags that have been made
172 /// invalid due to scheduling
174 void FixupKills(MachineBasicBlock *MBB);
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);
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);
188 void dumpSchedule() const;
192 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
194 INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
195 "Post RA top-down list latency scheduler", false, false)
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())
205 const TargetMachine &TM = MF.getTarget();
206 const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
208 TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins, this);
210 assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE ||
211 MRI.tracksLiveness()) &&
212 "Live-ins must be accurate for anti-dependency breaking");
214 ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
215 (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
216 ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
217 (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : NULL));
220 SchedulePostRATDList::~SchedulePostRATDList() {
225 /// Initialize state associated with the next scheduling region.
226 void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
227 MachineBasicBlock::iterator begin,
228 MachineBasicBlock::iterator end,
230 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
234 /// Print the schedule before exiting the region.
235 void SchedulePostRATDList::exitRegion() {
237 dbgs() << "*** Final schedule ***\n";
241 ScheduleDAGInstrs::exitRegion();
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])
250 dbgs() << "**** NOOP ****\n";
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>();
261 RegClassInfo.runOnMachineFunction(Fn);
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)
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,
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);
288 DEBUG(dbgs() << "PostRAScheduler\n");
290 SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
293 // Loop over all of the basic blocks
294 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
295 MBB != MBBe; ++MBB) {
297 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
299 static int bbcnt = 0;
300 if (bbcnt++ % DebugDiv != DebugMod)
302 dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getName()
303 << ":BB#" << MBB->getNumber() << " ***\n";
307 // Initialize register live-range state for scheduling in this block.
308 Scheduler.startBlock(MBB);
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();
325 CurrentCount = Count - 1;
326 Scheduler.Observe(MI, CurrentCount);
331 Count -= MI->getBundleSize();
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();
341 // Clean up register live-range state.
342 Scheduler.finishBlock();
344 // Update register kills
345 Scheduler.FixupKills(MBB);
351 /// StartBlock - Initialize register live-range state for scheduling in
354 void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
355 // Call the superclass.
356 ScheduleDAGInstrs::startBlock(BB);
358 // Reset the hazard recognizer and anti-dep breaker.
360 if (AntiDepBreak != NULL)
361 AntiDepBreak->StartBlock(BB);
364 /// Schedule - Schedule the instruction range using list scheduling.
366 void SchedulePostRATDList::schedule() {
367 // Build the scheduling graph.
370 if (AntiDepBreak != NULL) {
372 AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
373 EndIndex, DbgValues);
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();
385 NumFixedAnti += Broken;
389 DEBUG(dbgs() << "********** List Scheduling **********\n");
390 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
391 SUnits[su].dumpAll(this));
393 AvailableQueue.initNodes(SUnits);
394 ListScheduleTopDown();
395 AvailableQueue.releaseState();
398 /// Observe - Update liveness information to account for the current
399 /// instruction, which will not be scheduled.
401 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
402 if (AntiDepBreak != NULL)
403 AntiDepBreak->Observe(MI, Count, EndIndex);
406 /// FinishBlock - Clean up register live-range state.
408 void SchedulePostRATDList::finishBlock() {
409 if (AntiDepBreak != NULL)
410 AntiDepBreak->FinishBlock();
412 // Call the superclass.
413 ScheduleDAGInstrs::finishBlock();
416 /// StartBlockForKills - Initialize register live-range state for updating kills
418 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
419 // Start with no live registers.
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) {
429 // Repeat, for all subregs.
430 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
431 LiveRegs.set(*SubRegs);
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) {
442 // Repeat, for all subregs.
443 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
444 LiveRegs.set(*SubRegs);
450 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
451 MachineOperand &MO) {
452 // Setting kill flag...
458 // If MO itself is live, clear the kill flag...
459 if (LiveRegs.test(MO.getReg())) {
464 // If any subreg of MO is live, then create an imp-def for that
465 // subreg and keep MO marked as killed.
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,
485 /// FixupKills - Fix the register kill flags, they may have been made
486 /// incorrect by instruction reordering.
488 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
489 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
491 BitVector killedRegs(TRI->getNumRegs());
492 BitVector ReservedRegs = TRI->getReservedRegs(MF);
494 StartBlockForKills(MBB);
496 // Examine block from end to start...
497 unsigned Count = MBB->size();
498 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
500 MachineInstr *MI = --I;
501 if (MI->isDebugValue())
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);
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;
520 // Repeat for all subregs.
521 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
522 LiveRegs.reset(*SubRegs);
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
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;
536 if (!killedRegs.test(Reg)) {
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)) {
546 // If subreg is not live, then register is killed if it became
547 // live in this instruction
549 kill = !LiveRegs.test(Reg);
552 if (MO.isKill() != kill) {
553 DEBUG(dbgs() << "Fixing " << MO << " in ");
554 // Warning: ToggleKillFlag may invalidate MO.
555 ToggleKillFlag(MI, MO);
562 // Mark any used register (that is not using undef) and subregs as
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;
572 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
573 LiveRegs.set(*SubRegs);
578 //===----------------------------------------------------------------------===//
579 // Top-Down Scheduling
580 //===----------------------------------------------------------------------===//
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();
588 if (SuccSU->NumPredsLeft == 0) {
589 dbgs() << "*** Scheduling failed! ***\n";
591 dbgs() << " has been released too many times!\n";
595 --SuccSU->NumPredsLeft;
597 // Standard scheduler algorithms will recompute the depth of the successor
599 // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
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.
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);
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();
618 ReleaseSucc(SU, &*I);
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));
629 Sequence.push_back(SU);
630 assert(CurCycle >= SU->getDepth() &&
631 "Node scheduled above its depth!");
632 SU->setDepthToAtLeast(CurCycle);
634 ReleaseSuccessors(SU);
635 SU->isScheduled = true;
636 AvailableQueue.scheduledNode(SU);
639 /// ListScheduleTopDown - The main loop of list scheduling for top-down
641 void SchedulePostRATDList::ListScheduleTopDown() {
642 unsigned CurCycle = 0;
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).
650 // Release any successors of the special Entry node.
651 ReleaseSuccessors(&EntrySU);
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();
658 AvailableQueue.push(&SUnits[i]);
659 SUnits[i].isAvailable = true;
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;
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();
682 } else if (PendingQueue[i]->getDepth() < MinDepth)
683 MinDepth = PendingQueue[i]->getDepth();
686 DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
688 SUnit *FoundSUnit = 0;
689 bool HasNoopHazards = false;
690 while (!AvailableQueue.empty()) {
691 SUnit *CurSUnit = AvailableQueue.pop();
693 ScheduleHazardRecognizer::HazardType HT =
694 HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
695 if (HT == ScheduleHazardRecognizer::NoHazard) {
696 FoundSUnit = CurSUnit;
700 // Remember if this is a noop hazard.
701 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
703 NotReady.push_back(CurSUnit);
706 // Add the nodes that aren't ready back onto the available list.
707 if (!NotReady.empty()) {
708 AvailableQueue.push_all(NotReady);
712 // If we found a node to schedule...
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();
722 CycleHasInsts = false;
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();
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
745 CycleHasInsts = false;
750 unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
752 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
755 assert(Sequence.size() - Noops == ScheduledNodes &&
756 "The number of nodes scheduled doesn't match the expected number!");
760 // EmitSchedule - Emit the machine code in scheduled order.
761 void SchedulePostRATDList::EmitSchedule() {
762 RegionBegin = RegionEnd;
764 // If first instruction was a DBG_VALUE then put it back.
766 BB->splice(RegionEnd, BB, FirstDbgValue);
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());
773 // Null SUnit* is a noop.
774 TII->insertNoop(*BB, RegionEnd);
776 // Update the Begin iterator, as the first instruction in the block
777 // may have been scheduled later.
779 RegionBegin = prior(RegionEnd);
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);
791 FirstDbgValue = NULL;