blob: 100137b38cf0385e0d303bab007d2c226d3c688b [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 Trick006e1ab2012-04-24 17:56:43 +000017#include "RegisterPressure.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trickc174eaf2012-03-08 01:41:12 +000019#include "llvm/CodeGen/MachineScheduler.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000020#include "llvm/CodeGen/Passes.h"
Andrew Tricked395c82012-03-07 23:01:06 +000021#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Andrew Tricke9ef4ed2012-01-14 02:17:09 +000023#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/ADT/OwningPtr.h"
Andrew Trick17d35e52012-03-14 04:00:41 +000029#include "llvm/ADT/PriorityQueue.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000030
Andrew Trickc6cf11b2012-01-17 06:55:07 +000031#include <queue>
32
Andrew Trick96f678f2012-01-13 06:30:30 +000033using namespace llvm;
34
Andrew Trick17d35e52012-03-14 04:00:41 +000035static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
39
Andrew Trick0df7f882012-03-07 00:18:25 +000040#ifndef NDEBUG
41static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
42 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000043
44static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
45 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000046#else
47static bool ViewMISchedDAGs = false;
48#endif // NDEBUG
49
Andrew Trick5edf2f02012-01-14 02:17:06 +000050//===----------------------------------------------------------------------===//
51// Machine Instruction Scheduling Pass and Registry
52//===----------------------------------------------------------------------===//
53
Andrew Trick96f678f2012-01-13 06:30:30 +000054namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000055/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000056class MachineScheduler : public MachineSchedContext,
57 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000058public:
Andrew Trick42b7a712012-01-17 06:55:03 +000059 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000060
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
62
63 virtual void releaseMemory() {}
64
65 virtual bool runOnMachineFunction(MachineFunction&);
66
67 virtual void print(raw_ostream &O, const Module* = 0) const;
68
69 static char ID; // Class identification, replacement for typeinfo
70};
71} // namespace
72
Andrew Trick42b7a712012-01-17 06:55:03 +000073char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000074
Andrew Trick42b7a712012-01-17 06:55:03 +000075char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000076
Andrew Trick42b7a712012-01-17 06:55:03 +000077INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000078 "Machine Instruction Scheduler", false, false)
79INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
80INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
81INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +000082INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000083 "Machine Instruction Scheduler", false, false)
84
Andrew Trick42b7a712012-01-17 06:55:03 +000085MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +000086: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +000087 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +000088}
89
Andrew Trick42b7a712012-01-17 06:55:03 +000090void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +000091 AU.setPreservesCFG();
92 AU.addRequiredID(MachineDominatorsID);
93 AU.addRequired<MachineLoopInfo>();
94 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +000095 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +000096 AU.addRequired<SlotIndexes>();
97 AU.addPreserved<SlotIndexes>();
98 AU.addRequired<LiveIntervals>();
99 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000100 MachineFunctionPass::getAnalysisUsage(AU);
101}
102
Andrew Trick96f678f2012-01-13 06:30:30 +0000103MachinePassRegistry MachineSchedRegistry::Registry;
104
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000105/// A dummy default scheduler factory indicates whether the scheduler
106/// is overridden on the command line.
107static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
108 return 0;
109}
Andrew Trick96f678f2012-01-13 06:30:30 +0000110
111/// MachineSchedOpt allows command line selection of the scheduler.
112static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
113 RegisterPassParser<MachineSchedRegistry> >
114MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000115 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000116 cl::desc("Machine instruction scheduler to use"));
117
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000118static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000119DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000120 useDefaultMachineSched);
121
Andrew Trick17d35e52012-03-14 04:00:41 +0000122/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000123/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000124static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000125
Andrew Trickcb058d52012-03-14 04:00:38 +0000126/// Top-level MachineScheduler pass driver.
127///
128/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000129/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
130/// consistent with the DAG builder, which traverses the interior of the
131/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000132///
133/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000134/// simplifying the DAG builder's support for "special" target instructions.
135/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000136/// scheduling boundaries, for example to bundle the boudary instructions
137/// without reordering them. This creates complexity, because the target
138/// scheduler must update the RegionBegin and RegionEnd positions cached by
139/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
140/// design would be to split blocks at scheduling boundaries, but LLVM has a
141/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000142bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick96f678f2012-01-13 06:30:30 +0000143 // Initialize the context of the pass.
144 MF = &mf;
145 MLI = &getAnalysis<MachineLoopInfo>();
146 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000147 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000148 AA = &getAnalysis<AliasAnalysis>();
149
Lang Hames907cc8f2012-01-27 22:36:19 +0000150 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000151 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000152
Andrew Trick006e1ab2012-04-24 17:56:43 +0000153 RegClassInfo.runOnMachineFunction(*MF);
154
Andrew Trick96f678f2012-01-13 06:30:30 +0000155 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000156 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
157 if (Ctor == useDefaultMachineSched) {
158 // Get the default scheduler set by the target.
159 Ctor = MachineSchedRegistry::getDefault();
160 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000161 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000162 MachineSchedRegistry::setDefault(Ctor);
163 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000164 }
165 // Instantiate the selected scheduler.
166 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
167
168 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000169 //
170 // TODO: Visit blocks in global postorder or postorder within the bottom-up
171 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000172 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
173 MBB != MBBEnd; ++MBB) {
174
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000175 Scheduler->startBlock(MBB);
176
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000177 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000178 // region as soon as it is discovered. RegionEnd points the the scheduling
179 // boundary at the bottom of the region. The DAG does not include RegionEnd,
180 // but the region does (i.e. the next RegionEnd is above the previous
181 // RegionBegin). If the current block has no terminator then RegionEnd ==
182 // MBB->end() for the bottom region.
183 //
184 // The Scheduler may insert instructions during either schedule() or
185 // exitRegion(), even for empty regions. So the local iterators 'I' and
186 // 'RegionEnd' are invalid across these calls.
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000187 unsigned RemainingCount = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000188 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000189 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000190
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000191 // Avoid decrementing RegionEnd for blocks with no terminator.
192 if (RegionEnd != MBB->end()
193 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
194 --RegionEnd;
195 // Count the boundary instruction.
196 --RemainingCount;
197 }
198
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000199 // The next region starts above the previous region. Look backward in the
200 // instruction stream until we find the nearest boundary.
201 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick7799eb42012-03-09 03:46:39 +0000202 for(;I != MBB->begin(); --I, --RemainingCount) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000203 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
204 break;
205 }
Andrew Trick47c14452012-03-07 05:21:52 +0000206 // Notify the scheduler of the region, even if we may skip scheduling
207 // it. Perhaps it still needs to be bundled.
208 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
209
210 // Skip empty scheduling regions (0 or 1 schedulable instructions).
211 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000212 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000213 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000214 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000215 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000216 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000217 DEBUG(dbgs() << "MachineScheduling " << MF->getFunction()->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000218 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
219 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
220 else dbgs() << "End";
221 dbgs() << " Remaining: " << RemainingCount << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000222
Andrew Trickd24da972012-03-09 03:46:42 +0000223 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000224 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000225 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000226
227 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000228 Scheduler->exitRegion();
229
230 // Scheduling has invalidated the current iterator 'I'. Ask the
231 // scheduler for the top of it's scheduled region.
232 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000233 }
234 assert(RemainingCount == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000235 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000236 }
Andrew Trick830da402012-04-01 07:24:23 +0000237 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000238 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000239 return true;
240}
241
Andrew Trick42b7a712012-01-17 06:55:03 +0000242void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000243 // unimplemented
244}
245
Andrew Trick5edf2f02012-01-14 02:17:06 +0000246//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000247// MachineSchedStrategy - Interface to a machine scheduling algorithm.
248//===----------------------------------------------------------------------===//
Andrew Trickc174eaf2012-03-08 01:41:12 +0000249
250namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000251class ScheduleDAGMI;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000252
Andrew Trick17d35e52012-03-14 04:00:41 +0000253/// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
254/// scheduling algorithm.
255///
256/// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
257/// in ScheduleDAGInstrs.h
258class MachineSchedStrategy {
259public:
260 virtual ~MachineSchedStrategy() {}
261
262 /// Initialize the strategy after building the DAG for a new region.
263 virtual void initialize(ScheduleDAGMI *DAG) = 0;
264
265 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
266 /// schedule the node at the top of the unscheduled region. Otherwise it will
267 /// be scheduled at the bottom.
268 virtual SUnit *pickNode(bool &IsTopNode) = 0;
269
270 /// When all predecessor dependencies have been resolved, free this node for
271 /// top-down scheduling.
272 virtual void releaseTopNode(SUnit *SU) = 0;
273 /// When all successor dependencies have been resolved, free this node for
274 /// bottom-up scheduling.
275 virtual void releaseBottomNode(SUnit *SU) = 0;
276};
277} // namespace
278
279//===----------------------------------------------------------------------===//
280// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
281// preservation.
282//===----------------------------------------------------------------------===//
283
284namespace {
285/// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
286/// machine instructions while updating LiveIntervals.
287class ScheduleDAGMI : public ScheduleDAGInstrs {
288 AliasAnalysis *AA;
Andrew Trick006e1ab2012-04-24 17:56:43 +0000289 RegisterClassInfo *RegClassInfo;
Andrew Trick17d35e52012-03-14 04:00:41 +0000290 MachineSchedStrategy *SchedImpl;
291
Andrew Trick006e1ab2012-04-24 17:56:43 +0000292 // Register pressure in this region computed by buildSchedGraph.
293 IntervalPressure RegPressure;
294 RegPressureTracker RPTracker;
295
Andrew Trick17d35e52012-03-14 04:00:41 +0000296 /// The top of the unscheduled zone.
297 MachineBasicBlock::iterator CurrentTop;
298
299 /// The bottom of the unscheduled zone.
300 MachineBasicBlock::iterator CurrentBottom;
Lang Hames23f1cbb2012-03-19 18:38:38 +0000301
302 /// The number of instructions scheduled so far. Used to cut off the
303 /// scheduler at the point determined by misched-cutoff.
304 unsigned NumInstrsScheduled;
Andrew Trick17d35e52012-03-14 04:00:41 +0000305public:
306 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
307 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
Andrew Trick006e1ab2012-04-24 17:56:43 +0000308 AA(C->AA), RegClassInfo(&C->RegClassInfo), SchedImpl(S),
309 RPTracker(RegPressure), CurrentTop(), CurrentBottom(),
Lang Hames23f1cbb2012-03-19 18:38:38 +0000310 NumInstrsScheduled(0) {}
Andrew Trick17d35e52012-03-14 04:00:41 +0000311
312 ~ScheduleDAGMI() {
313 delete SchedImpl;
314 }
315
316 MachineBasicBlock::iterator top() const { return CurrentTop; }
317 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
318
Andrew Trick006e1ab2012-04-24 17:56:43 +0000319 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
320 /// region. This covers all instructions in a block, while schedule() may only
321 /// cover a subset.
322 void enterRegion(MachineBasicBlock *bb,
323 MachineBasicBlock::iterator begin,
324 MachineBasicBlock::iterator end,
325 unsigned endcount);
326
327 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
328 /// reorderable instructions.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000329 void schedule();
330
Andrew Trickc174eaf2012-03-08 01:41:12 +0000331protected:
Andrew Trick17d35e52012-03-14 04:00:41 +0000332 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
Andrew Trick0b0d8992012-03-21 04:12:07 +0000333 bool checkSchedLimit();
Andrew Trick17d35e52012-03-14 04:00:41 +0000334
Andrew Trickc174eaf2012-03-08 01:41:12 +0000335 void releaseSucc(SUnit *SU, SDep *SuccEdge);
336 void releaseSuccessors(SUnit *SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000337 void releasePred(SUnit *SU, SDep *PredEdge);
338 void releasePredecessors(SUnit *SU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000339};
340} // namespace
341
342/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
343/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick17d35e52012-03-14 04:00:41 +0000344void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000345 SUnit *SuccSU = SuccEdge->getSUnit();
346
347#ifndef NDEBUG
348 if (SuccSU->NumPredsLeft == 0) {
349 dbgs() << "*** Scheduling failed! ***\n";
350 SuccSU->dump(this);
351 dbgs() << " has been released too many times!\n";
352 llvm_unreachable(0);
353 }
354#endif
355 --SuccSU->NumPredsLeft;
356 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000357 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000358}
359
360/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000361void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000362 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
363 I != E; ++I) {
364 releaseSucc(SU, &*I);
365 }
366}
367
Andrew Trick17d35e52012-03-14 04:00:41 +0000368/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
369/// NumSuccsLeft reaches zero, release the predecessor node.
370void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
371 SUnit *PredSU = PredEdge->getSUnit();
372
373#ifndef NDEBUG
374 if (PredSU->NumSuccsLeft == 0) {
375 dbgs() << "*** Scheduling failed! ***\n";
376 PredSU->dump(this);
377 dbgs() << " has been released too many times!\n";
378 llvm_unreachable(0);
379 }
380#endif
381 --PredSU->NumSuccsLeft;
382 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
383 SchedImpl->releaseBottomNode(PredSU);
384}
385
386/// releasePredecessors - Call releasePred on each of SU's predecessors.
387void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
388 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
389 I != E; ++I) {
390 releasePred(SU, &*I);
391 }
392}
393
394void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
395 MachineBasicBlock::iterator InsertPos) {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000396 // Fix RegionBegin if the first instruction moves down.
397 if (&*RegionBegin == MI)
398 RegionBegin = llvm::next(RegionBegin);
Andrew Trick17d35e52012-03-14 04:00:41 +0000399 BB->splice(InsertPos, BB, MI);
400 LIS->handleMove(MI);
Andrew Trick1ce062f2012-03-21 04:12:10 +0000401 // Fix RegionBegin if another instruction moves above the first instruction.
Andrew Trick17d35e52012-03-14 04:00:41 +0000402 if (RegionBegin == InsertPos)
403 RegionBegin = MI;
404}
405
Andrew Trick0b0d8992012-03-21 04:12:07 +0000406bool ScheduleDAGMI::checkSchedLimit() {
407#ifndef NDEBUG
408 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
409 CurrentTop = CurrentBottom;
410 return false;
411 }
412 ++NumInstrsScheduled;
413#endif
414 return true;
415}
416
Andrew Trick006e1ab2012-04-24 17:56:43 +0000417/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
418/// crossing a scheduling boundary. [begin, end) includes all instructions in
419/// the region, including the boundary itself and single-instruction regions
420/// that don't get scheduled.
421void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
422 MachineBasicBlock::iterator begin,
423 MachineBasicBlock::iterator end,
424 unsigned endcount)
425{
426 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
427 // Setup the register pressure tracker to begin tracking at the end of this
428 // region.
429 RPTracker.init(&MF, RegClassInfo, LIS, BB, end);
430}
431
Andrew Trick17d35e52012-03-14 04:00:41 +0000432/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000433/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
434/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick17d35e52012-03-14 04:00:41 +0000435void ScheduleDAGMI::schedule() {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000436 while(RPTracker.getPos() != RegionEnd) {
437 bool Moved = RPTracker.recede();
438 assert(Moved && "Regpressure tracker cannot find RegionEnd"); (void)Moved;
439 }
440
441 // Build the DAG.
442 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000443
444 DEBUG(dbgs() << "********** MI Scheduling **********\n");
445 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
446 SUnits[su].dumpAll(this));
447
448 if (ViewMISchedDAGs) viewGraph();
449
Andrew Trick17d35e52012-03-14 04:00:41 +0000450 SchedImpl->initialize(this);
451
452 // Release edges from the special Entry node or to the special Exit node.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000453 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000454 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000455
456 // Release all DAG roots for scheduling.
457 for (std::vector<SUnit>::iterator I = SUnits.begin(), E = SUnits.end();
458 I != E; ++I) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000459 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000460 if (I->Preds.empty())
Andrew Trick17d35e52012-03-14 04:00:41 +0000461 SchedImpl->releaseTopNode(&(*I));
462 // A SUnit is ready to bottom schedule if it has no successors.
463 if (I->Succs.empty())
464 SchedImpl->releaseBottomNode(&(*I));
Andrew Trickc174eaf2012-03-08 01:41:12 +0000465 }
466
Andrew Trick17d35e52012-03-14 04:00:41 +0000467 CurrentTop = RegionBegin;
468 CurrentBottom = RegionEnd;
469 bool IsTopNode = false;
470 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
471 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
472 << " Scheduling Instruction:\n"; SU->dump(this));
Andrew Trick0b0d8992012-03-21 04:12:07 +0000473 if (!checkSchedLimit())
474 break;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000475
476 // Move the instruction to its new location in the instruction stream.
477 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000478
Andrew Trick17d35e52012-03-14 04:00:41 +0000479 if (IsTopNode) {
480 assert(SU->isTopReady() && "node still has unscheduled dependencies");
481 if (&*CurrentTop == MI)
482 ++CurrentTop;
483 else
484 moveInstruction(MI, CurrentTop);
485 // Release dependent instructions for scheduling.
486 releaseSuccessors(SU);
487 }
488 else {
489 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
490 if (&*llvm::prior(CurrentBottom) == MI)
491 --CurrentBottom;
492 else {
Andrew Trick1ce062f2012-03-21 04:12:10 +0000493 if (&*CurrentTop == MI)
494 CurrentTop = llvm::next(CurrentTop);
Andrew Trick17d35e52012-03-14 04:00:41 +0000495 moveInstruction(MI, CurrentBottom);
496 CurrentBottom = MI;
497 }
498 // Release dependent instructions for scheduling.
499 releasePredecessors(SU);
500 }
501 SU->isScheduled = true;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000502 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000503 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
Andrew Trickc174eaf2012-03-08 01:41:12 +0000504}
505
506//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000507// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000508//===----------------------------------------------------------------------===//
509
510namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000511/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
512/// the schedule.
513class ConvergingScheduler : public MachineSchedStrategy {
514 ScheduleDAGMI *DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +0000515
Andrew Trick17d35e52012-03-14 04:00:41 +0000516 unsigned NumTopReady;
517 unsigned NumBottomReady;
518
519public:
520 virtual void initialize(ScheduleDAGMI *dag) {
521 DAG = dag;
522
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000523 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000524 "-misched-topdown incompatible with -misched-bottomup");
525 }
526
527 virtual SUnit *pickNode(bool &IsTopNode) {
528 if (DAG->top() == DAG->bottom())
529 return NULL;
530
531 // As an initial placeholder heuristic, schedule in the direction that has
532 // the fewest choices.
533 SUnit *SU;
534 if (ForceTopDown || (!ForceBottomUp && NumTopReady <= NumBottomReady)) {
535 SU = DAG->getSUnit(DAG->top());
536 IsTopNode = true;
537 }
538 else {
539 SU = DAG->getSUnit(llvm::prior(DAG->bottom()));
540 IsTopNode = false;
541 }
542 if (SU->isTopReady()) {
543 assert(NumTopReady > 0 && "bad ready count");
544 --NumTopReady;
545 }
546 if (SU->isBottomReady()) {
547 assert(NumBottomReady > 0 && "bad ready count");
548 --NumBottomReady;
549 }
550 return SU;
551 }
552
553 virtual void releaseTopNode(SUnit *SU) {
554 ++NumTopReady;
555 }
556 virtual void releaseBottomNode(SUnit *SU) {
557 ++NumBottomReady;
558 }
Andrew Trick42b7a712012-01-17 06:55:03 +0000559};
560} // namespace
561
Andrew Trick17d35e52012-03-14 04:00:41 +0000562/// Create the standard converging machine scheduler. This will be used as the
563/// default scheduler if the target does not set a default.
564static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000565 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000566 "-misched-topdown incompatible with -misched-bottomup");
567 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +0000568}
569static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000570ConvergingSchedRegistry("converge", "Standard converging scheduler.",
571 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +0000572
573//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +0000574// Machine Instruction Shuffler for Correctness Testing
575//===----------------------------------------------------------------------===//
576
Andrew Trick96f678f2012-01-13 06:30:30 +0000577#ifndef NDEBUG
578namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000579/// Apply a less-than relation on the node order, which corresponds to the
580/// instruction order prior to scheduling. IsReverse implements greater-than.
581template<bool IsReverse>
582struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000583 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +0000584 if (IsReverse)
585 return A->NodeNum > B->NodeNum;
586 else
587 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000588 }
589};
590
Andrew Trick96f678f2012-01-13 06:30:30 +0000591/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +0000592class InstructionShuffler : public MachineSchedStrategy {
593 bool IsAlternating;
594 bool IsTopDown;
595
596 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
597 // gives nodes with a higher number higher priority causing the latest
598 // instructions to be scheduled first.
599 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
600 TopQ;
601 // When scheduling bottom-up, use greater-than as the queue priority.
602 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
603 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +0000604public:
Andrew Trick17d35e52012-03-14 04:00:41 +0000605 InstructionShuffler(bool alternate, bool topdown)
606 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +0000607
Andrew Trick17d35e52012-03-14 04:00:41 +0000608 virtual void initialize(ScheduleDAGMI *) {
609 TopQ.clear();
610 BottomQ.clear();
611 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000612
Andrew Trick17d35e52012-03-14 04:00:41 +0000613 /// Implement MachineSchedStrategy interface.
614 /// -----------------------------------------
615
616 virtual SUnit *pickNode(bool &IsTopNode) {
617 SUnit *SU;
618 if (IsTopDown) {
619 do {
620 if (TopQ.empty()) return NULL;
621 SU = TopQ.top();
622 TopQ.pop();
623 } while (SU->isScheduled);
624 IsTopNode = true;
625 }
626 else {
627 do {
628 if (BottomQ.empty()) return NULL;
629 SU = BottomQ.top();
630 BottomQ.pop();
631 } while (SU->isScheduled);
632 IsTopNode = false;
633 }
634 if (IsAlternating)
635 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000636 return SU;
637 }
638
Andrew Trick17d35e52012-03-14 04:00:41 +0000639 virtual void releaseTopNode(SUnit *SU) {
640 TopQ.push(SU);
641 }
642 virtual void releaseBottomNode(SUnit *SU) {
643 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +0000644 }
645};
646} // namespace
647
Andrew Trickc174eaf2012-03-08 01:41:12 +0000648static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000649 bool Alternate = !ForceTopDown && !ForceBottomUp;
650 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +0000651 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +0000652 "-misched-topdown incompatible with -misched-bottomup");
653 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +0000654}
Andrew Trick17d35e52012-03-14 04:00:41 +0000655static MachineSchedRegistry ShufflerRegistry(
656 "shuffle", "Shuffle machine instructions alternating directions",
657 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +0000658#endif // !NDEBUG