blob: 7a099cdadef3ae054090e23d7149d279e7c64a4f [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 Trick86b7e2a2012-04-24 20:36:19 +000017#include "RegisterClassInfo.h"
Andrew Trick006e1ab2012-04-24 17:56:43 +000018#include "RegisterPressure.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trickc174eaf2012-03-08 01:41:12 +000020#include "llvm/CodeGen/MachineScheduler.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000021#include "llvm/CodeGen/Passes.h"
Andrew Tricked395c82012-03-07 23:01:06 +000022#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000023#include "llvm/Analysis/AliasAnalysis.h"
Andrew Tricke9ef4ed2012-01-14 02:17:09 +000024#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/ADT/OwningPtr.h"
Andrew Trick17d35e52012-03-14 04:00:41 +000030#include "llvm/ADT/PriorityQueue.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000031
Andrew Trickc6cf11b2012-01-17 06:55:07 +000032#include <queue>
33
Andrew Trick96f678f2012-01-13 06:30:30 +000034using namespace llvm;
35
Andrew Trick17d35e52012-03-14 04:00:41 +000036static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
37 cl::desc("Force top-down list scheduling"));
38static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
39 cl::desc("Force bottom-up list scheduling"));
40
Andrew Trick0df7f882012-03-07 00:18:25 +000041#ifndef NDEBUG
42static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000044
45static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000047#else
48static bool ViewMISchedDAGs = false;
49#endif // NDEBUG
50
Andrew Trick5edf2f02012-01-14 02:17:06 +000051//===----------------------------------------------------------------------===//
52// Machine Instruction Scheduling Pass and Registry
53//===----------------------------------------------------------------------===//
54
Andrew Trick86b7e2a2012-04-24 20:36:19 +000055MachineSchedContext::MachineSchedContext():
56 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
57 RegClassInfo = new RegisterClassInfo();
58}
59
60MachineSchedContext::~MachineSchedContext() {
61 delete RegClassInfo;
62}
63
Andrew Trick96f678f2012-01-13 06:30:30 +000064namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000065/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000066class MachineScheduler : public MachineSchedContext,
67 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000068public:
Andrew Trick42b7a712012-01-17 06:55:03 +000069 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000070
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
72
73 virtual void releaseMemory() {}
74
75 virtual bool runOnMachineFunction(MachineFunction&);
76
77 virtual void print(raw_ostream &O, const Module* = 0) const;
78
79 static char ID; // Class identification, replacement for typeinfo
80};
81} // namespace
82
Andrew Trick42b7a712012-01-17 06:55:03 +000083char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000084
Andrew Trick42b7a712012-01-17 06:55:03 +000085char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000086
Andrew Trick42b7a712012-01-17 06:55:03 +000087INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000088 "Machine Instruction Scheduler", false, false)
89INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
91INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +000092INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000093 "Machine Instruction Scheduler", false, false)
94
Andrew Trick42b7a712012-01-17 06:55:03 +000095MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +000096: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +000097 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +000098}
99
Andrew Trick42b7a712012-01-17 06:55:03 +0000100void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000101 AU.setPreservesCFG();
102 AU.addRequiredID(MachineDominatorsID);
103 AU.addRequired<MachineLoopInfo>();
104 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000105 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000106 AU.addRequired<SlotIndexes>();
107 AU.addPreserved<SlotIndexes>();
108 AU.addRequired<LiveIntervals>();
109 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000110 MachineFunctionPass::getAnalysisUsage(AU);
111}
112
Andrew Trick96f678f2012-01-13 06:30:30 +0000113MachinePassRegistry MachineSchedRegistry::Registry;
114
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000115/// A dummy default scheduler factory indicates whether the scheduler
116/// is overridden on the command line.
117static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
118 return 0;
119}
Andrew Trick96f678f2012-01-13 06:30:30 +0000120
121/// MachineSchedOpt allows command line selection of the scheduler.
122static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
123 RegisterPassParser<MachineSchedRegistry> >
124MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000125 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000126 cl::desc("Machine instruction scheduler to use"));
127
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000128static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000129DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000130 useDefaultMachineSched);
131
Andrew Trick17d35e52012-03-14 04:00:41 +0000132/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000133/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000134static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000135
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000136
137/// Decrement this iterator until reaching the top or a non-debug instr.
138static MachineBasicBlock::iterator
139priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
140 assert(I != Beg && "reached the top of the region, cannot decrement");
141 while (--I != Beg) {
142 if (!I->isDebugValue())
143 break;
144 }
145 return I;
146}
147
148/// If this iterator is a debug value, increment until reaching the End or a
149/// non-debug instruction.
150static MachineBasicBlock::iterator
151nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
152 while(I != End) {
153 if (!I->isDebugValue())
154 break;
155 }
156 return I;
157}
158
Andrew Trickcb058d52012-03-14 04:00:38 +0000159/// Top-level MachineScheduler pass driver.
160///
161/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000162/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
163/// consistent with the DAG builder, which traverses the interior of the
164/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000165///
166/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000167/// simplifying the DAG builder's support for "special" target instructions.
168/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000169/// scheduling boundaries, for example to bundle the boudary instructions
170/// without reordering them. This creates complexity, because the target
171/// scheduler must update the RegionBegin and RegionEnd positions cached by
172/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
173/// design would be to split blocks at scheduling boundaries, but LLVM has a
174/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000175bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000176 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
177
Andrew Trick96f678f2012-01-13 06:30:30 +0000178 // Initialize the context of the pass.
179 MF = &mf;
180 MLI = &getAnalysis<MachineLoopInfo>();
181 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000182 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000183 AA = &getAnalysis<AliasAnalysis>();
184
Lang Hames907cc8f2012-01-27 22:36:19 +0000185 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000186 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000187
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000188 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000189
Andrew Trick96f678f2012-01-13 06:30:30 +0000190 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000191 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
192 if (Ctor == useDefaultMachineSched) {
193 // Get the default scheduler set by the target.
194 Ctor = MachineSchedRegistry::getDefault();
195 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000196 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000197 MachineSchedRegistry::setDefault(Ctor);
198 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000199 }
200 // Instantiate the selected scheduler.
201 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
202
203 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000204 //
205 // TODO: Visit blocks in global postorder or postorder within the bottom-up
206 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000207 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
208 MBB != MBBEnd; ++MBB) {
209
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000210 Scheduler->startBlock(MBB);
211
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000212 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000213 // region as soon as it is discovered. RegionEnd points the the scheduling
214 // boundary at the bottom of the region. The DAG does not include RegionEnd,
215 // but the region does (i.e. the next RegionEnd is above the previous
216 // RegionBegin). If the current block has no terminator then RegionEnd ==
217 // MBB->end() for the bottom region.
218 //
219 // The Scheduler may insert instructions during either schedule() or
220 // exitRegion(), even for empty regions. So the local iterators 'I' and
221 // 'RegionEnd' are invalid across these calls.
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000222 unsigned RemainingCount = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000223 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000224 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000225
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000226 // Avoid decrementing RegionEnd for blocks with no terminator.
227 if (RegionEnd != MBB->end()
228 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
229 --RegionEnd;
230 // Count the boundary instruction.
231 --RemainingCount;
232 }
233
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000234 // The next region starts above the previous region. Look backward in the
235 // instruction stream until we find the nearest boundary.
236 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick7799eb42012-03-09 03:46:39 +0000237 for(;I != MBB->begin(); --I, --RemainingCount) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000238 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
239 break;
240 }
Andrew Trick47c14452012-03-07 05:21:52 +0000241 // Notify the scheduler of the region, even if we may skip scheduling
242 // it. Perhaps it still needs to be bundled.
243 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
244
245 // Skip empty scheduling regions (0 or 1 schedulable instructions).
246 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000247 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000248 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000249 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000250 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000251 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000252 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000253 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
254 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
255 else dbgs() << "End";
256 dbgs() << " Remaining: " << RemainingCount << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000257
Andrew Trickd24da972012-03-09 03:46:42 +0000258 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000259 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000260 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000261
262 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000263 Scheduler->exitRegion();
264
265 // Scheduling has invalidated the current iterator 'I'. Ask the
266 // scheduler for the top of it's scheduled region.
267 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000268 }
269 assert(RemainingCount == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000270 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000271 }
Andrew Trick830da402012-04-01 07:24:23 +0000272 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000273 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000274 return true;
275}
276
Andrew Trick42b7a712012-01-17 06:55:03 +0000277void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000278 // unimplemented
279}
280
Andrew Trick5edf2f02012-01-14 02:17:06 +0000281//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000282// MachineSchedStrategy - Interface to a machine scheduling algorithm.
283//===----------------------------------------------------------------------===//
Andrew Trickc174eaf2012-03-08 01:41:12 +0000284
285namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000286class ScheduleDAGMI;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000287
Andrew Trick17d35e52012-03-14 04:00:41 +0000288/// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
289/// scheduling algorithm.
290///
291/// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
292/// in ScheduleDAGInstrs.h
293class MachineSchedStrategy {
294public:
295 virtual ~MachineSchedStrategy() {}
296
297 /// Initialize the strategy after building the DAG for a new region.
298 virtual void initialize(ScheduleDAGMI *DAG) = 0;
299
300 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
301 /// schedule the node at the top of the unscheduled region. Otherwise it will
302 /// be scheduled at the bottom.
303 virtual SUnit *pickNode(bool &IsTopNode) = 0;
304
305 /// When all predecessor dependencies have been resolved, free this node for
306 /// top-down scheduling.
307 virtual void releaseTopNode(SUnit *SU) = 0;
308 /// When all successor dependencies have been resolved, free this node for
309 /// bottom-up scheduling.
310 virtual void releaseBottomNode(SUnit *SU) = 0;
311};
312} // namespace
313
314//===----------------------------------------------------------------------===//
315// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
316// preservation.
317//===----------------------------------------------------------------------===//
318
319namespace {
320/// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
321/// machine instructions while updating LiveIntervals.
322class ScheduleDAGMI : public ScheduleDAGInstrs {
323 AliasAnalysis *AA;
Andrew Trick006e1ab2012-04-24 17:56:43 +0000324 RegisterClassInfo *RegClassInfo;
Andrew Trick17d35e52012-03-14 04:00:41 +0000325 MachineSchedStrategy *SchedImpl;
326
Andrew Trick7f8ab782012-05-10 21:06:10 +0000327 MachineBasicBlock::iterator LiveRegionEnd;
328
Andrew Trick006e1ab2012-04-24 17:56:43 +0000329 // Register pressure in this region computed by buildSchedGraph.
330 IntervalPressure RegPressure;
331 RegPressureTracker RPTracker;
332
Andrew Trick17d35e52012-03-14 04:00:41 +0000333 /// The top of the unscheduled zone.
334 MachineBasicBlock::iterator CurrentTop;
Andrew Trick7f8ab782012-05-10 21:06:10 +0000335 IntervalPressure TopPressure;
336 RegPressureTracker TopRPTracker;
Andrew Trick17d35e52012-03-14 04:00:41 +0000337
338 /// The bottom of the unscheduled zone.
339 MachineBasicBlock::iterator CurrentBottom;
Andrew Trick7f8ab782012-05-10 21:06:10 +0000340 IntervalPressure BotPressure;
341 RegPressureTracker BotRPTracker;
Lang Hames23f1cbb2012-03-19 18:38:38 +0000342
343 /// The number of instructions scheduled so far. Used to cut off the
344 /// scheduler at the point determined by misched-cutoff.
345 unsigned NumInstrsScheduled;
Andrew Trick17d35e52012-03-14 04:00:41 +0000346public:
347 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
348 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000349 AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S),
Andrew Trick7f8ab782012-05-10 21:06:10 +0000350 RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
351 CurrentBottom(), BotRPTracker(BotPressure), NumInstrsScheduled(0) {}
Andrew Trick17d35e52012-03-14 04:00:41 +0000352
353 ~ScheduleDAGMI() {
354 delete SchedImpl;
355 }
356
357 MachineBasicBlock::iterator top() const { return CurrentTop; }
358 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
359
Andrew Trick006e1ab2012-04-24 17:56:43 +0000360 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
361 /// region. This covers all instructions in a block, while schedule() may only
362 /// cover a subset.
363 void enterRegion(MachineBasicBlock *bb,
364 MachineBasicBlock::iterator begin,
365 MachineBasicBlock::iterator end,
366 unsigned endcount);
367
368 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
369 /// reorderable instructions.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000370 void schedule();
371
Andrew Trick7196a8f2012-05-10 21:06:16 +0000372 /// Get current register pressure for the top scheduled instructions.
373 const IntervalPressure &getTopPressure() const { return TopPressure; }
374 const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
375
376 /// Get current register pressure for the bottom scheduled instructions.
377 const IntervalPressure &getBotPressure() const { return BotPressure; }
378 const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
379
380 /// Get register pressure for the entire scheduling region before scheduling.
381 const IntervalPressure &getRegPressure() const { return RegPressure; }
382
Andrew Trickc174eaf2012-03-08 01:41:12 +0000383protected:
Andrew Trick7f8ab782012-05-10 21:06:10 +0000384 void initRegPressure();
385
Andrew Trick17d35e52012-03-14 04:00:41 +0000386 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
Andrew Trick0b0d8992012-03-21 04:12:07 +0000387 bool checkSchedLimit();
Andrew Trick17d35e52012-03-14 04:00:41 +0000388
Andrew Trickc174eaf2012-03-08 01:41:12 +0000389 void releaseSucc(SUnit *SU, SDep *SuccEdge);
390 void releaseSuccessors(SUnit *SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000391 void releasePred(SUnit *SU, SDep *PredEdge);
392 void releasePredecessors(SUnit *SU);
Andrew Trick000b2502012-04-24 18:04:37 +0000393
394 void placeDebugValues();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000395};
396} // namespace
397
398/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
399/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick17d35e52012-03-14 04:00:41 +0000400void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000401 SUnit *SuccSU = SuccEdge->getSUnit();
402
403#ifndef NDEBUG
404 if (SuccSU->NumPredsLeft == 0) {
405 dbgs() << "*** Scheduling failed! ***\n";
406 SuccSU->dump(this);
407 dbgs() << " has been released too many times!\n";
408 llvm_unreachable(0);
409 }
410#endif
411 --SuccSU->NumPredsLeft;
412 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000413 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000414}
415
416/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000417void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000418 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
419 I != E; ++I) {
420 releaseSucc(SU, &*I);
421 }
422}
423
Andrew Trick17d35e52012-03-14 04:00:41 +0000424/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
425/// NumSuccsLeft reaches zero, release the predecessor node.
426void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
427 SUnit *PredSU = PredEdge->getSUnit();
428
429#ifndef NDEBUG
430 if (PredSU->NumSuccsLeft == 0) {
431 dbgs() << "*** Scheduling failed! ***\n";
432 PredSU->dump(this);
433 dbgs() << " has been released too many times!\n";
434 llvm_unreachable(0);
435 }
436#endif
437 --PredSU->NumSuccsLeft;
438 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
439 SchedImpl->releaseBottomNode(PredSU);
440}
441
442/// releasePredecessors - Call releasePred on each of SU's predecessors.
443void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
444 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
445 I != E; ++I) {
446 releasePred(SU, &*I);
447 }
448}
449
450void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
451 MachineBasicBlock::iterator InsertPos) {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000452 // Fix RegionBegin if the first instruction moves down.
453 if (&*RegionBegin == MI)
454 RegionBegin = llvm::next(RegionBegin);
Andrew Trick17d35e52012-03-14 04:00:41 +0000455 BB->splice(InsertPos, BB, MI);
456 LIS->handleMove(MI);
Andrew Trick1ce062f2012-03-21 04:12:10 +0000457 // Fix RegionBegin if another instruction moves above the first instruction.
Andrew Trick17d35e52012-03-14 04:00:41 +0000458 if (RegionBegin == InsertPos)
459 RegionBegin = MI;
Andrew Trick7f8ab782012-05-10 21:06:10 +0000460 // Fix TopRPTracker if we move something above CurrentTop.
461 if (CurrentTop == InsertPos)
462 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000463}
464
Andrew Trick0b0d8992012-03-21 04:12:07 +0000465bool ScheduleDAGMI::checkSchedLimit() {
466#ifndef NDEBUG
467 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
468 CurrentTop = CurrentBottom;
469 return false;
470 }
471 ++NumInstrsScheduled;
472#endif
473 return true;
474}
475
Andrew Trick006e1ab2012-04-24 17:56:43 +0000476/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
477/// crossing a scheduling boundary. [begin, end) includes all instructions in
478/// the region, including the boundary itself and single-instruction regions
479/// that don't get scheduled.
480void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
481 MachineBasicBlock::iterator begin,
482 MachineBasicBlock::iterator end,
483 unsigned endcount)
484{
485 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000486
487 // For convenience remember the end of the liveness region.
488 LiveRegionEnd =
489 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
490}
491
492// Setup the register pressure trackers for the top scheduled top and bottom
493// scheduled regions.
494void ScheduleDAGMI::initRegPressure() {
495 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
496 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
497
498 // Close the RPTracker to finalize live ins.
499 RPTracker.closeRegion();
500
501 // Initialize the live ins and live outs.
502 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
503 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
504
505 // Close one end of the tracker so we can call
506 // getMaxUpward/DownwardPressureDelta before advancing across any
507 // instructions. This converts currently live regs into live ins/outs.
508 TopRPTracker.closeTop();
509 BotRPTracker.closeBottom();
510
511 // Account for liveness generated by the region boundary.
512 if (LiveRegionEnd != RegionEnd)
513 BotRPTracker.recede();
514
515 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick006e1ab2012-04-24 17:56:43 +0000516}
517
Andrew Trick17d35e52012-03-14 04:00:41 +0000518/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000519/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
520/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick17d35e52012-03-14 04:00:41 +0000521void ScheduleDAGMI::schedule() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000522 // Initialize the register pressure tracker used by buildSchedGraph.
523 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000524
Andrew Trick7f8ab782012-05-10 21:06:10 +0000525 // Account for liveness generate by the region boundary.
526 if (LiveRegionEnd != RegionEnd)
527 RPTracker.recede();
528
529 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000530 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000531
Andrew Trick7f8ab782012-05-10 21:06:10 +0000532 // Initialize top/bottom trackers after computing region pressure.
533 initRegPressure();
534
Andrew Trickc174eaf2012-03-08 01:41:12 +0000535 DEBUG(dbgs() << "********** MI Scheduling **********\n");
536 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
537 SUnits[su].dumpAll(this));
538
539 if (ViewMISchedDAGs) viewGraph();
540
Andrew Trick17d35e52012-03-14 04:00:41 +0000541 SchedImpl->initialize(this);
542
543 // Release edges from the special Entry node or to the special Exit node.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000544 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000545 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000546
547 // Release all DAG roots for scheduling.
548 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
549 I != E; ++I) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000550 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000551 if (I->Preds.empty())
Andrew Trick17d35e52012-03-14 04:00:41 +0000552 SchedImpl->releaseTopNode(&(*I));
553 // A SUnit is ready to bottom schedule if it has no successors.
554 if (I->Succs.empty())
555 SchedImpl->releaseBottomNode(&(*I));
Andrew Trickc174eaf2012-03-08 01:41:12 +0000556 }
557
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000558 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick17d35e52012-03-14 04:00:41 +0000559 CurrentBottom = RegionEnd;
560 bool IsTopNode = false;
561 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
562 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
563 << " Scheduling Instruction:\n"; SU->dump(this));
Andrew Trick0b0d8992012-03-21 04:12:07 +0000564 if (!checkSchedLimit())
565 break;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000566
567 // Move the instruction to its new location in the instruction stream.
568 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000569
Andrew Trick17d35e52012-03-14 04:00:41 +0000570 if (IsTopNode) {
571 assert(SU->isTopReady() && "node still has unscheduled dependencies");
572 if (&*CurrentTop == MI)
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000573 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000574 else
575 moveInstruction(MI, CurrentTop);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000576
577 // Update top scheduled pressure.
578 TopRPTracker.advance();
579 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
580
Andrew Trick17d35e52012-03-14 04:00:41 +0000581 // Release dependent instructions for scheduling.
582 releaseSuccessors(SU);
583 }
584 else {
585 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000586 MachineBasicBlock::iterator priorII =
587 priorNonDebug(CurrentBottom, CurrentTop);
588 if (&*priorII == MI)
589 CurrentBottom = priorII;
Andrew Trick17d35e52012-03-14 04:00:41 +0000590 else {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000591 if (&*CurrentTop == MI)
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000592 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000593 moveInstruction(MI, CurrentBottom);
594 CurrentBottom = MI;
595 }
Andrew Trick7f8ab782012-05-10 21:06:10 +0000596 // Update bottom scheduled pressure.
597 BotRPTracker.recede();
598 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
599
Andrew Trick17d35e52012-03-14 04:00:41 +0000600 // Release dependent instructions for scheduling.
601 releasePredecessors(SU);
602 }
603 SU->isScheduled = true;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000604 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000605 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
Andrew Trick000b2502012-04-24 18:04:37 +0000606
607 placeDebugValues();
608}
609
610/// Reinsert any remaining debug_values, just like the PostRA scheduler.
611void ScheduleDAGMI::placeDebugValues() {
612 // If first instruction was a DBG_VALUE then put it back.
613 if (FirstDbgValue) {
614 BB->splice(RegionBegin, BB, FirstDbgValue);
615 RegionBegin = FirstDbgValue;
616 }
617
618 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
619 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
620 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
621 MachineInstr *DbgValue = P.first;
622 MachineBasicBlock::iterator OrigPrevMI = P.second;
623 BB->splice(++OrigPrevMI, BB, DbgValue);
624 if (OrigPrevMI == llvm::prior(RegionEnd))
625 RegionEnd = DbgValue;
626 }
627 DbgValues.clear();
628 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000629}
630
631//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000632// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000633//===----------------------------------------------------------------------===//
634
635namespace {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000636/// Wrapper around a vector of SUnits with some basic convenience methods.
Andrew Trickd38f87e2012-05-10 21:06:12 +0000637struct ReadyQ {
638 typedef std::vector<SUnit*>::iterator iterator;
639
640 unsigned ID;
641 std::vector<SUnit*> Queue;
642
643 ReadyQ(unsigned id): ID(id) {}
644
645 bool isInQueue(SUnit *SU) const {
646 return SU->NodeQueueId & ID;
647 }
648
649 bool empty() const { return Queue.empty(); }
650
Andrew Trick16716c72012-05-10 21:06:14 +0000651 iterator begin() { return Queue.begin(); }
652
653 iterator end() { return Queue.end(); }
654
Andrew Trickd38f87e2012-05-10 21:06:12 +0000655 iterator find(SUnit *SU) {
656 return std::find(Queue.begin(), Queue.end(), SU);
657 }
658
659 void push(SUnit *SU) {
660 Queue.push_back(SU);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000661 SU->NodeQueueId |= ID;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000662 }
663
664 void remove(iterator I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000665 (*I)->NodeQueueId &= ~ID;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000666 *I = Queue.back();
667 Queue.pop_back();
668 }
669};
670
Andrew Trick17d35e52012-03-14 04:00:41 +0000671/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
672/// the schedule.
673class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000674
675 /// Store the state used by ConvergingScheduler heuristics, required for the
676 /// lifetime of one invocation of pickNode().
677 struct SchedCandidate {
678 // The best SUnit candidate.
679 SUnit *SU;
680
681 // Register pressure values for the best candidate.
682 RegPressureDelta RPDelta;
683
684 SchedCandidate(): SU(NULL) {}
685 };
686
Andrew Trick17d35e52012-03-14 04:00:41 +0000687 ScheduleDAGMI *DAG;
Andrew Trick7196a8f2012-05-10 21:06:16 +0000688 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +0000689
Andrew Trickd38f87e2012-05-10 21:06:12 +0000690 ReadyQ TopQueue;
691 ReadyQ BotQueue;
Andrew Trick17d35e52012-03-14 04:00:41 +0000692
693public:
Andrew Trick7196a8f2012-05-10 21:06:16 +0000694 /// SUnit::NodeQueueId = 0 (none), = 1 (top), = 2 (bottom), = 3 (both)
695 enum {
696 TopQID = 1,
697 BotQID = 2
698 };
699
700 ConvergingScheduler(): DAG(0), TRI(0), TopQueue(TopQID), BotQueue(BotQID) {}
701
702 static const char *getQName(unsigned ID) {
703 switch(ID) {
704 default: return "NoQ";
705 case TopQID: return "TopQ";
706 case BotQID: return "BotQ";
707 };
708 }
Andrew Trickd38f87e2012-05-10 21:06:12 +0000709
Andrew Trick17d35e52012-03-14 04:00:41 +0000710 virtual void initialize(ScheduleDAGMI *dag) {
711 DAG = dag;
Andrew Trick7196a8f2012-05-10 21:06:16 +0000712 TRI = DAG->TRI;
Andrew Trick17d35e52012-03-14 04:00:41 +0000713
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000714 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000715 "-misched-topdown incompatible with -misched-bottomup");
716 }
717
Andrew Trick7196a8f2012-05-10 21:06:16 +0000718 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +0000719
720 virtual void releaseTopNode(SUnit *SU) {
Andrew Trick16716c72012-05-10 21:06:14 +0000721 if (!SU->isScheduled)
722 TopQueue.push(SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000723 }
724 virtual void releaseBottomNode(SUnit *SU) {
Andrew Trick16716c72012-05-10 21:06:14 +0000725 if (!SU->isScheduled)
726 BotQueue.push(SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000727 }
Andrew Trick7196a8f2012-05-10 21:06:16 +0000728protected:
Andrew Trick28ebc892012-05-10 21:06:19 +0000729#ifndef NDEBUG
730 void traceCandidate(const char *Label, unsigned QID, SUnit *SU,
731 int RPDiff, unsigned PSetID);
732#endif
Andrew Trick7196a8f2012-05-10 21:06:16 +0000733 bool pickNodeFromQueue(ReadyQ &Q, const RegPressureTracker &RPTracker,
734 SchedCandidate &Candidate);
Andrew Trick42b7a712012-01-17 06:55:03 +0000735};
736} // namespace
737
Andrew Trick28ebc892012-05-10 21:06:19 +0000738#ifndef NDEBUG
739void ConvergingScheduler::
740traceCandidate(const char *Label, unsigned QID, SUnit *SU,
741 int RPDiff, unsigned PSetID) {
742 dbgs() << Label << getQName(QID) << " ";
743 if (RPDiff)
744 dbgs() << TRI->getRegPressureSetName(PSetID) << ":" << RPDiff << " ";
745 else
746 dbgs() << " ";
747 SU->dump(DAG);
748}
749#endif
750
Andrew Trick7196a8f2012-05-10 21:06:16 +0000751/// Pick the best candidate from the top queue.
752///
753/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
754/// DAG building. To adjust for the current scheduling location we need to
755/// maintain the number of vreg uses remaining to be top-scheduled.
756bool ConvergingScheduler::pickNodeFromQueue(ReadyQ &Q,
757 const RegPressureTracker &RPTracker,
758 SchedCandidate &Candidate) {
759 // getMaxPressureDelta temporarily modifies the tracker.
760 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
761
762 // BestSU remains NULL if no top candidates beat the best existing candidate.
763 bool FoundCandidate = false;
764 for (ReadyQ::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
765
766 RegPressureDelta RPDelta;
767 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta);
768
769 // Avoid exceeding the target's limit.
770 if (!Candidate.SU || RPDelta.ExcessUnits < Candidate.RPDelta.ExcessUnits) {
Andrew Trick28ebc892012-05-10 21:06:19 +0000771 DEBUG(traceCandidate(Candidate.SU ? "PCAND" : "ACAND", Q.ID, *I,
772 RPDelta.ExcessUnits, RPDelta.ExcessSetID));
Andrew Trick7196a8f2012-05-10 21:06:16 +0000773 Candidate.SU = *I;
774 Candidate.RPDelta = RPDelta;
775 FoundCandidate = true;
776 continue;
777 }
778 if (RPDelta.ExcessUnits > Candidate.RPDelta.ExcessUnits)
779 continue;
780
781 // Avoid increasing the max pressure.
782 if (RPDelta.MaxUnitIncrease < Candidate.RPDelta.MaxUnitIncrease) {
Andrew Trick28ebc892012-05-10 21:06:19 +0000783 DEBUG(traceCandidate("MCAND", Q.ID, *I,
784 RPDelta.ExcessUnits, RPDelta.ExcessSetID));
Andrew Trick7196a8f2012-05-10 21:06:16 +0000785 Candidate.SU = *I;
786 Candidate.RPDelta = RPDelta;
787 FoundCandidate = true;
Andrew Trick7196a8f2012-05-10 21:06:16 +0000788 continue;
789 }
790 if (RPDelta.MaxUnitIncrease > Candidate.RPDelta.MaxUnitIncrease)
791 continue;
792
793 // Fall through to original instruction order.
794 // Only consider node order if BestSU was chosen from this Q.
795 if (!FoundCandidate)
796 continue;
797
798 if ((Q.ID == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
799 || (Q.ID == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
Andrew Trick28ebc892012-05-10 21:06:19 +0000800 DEBUG(traceCandidate("NCAND", Q.ID, *I, 0, 0));
Andrew Trick7196a8f2012-05-10 21:06:16 +0000801 Candidate.SU = *I;
802 Candidate.RPDelta = RPDelta;
803 FoundCandidate = true;
804 }
805 }
806 return FoundCandidate;
807}
808
809/// Pick the best node from either the top or bottom queue to balance the
810/// schedule.
811SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
812 if (DAG->top() == DAG->bottom()) {
813 assert(TopQueue.empty() && BotQueue.empty() && "ReadyQ garbage");
814 return NULL;
815 }
816 // As an initial placeholder heuristic, schedule in the direction that has
817 // the fewest choices.
818 SUnit *SU;
819 if (ForceTopDown) {
820 SU = DAG->getSUnit(DAG->top());
821 IsTopNode = true;
822 }
823 else if (ForceBottomUp) {
824 SU = DAG->getSUnit(priorNonDebug(DAG->bottom(), DAG->top()));
825 IsTopNode = false;
826 }
827 else {
828 SchedCandidate Candidate;
829 // Prefer picking from the bottom.
830 pickNodeFromQueue(BotQueue, DAG->getBotRPTracker(), Candidate);
831 IsTopNode =
832 pickNodeFromQueue(TopQueue, DAG->getTopRPTracker(), Candidate);
833 SU = Candidate.SU;
834 }
835 if (SU->isTopReady()) {
836 assert(!TopQueue.empty() && "bad ready count");
837 TopQueue.remove(TopQueue.find(SU));
838 }
839 if (SU->isBottomReady()) {
840 assert(!BotQueue.empty() && "bad ready count");
841 BotQueue.remove(BotQueue.find(SU));
842 }
843 return SU;
844}
845
Andrew Trick17d35e52012-03-14 04:00:41 +0000846/// Create the standard converging machine scheduler. This will be used as the
847/// default scheduler if the target does not set a default.
848static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000849 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000850 "-misched-topdown incompatible with -misched-bottomup");
851 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +0000852}
853static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000854ConvergingSchedRegistry("converge", "Standard converging scheduler.",
855 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +0000856
857//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +0000858// Machine Instruction Shuffler for Correctness Testing
859//===----------------------------------------------------------------------===//
860
Andrew Trick96f678f2012-01-13 06:30:30 +0000861#ifndef NDEBUG
862namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000863/// Apply a less-than relation on the node order, which corresponds to the
864/// instruction order prior to scheduling. IsReverse implements greater-than.
865template<bool IsReverse>
866struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000867 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +0000868 if (IsReverse)
869 return A->NodeNum > B->NodeNum;
870 else
871 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000872 }
873};
874
Andrew Trick96f678f2012-01-13 06:30:30 +0000875/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +0000876class InstructionShuffler : public MachineSchedStrategy {
877 bool IsAlternating;
878 bool IsTopDown;
879
880 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
881 // gives nodes with a higher number higher priority causing the latest
882 // instructions to be scheduled first.
883 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
884 TopQ;
885 // When scheduling bottom-up, use greater-than as the queue priority.
886 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
887 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +0000888public:
Andrew Trick17d35e52012-03-14 04:00:41 +0000889 InstructionShuffler(bool alternate, bool topdown)
890 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +0000891
Andrew Trick17d35e52012-03-14 04:00:41 +0000892 virtual void initialize(ScheduleDAGMI *) {
893 TopQ.clear();
894 BottomQ.clear();
895 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000896
Andrew Trick17d35e52012-03-14 04:00:41 +0000897 /// Implement MachineSchedStrategy interface.
898 /// -----------------------------------------
899
900 virtual SUnit *pickNode(bool &IsTopNode) {
901 SUnit *SU;
902 if (IsTopDown) {
903 do {
904 if (TopQ.empty()) return NULL;
905 SU = TopQ.top();
906 TopQ.pop();
907 } while (SU->isScheduled);
908 IsTopNode = true;
909 }
910 else {
911 do {
912 if (BottomQ.empty()) return NULL;
913 SU = BottomQ.top();
914 BottomQ.pop();
915 } while (SU->isScheduled);
916 IsTopNode = false;
917 }
918 if (IsAlternating)
919 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000920 return SU;
921 }
922
Andrew Trick17d35e52012-03-14 04:00:41 +0000923 virtual void releaseTopNode(SUnit *SU) {
924 TopQ.push(SU);
925 }
926 virtual void releaseBottomNode(SUnit *SU) {
927 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +0000928 }
929};
930} // namespace
931
Andrew Trickc174eaf2012-03-08 01:41:12 +0000932static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000933 bool Alternate = !ForceTopDown && !ForceBottomUp;
934 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000935 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000936 "-misched-topdown incompatible with -misched-bottomup");
937 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +0000938}
Andrew Trick17d35e52012-03-14 04:00:41 +0000939static MachineSchedRegistry ShufflerRegistry(
940 "shuffle", "Shuffle machine instructions alternating directions",
941 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +0000942#endif // !NDEBUG