1 //===- MachineScheduler.cpp - Machine Instruction 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 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "misched"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/MachineScheduler.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/OwningPtr.h"
34 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
35 cl::desc("Pop up a window to show MISched dags after they are processed"));
37 static bool ViewMISchedDAGs = false;
40 //===----------------------------------------------------------------------===//
41 // Machine Instruction Scheduling Pass and Registry
42 //===----------------------------------------------------------------------===//
45 /// MachineScheduler runs after coalescing and before register allocation.
46 class MachineScheduler : public MachineSchedContext,
47 public MachineFunctionPass {
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
53 virtual void releaseMemory() {}
55 virtual bool runOnMachineFunction(MachineFunction&);
57 virtual void print(raw_ostream &O, const Module* = 0) const;
59 static char ID; // Class identification, replacement for typeinfo
63 char MachineScheduler::ID = 0;
65 char &llvm::MachineSchedulerID = MachineScheduler::ID;
67 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
68 "Machine Instruction Scheduler", false, false)
69 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
70 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
71 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
72 INITIALIZE_PASS_END(MachineScheduler, "misched",
73 "Machine Instruction Scheduler", false, false)
75 MachineScheduler::MachineScheduler()
76 : MachineFunctionPass(ID) {
77 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
80 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.addRequiredID(MachineDominatorsID);
83 AU.addRequired<MachineLoopInfo>();
84 AU.addRequired<AliasAnalysis>();
85 AU.addRequired<TargetPassConfig>();
86 AU.addRequired<SlotIndexes>();
87 AU.addPreserved<SlotIndexes>();
88 AU.addRequired<LiveIntervals>();
89 AU.addPreserved<LiveIntervals>();
90 MachineFunctionPass::getAnalysisUsage(AU);
93 MachinePassRegistry MachineSchedRegistry::Registry;
95 /// A dummy default scheduler factory indicates whether the scheduler
96 /// is overridden on the command line.
97 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
101 /// MachineSchedOpt allows command line selection of the scheduler.
102 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
103 RegisterPassParser<MachineSchedRegistry> >
104 MachineSchedOpt("misched",
105 cl::init(&useDefaultMachineSched), cl::Hidden,
106 cl::desc("Machine instruction scheduler to use"));
108 static MachineSchedRegistry
109 SchedDefaultRegistry("default", "Use the target's default scheduler choice.",
110 useDefaultMachineSched);
112 /// Forward declare the common machine scheduler. This will be used as the
113 /// default scheduler if the target does not set a default.
114 static ScheduleDAGInstrs *createCommonMachineSched(MachineSchedContext *C);
116 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
117 // Initialize the context of the pass.
119 MLI = &getAnalysis<MachineLoopInfo>();
120 MDT = &getAnalysis<MachineDominatorTree>();
121 PassConfig = &getAnalysis<TargetPassConfig>();
122 AA = &getAnalysis<AliasAnalysis>();
124 LIS = &getAnalysis<LiveIntervals>();
125 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
127 // Select the scheduler, or set the default.
128 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
129 if (Ctor == useDefaultMachineSched) {
130 // Get the default scheduler set by the target.
131 Ctor = MachineSchedRegistry::getDefault();
133 Ctor = createCommonMachineSched;
134 MachineSchedRegistry::setDefault(Ctor);
137 // Instantiate the selected scheduler.
138 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
140 // Visit all machine basic blocks.
141 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
142 MBB != MBBEnd; ++MBB) {
144 // Break the block into scheduling regions [I, RegionEnd), and schedule each
145 // region as soon as it is discovered.
146 unsigned RemainingCount = MBB->size();
147 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
148 RegionEnd != MBB->begin();) {
149 Scheduler->startBlock(MBB);
150 // The next region starts above the previous region. Look backward in the
151 // instruction stream until we find the nearest boundary.
152 MachineBasicBlock::iterator I = RegionEnd;
153 for(;I != MBB->begin(); --I, --RemainingCount) {
154 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
157 // Notify the scheduler of the region, even if we may skip scheduling
158 // it. Perhaps it still needs to be bundled.
159 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
161 // Skip empty scheduling regions (0 or 1 schedulable instructions).
162 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
163 RegionEnd = llvm::prior(RegionEnd);
166 // Close the current region. Bundle the terminator if needed.
167 Scheduler->exitRegion();
170 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
171 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
172 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
173 else dbgs() << "End";
174 dbgs() << " Remaining: " << RemainingCount << "\n");
176 // Schedule a region: possibly reorder instructions.
177 Scheduler->schedule();
179 // Close the current region.
180 Scheduler->exitRegion();
182 // Scheduling has invalidated the current iterator 'I'. Ask the
183 // scheduler for the top of it's scheduled region.
184 RegionEnd = Scheduler->begin();
186 assert(RemainingCount == 0 && "Instruction count mismatch!");
187 Scheduler->finishBlock();
192 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
196 //===----------------------------------------------------------------------===//
197 // ScheduleTopeDownLive - Base class for basic top-down scheduling with
198 // LiveIntervals preservation.
199 // ===----------------------------------------------------------------------===//
202 /// ScheduleTopDownLive is an implementation of ScheduleDAGInstrs that schedules
203 /// machine instructions while updating LiveIntervals.
204 class ScheduleTopDownLive : public ScheduleDAGInstrs {
207 ScheduleTopDownLive(MachineSchedContext *C):
208 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
211 /// ScheduleDAGInstrs interface.
214 /// Interface implemented by the selected top-down liveinterval scheduler.
216 /// Pick the next node to schedule, or return NULL.
217 virtual SUnit *pickNode() = 0;
219 /// When all preceeding dependencies have been resolved, free this node for
221 virtual void releaseNode(SUnit *SU) = 0;
224 void releaseSucc(SUnit *SU, SDep *SuccEdge);
225 void releaseSuccessors(SUnit *SU);
229 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
230 /// NumPredsLeft reaches zero, release the successor node.
231 void ScheduleTopDownLive::releaseSucc(SUnit *SU, SDep *SuccEdge) {
232 SUnit *SuccSU = SuccEdge->getSUnit();
235 if (SuccSU->NumPredsLeft == 0) {
236 dbgs() << "*** Scheduling failed! ***\n";
238 dbgs() << " has been released too many times!\n";
242 --SuccSU->NumPredsLeft;
243 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
247 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
248 void ScheduleTopDownLive::releaseSuccessors(SUnit *SU) {
249 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
251 releaseSucc(SU, &*I);
255 /// schedule - This is called back from ScheduleDAGInstrs::Run() when it's
256 /// time to do some work.
257 void ScheduleTopDownLive::schedule() {
260 DEBUG(dbgs() << "********** MI Scheduling **********\n");
261 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
262 SUnits[su].dumpAll(this));
264 if (ViewMISchedDAGs) viewGraph();
266 // Release any successors of the special Entry node. It is currently unused,
267 // but we keep up appearances.
268 releaseSuccessors(&EntrySU);
270 // Release all DAG roots for scheduling.
271 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
273 // A SUnit is ready to schedule if it has no predecessors.
274 if (I->Preds.empty())
278 MachineBasicBlock::iterator InsertPos = RegionBegin;
279 while (SUnit *SU = pickNode()) {
280 DEBUG(dbgs() << "*** Scheduling Instruction:\n"; SU->dump(this));
282 // Move the instruction to its new location in the instruction stream.
283 MachineInstr *MI = SU->getInstr();
284 if (&*InsertPos == MI)
287 BB->splice(InsertPos, BB, MI);
289 if (RegionBegin == InsertPos)
293 // Release dependent instructions for scheduling.
294 releaseSuccessors(SU);
298 //===----------------------------------------------------------------------===//
299 // Placeholder for the default machine instruction scheduler.
300 //===----------------------------------------------------------------------===//
303 class CommonMachineScheduler : public ScheduleDAGInstrs {
306 CommonMachineScheduler(MachineSchedContext *C):
307 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
310 /// schedule - This is called back from ScheduleDAGInstrs::Run() when it's
311 /// time to do some work.
316 /// The common machine scheduler will be used as the default scheduler if the
317 /// target does not set a default.
318 static ScheduleDAGInstrs *createCommonMachineSched(MachineSchedContext *C) {
319 return new CommonMachineScheduler(C);
321 static MachineSchedRegistry
322 SchedCommonRegistry("common", "Use the target's default scheduler choice.",
323 createCommonMachineSched);
325 /// Schedule - This is called back from ScheduleDAGInstrs::Run() when it's
326 /// time to do some work.
327 void CommonMachineScheduler::schedule() {
330 DEBUG(dbgs() << "********** MI Scheduling **********\n");
331 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
332 SUnits[su].dumpAll(this));
334 // TODO: Put interesting things here.
336 // When this is fully implemented, it will become a subclass of
337 // ScheduleTopDownLive. So this driver will disappear.
340 //===----------------------------------------------------------------------===//
341 // Machine Instruction Shuffler for Correctness Testing
342 //===----------------------------------------------------------------------===//
346 // Nodes with a higher number have higher priority. This way we attempt to
347 // schedule the latest instructions earliest.
349 // TODO: Relies on the property of the BuildSchedGraph that results in SUnits
350 // being ordered in sequence top-down.
351 struct ShuffleSUnitOrder {
352 bool operator()(SUnit *A, SUnit *B) const {
353 return A->NodeNum < B->NodeNum;
357 /// Reorder instructions as much as possible.
358 class InstructionShuffler : public ScheduleTopDownLive {
359 std::priority_queue<SUnit*, std::vector<SUnit*>, ShuffleSUnitOrder> Queue;
361 InstructionShuffler(MachineSchedContext *C):
362 ScheduleTopDownLive(C) {}
364 /// ScheduleTopDownLive Interface
366 virtual SUnit *pickNode() {
367 if (Queue.empty()) return NULL;
368 SUnit *SU = Queue.top();
373 virtual void releaseNode(SUnit *SU) {
379 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
380 return new InstructionShuffler(C);
382 static MachineSchedRegistry ShufflerRegistry("shuffle",
383 "Shuffle machine instructions",
384 createInstructionShuffler);