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