blob: 1d3241b8cc6b2d5361f20e203f2adf2bfb5848f5 [file] [log] [blame]
Andrew Trick96f678f2012-01-13 06:30:30 +00001//===- MachineScheduler.cpp - Machine Instruction 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// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16
Andrew Trick96f678f2012-01-13 06:30:30 +000017#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trickc174eaf2012-03-08 01:41:12 +000018#include "llvm/CodeGen/MachineScheduler.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000019#include "llvm/CodeGen/Passes.h"
Andrew Tricked395c82012-03-07 23:01:06 +000020#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000021#include "llvm/Analysis/AliasAnalysis.h"
Andrew Tricke9ef4ed2012-01-14 02:17:09 +000022#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000023#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"
Andrew Trick17d35e52012-03-14 04:00:41 +000028#include "llvm/ADT/PriorityQueue.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000029
Andrew Trickc6cf11b2012-01-17 06:55:07 +000030#include <queue>
31
Andrew Trick96f678f2012-01-13 06:30:30 +000032using namespace llvm;
33
Andrew Trick17d35e52012-03-14 04:00:41 +000034static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
35 cl::desc("Force top-down list scheduling"));
36static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
37 cl::desc("Force bottom-up list scheduling"));
38
Andrew Trick0df7f882012-03-07 00:18:25 +000039#ifndef NDEBUG
40static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
41 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000042
43static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
44 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000045#else
46static bool ViewMISchedDAGs = false;
47#endif // NDEBUG
48
Andrew Trick5edf2f02012-01-14 02:17:06 +000049//===----------------------------------------------------------------------===//
50// Machine Instruction Scheduling Pass and Registry
51//===----------------------------------------------------------------------===//
52
Andrew Trick96f678f2012-01-13 06:30:30 +000053namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000054/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000055class MachineScheduler : public MachineSchedContext,
56 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000057public:
Andrew Trick42b7a712012-01-17 06:55:03 +000058 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000059
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
61
62 virtual void releaseMemory() {}
63
64 virtual bool runOnMachineFunction(MachineFunction&);
65
66 virtual void print(raw_ostream &O, const Module* = 0) const;
67
68 static char ID; // Class identification, replacement for typeinfo
69};
70} // namespace
71
Andrew Trick42b7a712012-01-17 06:55:03 +000072char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000073
Andrew Trick42b7a712012-01-17 06:55:03 +000074char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000075
Andrew Trick42b7a712012-01-17 06:55:03 +000076INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000077 "Machine Instruction Scheduler", false, false)
78INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
79INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
80INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +000081INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000082 "Machine Instruction Scheduler", false, false)
83
Andrew Trick42b7a712012-01-17 06:55:03 +000084MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +000085: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +000086 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +000087}
88
Andrew Trick42b7a712012-01-17 06:55:03 +000089void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +000090 AU.setPreservesCFG();
91 AU.addRequiredID(MachineDominatorsID);
92 AU.addRequired<MachineLoopInfo>();
93 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +000094 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +000095 AU.addRequired<SlotIndexes>();
96 AU.addPreserved<SlotIndexes>();
97 AU.addRequired<LiveIntervals>();
98 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +000099 MachineFunctionPass::getAnalysisUsage(AU);
100}
101
Andrew Trick96f678f2012-01-13 06:30:30 +0000102MachinePassRegistry MachineSchedRegistry::Registry;
103
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000104/// A dummy default scheduler factory indicates whether the scheduler
105/// is overridden on the command line.
106static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
107 return 0;
108}
Andrew Trick96f678f2012-01-13 06:30:30 +0000109
110/// MachineSchedOpt allows command line selection of the scheduler.
111static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
112 RegisterPassParser<MachineSchedRegistry> >
113MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000114 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000115 cl::desc("Machine instruction scheduler to use"));
116
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000117static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000118DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000119 useDefaultMachineSched);
120
Andrew Trick17d35e52012-03-14 04:00:41 +0000121/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000122/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000123static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000124
Andrew Trickcb058d52012-03-14 04:00:38 +0000125/// Top-level MachineScheduler pass driver.
126///
127/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000128/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
129/// consistent with the DAG builder, which traverses the interior of the
130/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000131///
132/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000133/// simplifying the DAG builder's support for "special" target instructions.
134/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000135/// scheduling boundaries, for example to bundle the boudary instructions
136/// without reordering them. This creates complexity, because the target
137/// scheduler must update the RegionBegin and RegionEnd positions cached by
138/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
139/// design would be to split blocks at scheduling boundaries, but LLVM has a
140/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000141bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick96f678f2012-01-13 06:30:30 +0000142 // Initialize the context of the pass.
143 MF = &mf;
144 MLI = &getAnalysis<MachineLoopInfo>();
145 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000146 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000147 AA = &getAnalysis<AliasAnalysis>();
148
Lang Hames907cc8f2012-01-27 22:36:19 +0000149 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000150 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000151
152 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000153 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
154 if (Ctor == useDefaultMachineSched) {
155 // Get the default scheduler set by the target.
156 Ctor = MachineSchedRegistry::getDefault();
157 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000158 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000159 MachineSchedRegistry::setDefault(Ctor);
160 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000161 }
162 // Instantiate the selected scheduler.
163 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
164
165 // Visit all machine basic blocks.
166 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
167 MBB != MBBEnd; ++MBB) {
168
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000169 Scheduler->startBlock(MBB);
170
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000171 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000172 // region as soon as it is discovered. RegionEnd points the the scheduling
173 // boundary at the bottom of the region. The DAG does not include RegionEnd,
174 // but the region does (i.e. the next RegionEnd is above the previous
175 // RegionBegin). If the current block has no terminator then RegionEnd ==
176 // MBB->end() for the bottom region.
177 //
178 // The Scheduler may insert instructions during either schedule() or
179 // exitRegion(), even for empty regions. So the local iterators 'I' and
180 // 'RegionEnd' are invalid across these calls.
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000181 unsigned RemainingCount = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000182 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000183 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000184 // Avoid decrementing RegionEnd for blocks with no terminator.
185 if (RegionEnd != MBB->end()
186 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
187 --RegionEnd;
188 // Count the boundary instruction.
189 --RemainingCount;
190 }
191
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000192 // The next region starts above the previous region. Look backward in the
193 // instruction stream until we find the nearest boundary.
194 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick7799eb42012-03-09 03:46:39 +0000195 for(;I != MBB->begin(); --I, --RemainingCount) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000196 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
197 break;
198 }
Andrew Trick47c14452012-03-07 05:21:52 +0000199 // Notify the scheduler of the region, even if we may skip scheduling
200 // it. Perhaps it still needs to be bundled.
201 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
202
203 // Skip empty scheduling regions (0 or 1 schedulable instructions).
204 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000205 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000206 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000207 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000208 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000209 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000210 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000211 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
212 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
213 else dbgs() << "End";
214 dbgs() << " Remaining: " << RemainingCount << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000215
Andrew Trickd24da972012-03-09 03:46:42 +0000216 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000217 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000218 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000219
220 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000221 Scheduler->exitRegion();
222
223 // Scheduling has invalidated the current iterator 'I'. Ask the
224 // scheduler for the top of it's scheduled region.
225 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000226 }
227 assert(RemainingCount == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000228 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000229 }
Andrew Trick830da402012-04-01 07:24:23 +0000230 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000231 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000232 return true;
233}
234
Andrew Trick42b7a712012-01-17 06:55:03 +0000235void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000236 // unimplemented
237}
238
Andrew Trick5edf2f02012-01-14 02:17:06 +0000239//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000240// MachineSchedStrategy - Interface to a machine scheduling algorithm.
241//===----------------------------------------------------------------------===//
Andrew Trickc174eaf2012-03-08 01:41:12 +0000242
243namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000244class ScheduleDAGMI;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000245
Andrew Trick17d35e52012-03-14 04:00:41 +0000246/// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
247/// scheduling algorithm.
248///
249/// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
250/// in ScheduleDAGInstrs.h
251class MachineSchedStrategy {
252public:
253 virtual ~MachineSchedStrategy() {}
254
255 /// Initialize the strategy after building the DAG for a new region.
256 virtual void initialize(ScheduleDAGMI *DAG) = 0;
257
258 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
259 /// schedule the node at the top of the unscheduled region. Otherwise it will
260 /// be scheduled at the bottom.
261 virtual SUnit *pickNode(bool &IsTopNode) = 0;
262
263 /// When all predecessor dependencies have been resolved, free this node for
264 /// top-down scheduling.
265 virtual void releaseTopNode(SUnit *SU) = 0;
266 /// When all successor dependencies have been resolved, free this node for
267 /// bottom-up scheduling.
268 virtual void releaseBottomNode(SUnit *SU) = 0;
269};
270} // namespace
271
272//===----------------------------------------------------------------------===//
273// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
274// preservation.
275//===----------------------------------------------------------------------===//
276
277namespace {
278/// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
279/// machine instructions while updating LiveIntervals.
280class ScheduleDAGMI : public ScheduleDAGInstrs {
281 AliasAnalysis *AA;
282 MachineSchedStrategy *SchedImpl;
283
284 /// The top of the unscheduled zone.
285 MachineBasicBlock::iterator CurrentTop;
286
287 /// The bottom of the unscheduled zone.
288 MachineBasicBlock::iterator CurrentBottom;
Lang Hames23f1cbb2012-03-19 18:38:38 +0000289
290 /// The number of instructions scheduled so far. Used to cut off the
291 /// scheduler at the point determined by misched-cutoff.
292 unsigned NumInstrsScheduled;
Andrew Trick17d35e52012-03-14 04:00:41 +0000293public:
294 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
295 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
Lang Hames23f1cbb2012-03-19 18:38:38 +0000296 AA(C->AA), SchedImpl(S), CurrentTop(), CurrentBottom(),
297 NumInstrsScheduled(0) {}
Andrew Trick17d35e52012-03-14 04:00:41 +0000298
299 ~ScheduleDAGMI() {
300 delete SchedImpl;
301 }
302
303 MachineBasicBlock::iterator top() const { return CurrentTop; }
304 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
305
306 /// Implement ScheduleDAGInstrs interface.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000307 void schedule();
308
Andrew Trickc174eaf2012-03-08 01:41:12 +0000309protected:
Andrew Trick17d35e52012-03-14 04:00:41 +0000310 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
Andrew Trick0b0d8992012-03-21 04:12:07 +0000311 bool checkSchedLimit();
Andrew Trick17d35e52012-03-14 04:00:41 +0000312
Andrew Trickc174eaf2012-03-08 01:41:12 +0000313 void releaseSucc(SUnit *SU, SDep *SuccEdge);
314 void releaseSuccessors(SUnit *SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000315 void releasePred(SUnit *SU, SDep *PredEdge);
316 void releasePredecessors(SUnit *SU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000317};
318} // namespace
319
320/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
321/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick17d35e52012-03-14 04:00:41 +0000322void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000323 SUnit *SuccSU = SuccEdge->getSUnit();
324
325#ifndef NDEBUG
326 if (SuccSU->NumPredsLeft == 0) {
327 dbgs() << "*** Scheduling failed! ***\n";
328 SuccSU->dump(this);
329 dbgs() << " has been released too many times!\n";
330 llvm_unreachable(0);
331 }
332#endif
333 --SuccSU->NumPredsLeft;
334 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000335 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000336}
337
338/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000339void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000340 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
341 I != E; ++I) {
342 releaseSucc(SU, &*I);
343 }
344}
345
Andrew Trick17d35e52012-03-14 04:00:41 +0000346/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
347/// NumSuccsLeft reaches zero, release the predecessor node.
348void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
349 SUnit *PredSU = PredEdge->getSUnit();
350
351#ifndef NDEBUG
352 if (PredSU->NumSuccsLeft == 0) {
353 dbgs() << "*** Scheduling failed! ***\n";
354 PredSU->dump(this);
355 dbgs() << " has been released too many times!\n";
356 llvm_unreachable(0);
357 }
358#endif
359 --PredSU->NumSuccsLeft;
360 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
361 SchedImpl->releaseBottomNode(PredSU);
362}
363
364/// releasePredecessors - Call releasePred on each of SU's predecessors.
365void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
366 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
367 I != E; ++I) {
368 releasePred(SU, &*I);
369 }
370}
371
372void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
373 MachineBasicBlock::iterator InsertPos) {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000374 // Fix RegionBegin if the first instruction moves down.
375 if (&*RegionBegin == MI)
376 RegionBegin = llvm::next(RegionBegin);
Andrew Trick17d35e52012-03-14 04:00:41 +0000377 BB->splice(InsertPos, BB, MI);
378 LIS->handleMove(MI);
Andrew Trick1ce062f2012-03-21 04:12:10 +0000379 // Fix RegionBegin if another instruction moves above the first instruction.
Andrew Trick17d35e52012-03-14 04:00:41 +0000380 if (RegionBegin == InsertPos)
381 RegionBegin = MI;
382}
383
Andrew Trick0b0d8992012-03-21 04:12:07 +0000384bool ScheduleDAGMI::checkSchedLimit() {
385#ifndef NDEBUG
386 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
387 CurrentTop = CurrentBottom;
388 return false;
389 }
390 ++NumInstrsScheduled;
391#endif
392 return true;
393}
394
Andrew Trick17d35e52012-03-14 04:00:41 +0000395/// schedule - Called back from MachineScheduler::runOnMachineFunction
396/// after setting up the current scheduling region.
397void ScheduleDAGMI::schedule() {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000398 buildSchedGraph(AA);
399
400 DEBUG(dbgs() << "********** MI Scheduling **********\n");
401 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
402 SUnits[su].dumpAll(this));
403
404 if (ViewMISchedDAGs) viewGraph();
405
Andrew Trick17d35e52012-03-14 04:00:41 +0000406 SchedImpl->initialize(this);
407
408 // Release edges from the special Entry node or to the special Exit node.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000409 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000410 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000411
412 // Release all DAG roots for scheduling.
413 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
414 I != E; ++I) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000415 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000416 if (I->Preds.empty())
Andrew Trick17d35e52012-03-14 04:00:41 +0000417 SchedImpl->releaseTopNode(&(*I));
418 // A SUnit is ready to bottom schedule if it has no successors.
419 if (I->Succs.empty())
420 SchedImpl->releaseBottomNode(&(*I));
Andrew Trickc174eaf2012-03-08 01:41:12 +0000421 }
422
Andrew Trick17d35e52012-03-14 04:00:41 +0000423 CurrentTop = RegionBegin;
424 CurrentBottom = RegionEnd;
425 bool IsTopNode = false;
426 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
427 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
428 << " Scheduling Instruction:\n"; SU->dump(this));
Andrew Trick0b0d8992012-03-21 04:12:07 +0000429 if (!checkSchedLimit())
430 break;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000431
432 // Move the instruction to its new location in the instruction stream.
433 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000434
Andrew Trick17d35e52012-03-14 04:00:41 +0000435 if (IsTopNode) {
436 assert(SU->isTopReady() && "node still has unscheduled dependencies");
437 if (&*CurrentTop == MI)
438 ++CurrentTop;
439 else
440 moveInstruction(MI, CurrentTop);
441 // Release dependent instructions for scheduling.
442 releaseSuccessors(SU);
443 }
444 else {
445 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
446 if (&*llvm::prior(CurrentBottom) == MI)
447 --CurrentBottom;
448 else {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000449 if (&*CurrentTop == MI)
450 CurrentTop = llvm::next(CurrentTop);
Andrew Trick17d35e52012-03-14 04:00:41 +0000451 moveInstruction(MI, CurrentBottom);
452 CurrentBottom = MI;
453 }
454 // Release dependent instructions for scheduling.
455 releasePredecessors(SU);
456 }
457 SU->isScheduled = true;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000458 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000459 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
Andrew Trickc174eaf2012-03-08 01:41:12 +0000460}
461
462//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000463// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000464//===----------------------------------------------------------------------===//
465
466namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000467/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
468/// the schedule.
469class ConvergingScheduler : public MachineSchedStrategy {
470 ScheduleDAGMI *DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +0000471
Andrew Trick17d35e52012-03-14 04:00:41 +0000472 unsigned NumTopReady;
473 unsigned NumBottomReady;
474
475public:
476 virtual void initialize(ScheduleDAGMI *dag) {
477 DAG = dag;
478
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000479 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000480 "-misched-topdown incompatible with -misched-bottomup");
481 }
482
483 virtual SUnit *pickNode(bool &IsTopNode) {
484 if (DAG->top() == DAG->bottom())
485 return NULL;
486
487 // As an initial placeholder heuristic, schedule in the direction that has
488 // the fewest choices.
489 SUnit *SU;
490 if (ForceTopDown || (!ForceBottomUp && NumTopReady <= NumBottomReady)) {
491 SU = DAG->getSUnit(DAG->top());
492 IsTopNode = true;
493 }
494 else {
495 SU = DAG->getSUnit(llvm::prior(DAG->bottom()));
496 IsTopNode = false;
497 }
498 if (SU->isTopReady()) {
499 assert(NumTopReady > 0 && "bad ready count");
500 --NumTopReady;
501 }
502 if (SU->isBottomReady()) {
503 assert(NumBottomReady > 0 && "bad ready count");
504 --NumBottomReady;
505 }
506 return SU;
507 }
508
509 virtual void releaseTopNode(SUnit *SU) {
510 ++NumTopReady;
511 }
512 virtual void releaseBottomNode(SUnit *SU) {
513 ++NumBottomReady;
514 }
Andrew Trick42b7a712012-01-17 06:55:03 +0000515};
516} // namespace
517
Andrew Trick17d35e52012-03-14 04:00:41 +0000518/// Create the standard converging machine scheduler. This will be used as the
519/// default scheduler if the target does not set a default.
520static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000521 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000522 "-misched-topdown incompatible with -misched-bottomup");
523 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +0000524}
525static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000526ConvergingSchedRegistry("converge", "Standard converging scheduler.",
527 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +0000528
529//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +0000530// Machine Instruction Shuffler for Correctness Testing
531//===----------------------------------------------------------------------===//
532
Andrew Trick96f678f2012-01-13 06:30:30 +0000533#ifndef NDEBUG
534namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000535/// Apply a less-than relation on the node order, which corresponds to the
536/// instruction order prior to scheduling. IsReverse implements greater-than.
537template<bool IsReverse>
538struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000539 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +0000540 if (IsReverse)
541 return A->NodeNum > B->NodeNum;
542 else
543 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000544 }
545};
546
Andrew Trick96f678f2012-01-13 06:30:30 +0000547/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +0000548class InstructionShuffler : public MachineSchedStrategy {
549 bool IsAlternating;
550 bool IsTopDown;
551
552 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
553 // gives nodes with a higher number higher priority causing the latest
554 // instructions to be scheduled first.
555 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
556 TopQ;
557 // When scheduling bottom-up, use greater-than as the queue priority.
558 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
559 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +0000560public:
Andrew Trick17d35e52012-03-14 04:00:41 +0000561 InstructionShuffler(bool alternate, bool topdown)
562 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +0000563
Andrew Trick17d35e52012-03-14 04:00:41 +0000564 virtual void initialize(ScheduleDAGMI *) {
565 TopQ.clear();
566 BottomQ.clear();
567 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000568
Andrew Trick17d35e52012-03-14 04:00:41 +0000569 /// Implement MachineSchedStrategy interface.
570 /// -----------------------------------------
571
572 virtual SUnit *pickNode(bool &IsTopNode) {
573 SUnit *SU;
574 if (IsTopDown) {
575 do {
576 if (TopQ.empty()) return NULL;
577 SU = TopQ.top();
578 TopQ.pop();
579 } while (SU->isScheduled);
580 IsTopNode = true;
581 }
582 else {
583 do {
584 if (BottomQ.empty()) return NULL;
585 SU = BottomQ.top();
586 BottomQ.pop();
587 } while (SU->isScheduled);
588 IsTopNode = false;
589 }
590 if (IsAlternating)
591 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000592 return SU;
593 }
594
Andrew Trick17d35e52012-03-14 04:00:41 +0000595 virtual void releaseTopNode(SUnit *SU) {
596 TopQ.push(SU);
597 }
598 virtual void releaseBottomNode(SUnit *SU) {
599 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +0000600 }
601};
602} // namespace
603
Andrew Trickc174eaf2012-03-08 01:41:12 +0000604static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000605 bool Alternate = !ForceTopDown && !ForceBottomUp;
606 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000607 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000608 "-misched-topdown incompatible with -misched-bottomup");
609 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +0000610}
Andrew Trick17d35e52012-03-14 04:00:41 +0000611static MachineSchedRegistry ShufflerRegistry(
612 "shuffle", "Shuffle machine instructions alternating directions",
613 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +0000614#endif // !NDEBUG