blob: 18e61e0a78e3491121c6179840114d2d7105e6d4 [file] [log] [blame]
Andrew Trick5429a6b2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Trick96f678f2012-01-13 06:30:30 +00002//
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 Trick15252602012-06-06 20:29:31 +000020#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trickafc26572012-06-06 19:47:35 +000021#include "llvm/CodeGen/RegisterPressure.h"
Andrew Tricked395c82012-03-07 23:01:06 +000022#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000023#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Tricke9ef4ed2012-01-14 02:17:09 +000024#include "llvm/Target/TargetInstrInfo.h"
Andrew Trickb7e02892012-06-05 21:11:27 +000025#include "llvm/MC/MCInstrItineraries.h"
26#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/ADT/OwningPtr.h"
Andrew Trick17d35e52012-03-14 04:00:41 +000032#include "llvm/ADT/PriorityQueue.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000033
Andrew Trickc6cf11b2012-01-17 06:55:07 +000034#include <queue>
35
Andrew Trick96f678f2012-01-13 06:30:30 +000036using namespace llvm;
37
Andrew Trick17d35e52012-03-14 04:00:41 +000038static cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
39 cl::desc("Force top-down list scheduling"));
40static cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
41 cl::desc("Force bottom-up list scheduling"));
42
Andrew Trick0df7f882012-03-07 00:18:25 +000043#ifndef NDEBUG
44static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
45 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000046
47static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
48 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000049#else
50static bool ViewMISchedDAGs = false;
51#endif // NDEBUG
52
Andrew Trick5edf2f02012-01-14 02:17:06 +000053//===----------------------------------------------------------------------===//
54// Machine Instruction Scheduling Pass and Registry
55//===----------------------------------------------------------------------===//
56
Andrew Trick86b7e2a2012-04-24 20:36:19 +000057MachineSchedContext::MachineSchedContext():
58 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
59 RegClassInfo = new RegisterClassInfo();
60}
61
62MachineSchedContext::~MachineSchedContext() {
63 delete RegClassInfo;
64}
65
Andrew Trick96f678f2012-01-13 06:30:30 +000066namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000067/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000068class MachineScheduler : public MachineSchedContext,
69 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000070public:
Andrew Trick42b7a712012-01-17 06:55:03 +000071 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000072
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
74
75 virtual void releaseMemory() {}
76
77 virtual bool runOnMachineFunction(MachineFunction&);
78
79 virtual void print(raw_ostream &O, const Module* = 0) const;
80
81 static char ID; // Class identification, replacement for typeinfo
82};
83} // namespace
84
Andrew Trick42b7a712012-01-17 06:55:03 +000085char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000086
Andrew Trick42b7a712012-01-17 06:55:03 +000087char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000088
Andrew Trick42b7a712012-01-17 06:55:03 +000089INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000090 "Machine Instruction Scheduler", false, false)
91INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
92INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
93INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +000094INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000095 "Machine Instruction Scheduler", false, false)
96
Andrew Trick42b7a712012-01-17 06:55:03 +000097MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +000098: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +000099 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000100}
101
Andrew Trick42b7a712012-01-17 06:55:03 +0000102void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000103 AU.setPreservesCFG();
104 AU.addRequiredID(MachineDominatorsID);
105 AU.addRequired<MachineLoopInfo>();
106 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000107 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000108 AU.addRequired<SlotIndexes>();
109 AU.addPreserved<SlotIndexes>();
110 AU.addRequired<LiveIntervals>();
111 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000112 MachineFunctionPass::getAnalysisUsage(AU);
113}
114
Andrew Trick96f678f2012-01-13 06:30:30 +0000115MachinePassRegistry MachineSchedRegistry::Registry;
116
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000117/// A dummy default scheduler factory indicates whether the scheduler
118/// is overridden on the command line.
119static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
120 return 0;
121}
Andrew Trick96f678f2012-01-13 06:30:30 +0000122
123/// MachineSchedOpt allows command line selection of the scheduler.
124static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
125 RegisterPassParser<MachineSchedRegistry> >
126MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000127 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000128 cl::desc("Machine instruction scheduler to use"));
129
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000130static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000131DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000132 useDefaultMachineSched);
133
Andrew Trick17d35e52012-03-14 04:00:41 +0000134/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000135/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000136static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000137
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000138
139/// Decrement this iterator until reaching the top or a non-debug instr.
140static MachineBasicBlock::iterator
141priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
142 assert(I != Beg && "reached the top of the region, cannot decrement");
143 while (--I != Beg) {
144 if (!I->isDebugValue())
145 break;
146 }
147 return I;
148}
149
150/// If this iterator is a debug value, increment until reaching the End or a
151/// non-debug instruction.
152static MachineBasicBlock::iterator
153nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000154 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000155 if (!I->isDebugValue())
156 break;
157 }
158 return I;
159}
160
Andrew Trickcb058d52012-03-14 04:00:38 +0000161/// Top-level MachineScheduler pass driver.
162///
163/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000164/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
165/// consistent with the DAG builder, which traverses the interior of the
166/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000167///
168/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000169/// simplifying the DAG builder's support for "special" target instructions.
170/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000171/// scheduling boundaries, for example to bundle the boudary instructions
172/// without reordering them. This creates complexity, because the target
173/// scheduler must update the RegionBegin and RegionEnd positions cached by
174/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
175/// design would be to split blocks at scheduling boundaries, but LLVM has a
176/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000177bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000178 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
179
Andrew Trick96f678f2012-01-13 06:30:30 +0000180 // Initialize the context of the pass.
181 MF = &mf;
182 MLI = &getAnalysis<MachineLoopInfo>();
183 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000184 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000185 AA = &getAnalysis<AliasAnalysis>();
186
Lang Hames907cc8f2012-01-27 22:36:19 +0000187 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000188 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000189
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000190 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000191
Andrew Trick96f678f2012-01-13 06:30:30 +0000192 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000193 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
194 if (Ctor == useDefaultMachineSched) {
195 // Get the default scheduler set by the target.
196 Ctor = MachineSchedRegistry::getDefault();
197 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000198 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000199 MachineSchedRegistry::setDefault(Ctor);
200 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000201 }
202 // Instantiate the selected scheduler.
203 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
204
205 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000206 //
207 // TODO: Visit blocks in global postorder or postorder within the bottom-up
208 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000209 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
210 MBB != MBBEnd; ++MBB) {
211
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000212 Scheduler->startBlock(MBB);
213
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000214 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000215 // region as soon as it is discovered. RegionEnd points the the scheduling
216 // boundary at the bottom of the region. The DAG does not include RegionEnd,
217 // but the region does (i.e. the next RegionEnd is above the previous
218 // RegionBegin). If the current block has no terminator then RegionEnd ==
219 // MBB->end() for the bottom region.
220 //
221 // The Scheduler may insert instructions during either schedule() or
222 // exitRegion(), even for empty regions. So the local iterators 'I' and
223 // 'RegionEnd' are invalid across these calls.
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000224 unsigned RemainingCount = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000225 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000226 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000227
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000228 // Avoid decrementing RegionEnd for blocks with no terminator.
229 if (RegionEnd != MBB->end()
230 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
231 --RegionEnd;
232 // Count the boundary instruction.
233 --RemainingCount;
234 }
235
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000236 // The next region starts above the previous region. Look backward in the
237 // instruction stream until we find the nearest boundary.
238 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick7799eb42012-03-09 03:46:39 +0000239 for(;I != MBB->begin(); --I, --RemainingCount) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000240 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
241 break;
242 }
Andrew Trick47c14452012-03-07 05:21:52 +0000243 // Notify the scheduler of the region, even if we may skip scheduling
244 // it. Perhaps it still needs to be bundled.
245 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingCount);
246
247 // Skip empty scheduling regions (0 or 1 schedulable instructions).
248 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000249 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000250 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000251 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000252 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000253 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000254 DEBUG(dbgs() << "********** MI Scheduling **********\n");
255 DEBUG(dbgs() << MF->getFunction()->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000256 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
257 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
258 else dbgs() << "End";
259 dbgs() << " Remaining: " << RemainingCount << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000260
Andrew Trickd24da972012-03-09 03:46:42 +0000261 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000262 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000263 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000264
265 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000266 Scheduler->exitRegion();
267
268 // Scheduling has invalidated the current iterator 'I'. Ask the
269 // scheduler for the top of it's scheduled region.
270 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000271 }
272 assert(RemainingCount == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000273 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000274 }
Andrew Trick830da402012-04-01 07:24:23 +0000275 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000276 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000277 return true;
278}
279
Andrew Trick42b7a712012-01-17 06:55:03 +0000280void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000281 // unimplemented
282}
283
Andrew Trick5edf2f02012-01-14 02:17:06 +0000284//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000285// MachineSchedStrategy - Interface to a machine scheduling algorithm.
286//===----------------------------------------------------------------------===//
Andrew Trickc174eaf2012-03-08 01:41:12 +0000287
288namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000289class ScheduleDAGMI;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000290
Andrew Trick17d35e52012-03-14 04:00:41 +0000291/// MachineSchedStrategy - Interface used by ScheduleDAGMI to drive the selected
292/// scheduling algorithm.
293///
294/// If this works well and targets wish to reuse ScheduleDAGMI, we may expose it
295/// in ScheduleDAGInstrs.h
296class MachineSchedStrategy {
297public:
298 virtual ~MachineSchedStrategy() {}
299
300 /// Initialize the strategy after building the DAG for a new region.
301 virtual void initialize(ScheduleDAGMI *DAG) = 0;
302
303 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
304 /// schedule the node at the top of the unscheduled region. Otherwise it will
305 /// be scheduled at the bottom.
306 virtual SUnit *pickNode(bool &IsTopNode) = 0;
307
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000308 /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled a node.
309 virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
310
Andrew Trick17d35e52012-03-14 04:00:41 +0000311 /// When all predecessor dependencies have been resolved, free this node for
312 /// top-down scheduling.
313 virtual void releaseTopNode(SUnit *SU) = 0;
314 /// When all successor dependencies have been resolved, free this node for
315 /// bottom-up scheduling.
316 virtual void releaseBottomNode(SUnit *SU) = 0;
317};
318} // namespace
319
320//===----------------------------------------------------------------------===//
321// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
322// preservation.
323//===----------------------------------------------------------------------===//
324
325namespace {
326/// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
327/// machine instructions while updating LiveIntervals.
328class ScheduleDAGMI : public ScheduleDAGInstrs {
329 AliasAnalysis *AA;
Andrew Trick006e1ab2012-04-24 17:56:43 +0000330 RegisterClassInfo *RegClassInfo;
Andrew Trick17d35e52012-03-14 04:00:41 +0000331 MachineSchedStrategy *SchedImpl;
332
Andrew Trick7f8ab782012-05-10 21:06:10 +0000333 MachineBasicBlock::iterator LiveRegionEnd;
334
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000335 /// Register pressure in this region computed by buildSchedGraph.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000336 IntervalPressure RegPressure;
337 RegPressureTracker RPTracker;
338
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000339 /// List of pressure sets that exceed the target's pressure limit before
340 /// scheduling, listed in increasing set ID order. Each pressure set is paired
341 /// with its max pressure in the currently scheduled regions.
342 std::vector<PressureElement> RegionCriticalPSets;
343
Andrew Trick17d35e52012-03-14 04:00:41 +0000344 /// The top of the unscheduled zone.
345 MachineBasicBlock::iterator CurrentTop;
Andrew Trick7f8ab782012-05-10 21:06:10 +0000346 IntervalPressure TopPressure;
347 RegPressureTracker TopRPTracker;
Andrew Trick17d35e52012-03-14 04:00:41 +0000348
349 /// The bottom of the unscheduled zone.
350 MachineBasicBlock::iterator CurrentBottom;
Andrew Trick7f8ab782012-05-10 21:06:10 +0000351 IntervalPressure BotPressure;
352 RegPressureTracker BotRPTracker;
Lang Hames23f1cbb2012-03-19 18:38:38 +0000353
Benjamin Kramera9783662012-06-16 21:48:13 +0000354#ifndef NDEBUG
Lang Hames23f1cbb2012-03-19 18:38:38 +0000355 /// The number of instructions scheduled so far. Used to cut off the
356 /// scheduler at the point determined by misched-cutoff.
357 unsigned NumInstrsScheduled;
Benjamin Kramera9783662012-06-16 21:48:13 +0000358#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000359public:
360 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
361 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000362 AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S),
Andrew Trick7f8ab782012-05-10 21:06:10 +0000363 RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
Benjamin Kramera9783662012-06-16 21:48:13 +0000364 CurrentBottom(), BotRPTracker(BotPressure) {
365#ifndef NDEBUG
366 NumInstrsScheduled = 0;
367#endif
368 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000369
370 ~ScheduleDAGMI() {
371 delete SchedImpl;
372 }
373
374 MachineBasicBlock::iterator top() const { return CurrentTop; }
375 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
376
Andrew Trick006e1ab2012-04-24 17:56:43 +0000377 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
378 /// region. This covers all instructions in a block, while schedule() may only
379 /// cover a subset.
380 void enterRegion(MachineBasicBlock *bb,
381 MachineBasicBlock::iterator begin,
382 MachineBasicBlock::iterator end,
383 unsigned endcount);
384
385 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
386 /// reorderable instructions.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000387 void schedule();
388
Andrew Trick7196a8f2012-05-10 21:06:16 +0000389 /// Get current register pressure for the top scheduled instructions.
390 const IntervalPressure &getTopPressure() const { return TopPressure; }
391 const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
392
393 /// Get current register pressure for the bottom scheduled instructions.
394 const IntervalPressure &getBotPressure() const { return BotPressure; }
395 const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
396
397 /// Get register pressure for the entire scheduling region before scheduling.
398 const IntervalPressure &getRegPressure() const { return RegPressure; }
399
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000400 const std::vector<PressureElement> &getRegionCriticalPSets() const {
401 return RegionCriticalPSets;
402 }
403
Andrew Trickb7e02892012-06-05 21:11:27 +0000404 /// getIssueWidth - Return the max instructions per scheduling group.
Andrew Trickb7e02892012-06-05 21:11:27 +0000405 unsigned getIssueWidth() const {
406 return InstrItins ? InstrItins->Props.IssueWidth : 1;
407 }
408
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000409 /// getNumMicroOps - Return the number of issue slots required for this MI.
410 unsigned getNumMicroOps(MachineInstr *MI) const {
411 int UOps = InstrItins->getNumMicroOps(MI->getDesc().getSchedClass());
412 return (UOps >= 0) ? UOps : TII->getNumMicroOps(InstrItins, MI);
413 }
414
Andrew Trickc174eaf2012-03-08 01:41:12 +0000415protected:
Andrew Trick7f8ab782012-05-10 21:06:10 +0000416 void initRegPressure();
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000417 void updateScheduledPressure(std::vector<unsigned> NewMaxPressure);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000418
Andrew Trick17d35e52012-03-14 04:00:41 +0000419 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
Andrew Trick0b0d8992012-03-21 04:12:07 +0000420 bool checkSchedLimit();
Andrew Trick17d35e52012-03-14 04:00:41 +0000421
Andrew Trick2aa689d2012-05-24 22:11:05 +0000422 void releaseRoots();
423
Andrew Trickc174eaf2012-03-08 01:41:12 +0000424 void releaseSucc(SUnit *SU, SDep *SuccEdge);
425 void releaseSuccessors(SUnit *SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000426 void releasePred(SUnit *SU, SDep *PredEdge);
427 void releasePredecessors(SUnit *SU);
Andrew Trick000b2502012-04-24 18:04:37 +0000428
429 void placeDebugValues();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000430};
431} // namespace
432
433/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
434/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000435///
436/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000437void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000438 SUnit *SuccSU = SuccEdge->getSUnit();
439
440#ifndef NDEBUG
441 if (SuccSU->NumPredsLeft == 0) {
442 dbgs() << "*** Scheduling failed! ***\n";
443 SuccSU->dump(this);
444 dbgs() << " has been released too many times!\n";
445 llvm_unreachable(0);
446 }
447#endif
448 --SuccSU->NumPredsLeft;
449 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000450 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000451}
452
453/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000454void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000455 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
456 I != E; ++I) {
457 releaseSucc(SU, &*I);
458 }
459}
460
Andrew Trick17d35e52012-03-14 04:00:41 +0000461/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
462/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000463///
464/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000465void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
466 SUnit *PredSU = PredEdge->getSUnit();
467
468#ifndef NDEBUG
469 if (PredSU->NumSuccsLeft == 0) {
470 dbgs() << "*** Scheduling failed! ***\n";
471 PredSU->dump(this);
472 dbgs() << " has been released too many times!\n";
473 llvm_unreachable(0);
474 }
475#endif
476 --PredSU->NumSuccsLeft;
477 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
478 SchedImpl->releaseBottomNode(PredSU);
479}
480
481/// releasePredecessors - Call releasePred on each of SU's predecessors.
482void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
483 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
484 I != E; ++I) {
485 releasePred(SU, &*I);
486 }
487}
488
489void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
490 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000491 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000492 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000493 ++RegionBegin;
494
495 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000496 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000497
498 // Update LiveIntervals
Andrew Trick17d35e52012-03-14 04:00:41 +0000499 LIS->handleMove(MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000500
501 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000502 if (RegionBegin == InsertPos)
503 RegionBegin = MI;
504}
505
Andrew Trick0b0d8992012-03-21 04:12:07 +0000506bool ScheduleDAGMI::checkSchedLimit() {
507#ifndef NDEBUG
508 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
509 CurrentTop = CurrentBottom;
510 return false;
511 }
512 ++NumInstrsScheduled;
513#endif
514 return true;
515}
516
Andrew Trick006e1ab2012-04-24 17:56:43 +0000517/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
518/// crossing a scheduling boundary. [begin, end) includes all instructions in
519/// the region, including the boundary itself and single-instruction regions
520/// that don't get scheduled.
521void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
522 MachineBasicBlock::iterator begin,
523 MachineBasicBlock::iterator end,
524 unsigned endcount)
525{
526 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000527
528 // For convenience remember the end of the liveness region.
529 LiveRegionEnd =
530 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
531}
532
533// Setup the register pressure trackers for the top scheduled top and bottom
534// scheduled regions.
535void ScheduleDAGMI::initRegPressure() {
536 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
537 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
538
539 // Close the RPTracker to finalize live ins.
540 RPTracker.closeRegion();
541
Andrew Trickbb0a2422012-05-24 22:11:14 +0000542 DEBUG(RPTracker.getPressure().dump(TRI));
543
Andrew Trick7f8ab782012-05-10 21:06:10 +0000544 // Initialize the live ins and live outs.
545 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
546 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
547
548 // Close one end of the tracker so we can call
549 // getMaxUpward/DownwardPressureDelta before advancing across any
550 // instructions. This converts currently live regs into live ins/outs.
551 TopRPTracker.closeTop();
552 BotRPTracker.closeBottom();
553
554 // Account for liveness generated by the region boundary.
555 if (LiveRegionEnd != RegionEnd)
556 BotRPTracker.recede();
557
558 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000559
560 // Cache the list of excess pressure sets in this region. This will also track
561 // the max pressure in the scheduled code for these sets.
562 RegionCriticalPSets.clear();
563 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
564 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
565 unsigned Limit = TRI->getRegPressureSetLimit(i);
566 if (RegionPressure[i] > Limit)
567 RegionCriticalPSets.push_back(PressureElement(i, 0));
568 }
569 DEBUG(dbgs() << "Excess PSets: ";
570 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
571 dbgs() << TRI->getRegPressureSetName(
572 RegionCriticalPSets[i].PSetID) << " ";
573 dbgs() << "\n");
574}
575
576// FIXME: When the pressure tracker deals in pressure differences then we won't
577// iterate over all RegionCriticalPSets[i].
578void ScheduleDAGMI::
579updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
580 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
581 unsigned ID = RegionCriticalPSets[i].PSetID;
582 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
583 if ((int)NewMaxPressure[ID] > MaxUnits)
584 MaxUnits = NewMaxPressure[ID];
585 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000586}
587
Andrew Trick2aa689d2012-05-24 22:11:05 +0000588// Release all DAG roots for scheduling.
589void ScheduleDAGMI::releaseRoots() {
590 SmallVector<SUnit*, 16> BotRoots;
591
592 for (std::vector<SUnit>::iterator
593 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
594 // A SUnit is ready to top schedule if it has no predecessors.
595 if (I->Preds.empty())
596 SchedImpl->releaseTopNode(&(*I));
597 // A SUnit is ready to bottom schedule if it has no successors.
598 if (I->Succs.empty())
599 BotRoots.push_back(&(*I));
600 }
601 // Release bottom roots in reverse order so the higher priority nodes appear
602 // first. This is more natural and slightly more efficient.
603 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
604 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
605 SchedImpl->releaseBottomNode(*I);
606}
607
Andrew Trick17d35e52012-03-14 04:00:41 +0000608/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000609/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
610/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick17d35e52012-03-14 04:00:41 +0000611void ScheduleDAGMI::schedule() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000612 // Initialize the register pressure tracker used by buildSchedGraph.
613 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000614
Andrew Trick7f8ab782012-05-10 21:06:10 +0000615 // Account for liveness generate by the region boundary.
616 if (LiveRegionEnd != RegionEnd)
617 RPTracker.recede();
618
619 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000620 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000621
Andrew Trick7f8ab782012-05-10 21:06:10 +0000622 // Initialize top/bottom trackers after computing region pressure.
623 initRegPressure();
624
Andrew Trickc174eaf2012-03-08 01:41:12 +0000625 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
626 SUnits[su].dumpAll(this));
627
628 if (ViewMISchedDAGs) viewGraph();
629
Andrew Trick17d35e52012-03-14 04:00:41 +0000630 SchedImpl->initialize(this);
631
632 // Release edges from the special Entry node or to the special Exit node.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000633 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000634 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000635
636 // Release all DAG roots for scheduling.
Andrew Trick2aa689d2012-05-24 22:11:05 +0000637 releaseRoots();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000638
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000639 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick17d35e52012-03-14 04:00:41 +0000640 CurrentBottom = RegionEnd;
641 bool IsTopNode = false;
642 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick0b0d8992012-03-21 04:12:07 +0000643 if (!checkSchedLimit())
644 break;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000645
646 // Move the instruction to its new location in the instruction stream.
647 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000648
Andrew Trick17d35e52012-03-14 04:00:41 +0000649 if (IsTopNode) {
650 assert(SU->isTopReady() && "node still has unscheduled dependencies");
651 if (&*CurrentTop == MI)
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000652 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick811d92682012-05-17 18:35:03 +0000653 else {
Andrew Trick17d35e52012-03-14 04:00:41 +0000654 moveInstruction(MI, CurrentTop);
Andrew Trick811d92682012-05-17 18:35:03 +0000655 TopRPTracker.setPos(MI);
656 }
Andrew Trick7f8ab782012-05-10 21:06:10 +0000657
658 // Update top scheduled pressure.
659 TopRPTracker.advance();
660 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000661 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000662
Andrew Trick17d35e52012-03-14 04:00:41 +0000663 // Release dependent instructions for scheduling.
664 releaseSuccessors(SU);
665 }
666 else {
667 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000668 MachineBasicBlock::iterator priorII =
669 priorNonDebug(CurrentBottom, CurrentTop);
670 if (&*priorII == MI)
671 CurrentBottom = priorII;
Andrew Trick17d35e52012-03-14 04:00:41 +0000672 else {
Andrew Trick811d92682012-05-17 18:35:03 +0000673 if (&*CurrentTop == MI) {
674 CurrentTop = nextIfDebug(++CurrentTop, priorII);
675 TopRPTracker.setPos(CurrentTop);
676 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000677 moveInstruction(MI, CurrentBottom);
678 CurrentBottom = MI;
679 }
Andrew Trick7f8ab782012-05-10 21:06:10 +0000680 // Update bottom scheduled pressure.
681 BotRPTracker.recede();
682 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000683 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000684
Andrew Trick17d35e52012-03-14 04:00:41 +0000685 // Release dependent instructions for scheduling.
686 releasePredecessors(SU);
687 }
688 SU->isScheduled = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000689 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000690 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000691 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
Andrew Trick000b2502012-04-24 18:04:37 +0000692
693 placeDebugValues();
694}
695
696/// Reinsert any remaining debug_values, just like the PostRA scheduler.
697void ScheduleDAGMI::placeDebugValues() {
698 // If first instruction was a DBG_VALUE then put it back.
699 if (FirstDbgValue) {
700 BB->splice(RegionBegin, BB, FirstDbgValue);
701 RegionBegin = FirstDbgValue;
702 }
703
704 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
705 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
706 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
707 MachineInstr *DbgValue = P.first;
708 MachineBasicBlock::iterator OrigPrevMI = P.second;
709 BB->splice(++OrigPrevMI, BB, DbgValue);
710 if (OrigPrevMI == llvm::prior(RegionEnd))
711 RegionEnd = DbgValue;
712 }
713 DbgValues.clear();
714 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000715}
716
717//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000718// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000719//===----------------------------------------------------------------------===//
720
721namespace {
Andrew Trick76e9e832012-06-05 03:44:26 +0000722/// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
723/// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
724/// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
Andrew Trickf3234242012-05-24 22:11:12 +0000725class ReadyQueue {
Andrew Trickd38f87e2012-05-10 21:06:12 +0000726 unsigned ID;
Andrew Trickf3234242012-05-24 22:11:12 +0000727 std::string Name;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000728 std::vector<SUnit*> Queue;
729
Andrew Trickf3234242012-05-24 22:11:12 +0000730public:
731 ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
Andrew Trickd38f87e2012-05-10 21:06:12 +0000732
Andrew Trickf3234242012-05-24 22:11:12 +0000733 unsigned getID() const { return ID; }
734
735 StringRef getName() const { return Name; }
736
737 // SU is in this queue if it's NodeQueueID is a superset of this ID.
738 bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
Andrew Trickd38f87e2012-05-10 21:06:12 +0000739
740 bool empty() const { return Queue.empty(); }
741
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000742 unsigned size() const { return Queue.size(); }
743
Andrew Trickf3234242012-05-24 22:11:12 +0000744 typedef std::vector<SUnit*>::iterator iterator;
745
Andrew Trick16716c72012-05-10 21:06:14 +0000746 iterator begin() { return Queue.begin(); }
747
748 iterator end() { return Queue.end(); }
749
Andrew Trickd38f87e2012-05-10 21:06:12 +0000750 iterator find(SUnit *SU) {
751 return std::find(Queue.begin(), Queue.end(), SU);
752 }
753
754 void push(SUnit *SU) {
755 Queue.push_back(SU);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000756 SU->NodeQueueId |= ID;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000757 }
758
759 void remove(iterator I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000760 (*I)->NodeQueueId &= ~ID;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000761 *I = Queue.back();
762 Queue.pop_back();
763 }
Andrew Trick81f1be32012-05-17 18:35:13 +0000764
Andrew Trickf3234242012-05-24 22:11:12 +0000765 void dump() {
Andrew Trick81f1be32012-05-17 18:35:13 +0000766 dbgs() << Name << ": ";
767 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
768 dbgs() << Queue[i]->NodeNum << " ";
769 dbgs() << "\n";
770 }
Andrew Trickd38f87e2012-05-10 21:06:12 +0000771};
772
Andrew Trick17d35e52012-03-14 04:00:41 +0000773/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
774/// the schedule.
775class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000776
777 /// Store the state used by ConvergingScheduler heuristics, required for the
778 /// lifetime of one invocation of pickNode().
779 struct SchedCandidate {
780 // The best SUnit candidate.
781 SUnit *SU;
782
783 // Register pressure values for the best candidate.
784 RegPressureDelta RPDelta;
785
786 SchedCandidate(): SU(NULL) {}
787 };
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000788 /// Represent the type of SchedCandidate found within a single queue.
789 enum CandResult {
790 NoCand, NodeOrder, SingleExcess, SingleCritical, SingleMax, MultiPressure };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000791
Andrew Trickf3234242012-05-24 22:11:12 +0000792 /// Each Scheduling boundary is associated with ready queues. It tracks the
793 /// current cycle in whichever direction at has moved, and maintains the state
794 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000795 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000796 ScheduleDAGMI *DAG;
797
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000798 ReadyQueue Available;
799 ReadyQueue Pending;
800 bool CheckPending;
801
802 ScheduleHazardRecognizer *HazardRec;
803
804 unsigned CurrCycle;
805 unsigned IssueCount;
806
807 /// MinReadyCycle - Cycle of the soonest available instruction.
808 unsigned MinReadyCycle;
809
Andrew Trickb7e02892012-06-05 21:11:27 +0000810 // Remember the greatest min operand latency.
811 unsigned MaxMinLatency;
812
Andrew Trickf3234242012-05-24 22:11:12 +0000813 /// Pending queues extend the ready queues with the same ID and the
814 /// PendingFlag set.
815 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000816 DAG(0), Available(ID, Name+".A"),
Andrew Trickf3234242012-05-24 22:11:12 +0000817 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
818 CheckPending(false), HazardRec(0), CurrCycle(0), IssueCount(0),
Andrew Trickb7e02892012-06-05 21:11:27 +0000819 MinReadyCycle(UINT_MAX), MaxMinLatency(0) {}
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000820
821 ~SchedBoundary() { delete HazardRec; }
822
Andrew Trickf3234242012-05-24 22:11:12 +0000823 bool isTop() const {
824 return Available.getID() == ConvergingScheduler::TopQID;
825 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000826
Andrew Trick5559ffa2012-06-29 03:23:24 +0000827 bool checkHazard(SUnit *SU);
828
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000829 void releaseNode(SUnit *SU, unsigned ReadyCycle);
830
831 void bumpCycle();
832
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000833 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +0000834
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000835 void releasePending();
836
837 void removeReady(SUnit *SU);
838
839 SUnit *pickOnlyChoice();
840 };
841
Andrew Trick17d35e52012-03-14 04:00:41 +0000842 ScheduleDAGMI *DAG;
Andrew Trick7196a8f2012-05-10 21:06:16 +0000843 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +0000844
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000845 // State of the top and bottom scheduled instruction boundaries.
846 SchedBoundary Top;
847 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +0000848
849public:
Andrew Trickf3234242012-05-24 22:11:12 +0000850 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +0000851 enum {
852 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +0000853 BotQID = 2,
854 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +0000855 };
856
Andrew Trickf3234242012-05-24 22:11:12 +0000857 ConvergingScheduler():
858 DAG(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +0000859
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000860 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +0000861
Andrew Trick7196a8f2012-05-10 21:06:16 +0000862 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +0000863
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000864 virtual void schedNode(SUnit *SU, bool IsTopNode);
865
866 virtual void releaseTopNode(SUnit *SU);
867
868 virtual void releaseBottomNode(SUnit *SU);
869
Andrew Trick7196a8f2012-05-10 21:06:16 +0000870protected:
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000871 SUnit *pickNodeBidrectional(bool &IsTopNode);
872
Andrew Trick8c2d9212012-05-24 22:11:03 +0000873 CandResult pickNodeFromQueue(ReadyQueue &Q,
874 const RegPressureTracker &RPTracker,
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000875 SchedCandidate &Candidate);
Andrew Trick28ebc892012-05-10 21:06:19 +0000876#ifndef NDEBUG
Andrew Trickf3234242012-05-24 22:11:12 +0000877 void traceCandidate(const char *Label, const ReadyQueue &Q, SUnit *SU,
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000878 PressureElement P = PressureElement());
Andrew Trick28ebc892012-05-10 21:06:19 +0000879#endif
Andrew Trick42b7a712012-01-17 06:55:03 +0000880};
881} // namespace
882
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000883void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
884 DAG = dag;
885 TRI = DAG->TRI;
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000886 Top.DAG = dag;
887 Bot.DAG = dag;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000888
889 // Initialize the HazardRecognizers.
890 const TargetMachine &TM = DAG->MF.getTarget();
891 const InstrItineraryData *Itin = TM.getInstrItineraryData();
892 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
893 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
894
895 assert((!ForceTopDown || !ForceBottomUp) &&
896 "-misched-topdown incompatible with -misched-bottomup");
897}
898
899void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000900 if (SU->isScheduled)
901 return;
902
903 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
904 I != E; ++I) {
905 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
906 unsigned Latency =
907 DAG->computeOperandLatency(I->getSUnit(), SU, *I, /*FindMin=*/true);
908#ifndef NDEBUG
909 Top.MaxMinLatency = std::max(Latency, Top.MaxMinLatency);
910#endif
911 if (SU->TopReadyCycle < PredReadyCycle + Latency)
912 SU->TopReadyCycle = PredReadyCycle + Latency;
913 }
914 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000915}
916
917void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000918 if (SU->isScheduled)
919 return;
920
921 assert(SU->getInstr() && "Scheduled SUnit must have instr");
922
923 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
924 I != E; ++I) {
925 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
926 unsigned Latency =
927 DAG->computeOperandLatency(SU, I->getSUnit(), *I, /*FindMin=*/true);
928#ifndef NDEBUG
929 Bot.MaxMinLatency = std::max(Latency, Bot.MaxMinLatency);
930#endif
931 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
932 SU->BotReadyCycle = SuccReadyCycle + Latency;
933 }
934 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000935}
936
Andrew Trick5559ffa2012-06-29 03:23:24 +0000937/// Does this SU have a hazard within the current instruction group.
938///
939/// The scheduler supports two modes of hazard recognition. The first is the
940/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
941/// supports highly complicated in-order reservation tables
942/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
943///
944/// The second is a streamlined mechanism that checks for hazards based on
945/// simple counters that the scheduler itself maintains. It explicitly checks
946/// for instruction dispatch limitations, including the number of micro-ops that
947/// can dispatch per cycle.
948///
949/// TODO: Also check whether the SU must start a new group.
950bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
951 if (HazardRec->isEnabled())
952 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
953
954 if (IssueCount + DAG->getNumMicroOps(SU->getInstr()) > DAG->getIssueWidth())
955 return true;
956
957 return false;
958}
959
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000960void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
961 unsigned ReadyCycle) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000962 if (ReadyCycle < MinReadyCycle)
963 MinReadyCycle = ReadyCycle;
964
965 // Check for interlocks first. For the purpose of other heuristics, an
966 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +0000967 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000968 Pending.push(SU);
969 else
970 Available.push(SU);
971}
972
973/// Move the boundary of scheduled code by one cycle.
974void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000975 unsigned Width = DAG->getIssueWidth();
976 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000977
978 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
979 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
980
981 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000982 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000983 CurrCycle = NextCycle;
984 }
985 else {
Andrew Trickb7e02892012-06-05 21:11:27 +0000986 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000987 for (; CurrCycle != NextCycle; ++CurrCycle) {
988 if (isTop())
989 HazardRec->AdvanceCycle();
990 else
991 HazardRec->RecedeCycle();
992 }
993 }
994 CheckPending = true;
995
Andrew Trickf3234242012-05-24 22:11:12 +0000996 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000997 << CurrCycle << '\n');
998}
999
Andrew Trickb7e02892012-06-05 21:11:27 +00001000/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001001void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001002 // Update the reservation table.
1003 if (HazardRec->isEnabled()) {
1004 if (!isTop() && SU->isCall) {
1005 // Calls are scheduled with their preceding instructions. For bottom-up
1006 // scheduling, clear the pipeline state before emitting.
1007 HazardRec->Reset();
1008 }
1009 HazardRec->EmitInstruction(SU);
1010 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001011 // Check the instruction group dispatch limit.
1012 // TODO: Check if this SU must end a dispatch group.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001013 IssueCount += DAG->getNumMicroOps(SU->getInstr());
1014 if (IssueCount >= DAG->getIssueWidth()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001015 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
1016 bumpCycle();
1017 }
1018}
1019
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001020/// Release pending ready nodes in to the available queue. This makes them
1021/// visible to heuristics.
1022void ConvergingScheduler::SchedBoundary::releasePending() {
1023 // If the available queue is empty, it is safe to reset MinReadyCycle.
1024 if (Available.empty())
1025 MinReadyCycle = UINT_MAX;
1026
1027 // Check to see if any of the pending instructions are ready to issue. If
1028 // so, add them to the available queue.
1029 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1030 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001031 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001032
1033 if (ReadyCycle < MinReadyCycle)
1034 MinReadyCycle = ReadyCycle;
1035
1036 if (ReadyCycle > CurrCycle)
1037 continue;
1038
Andrew Trick5559ffa2012-06-29 03:23:24 +00001039 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001040 continue;
1041
1042 Available.push(SU);
1043 Pending.remove(Pending.begin()+i);
1044 --i; --e;
1045 }
1046 CheckPending = false;
1047}
1048
1049/// Remove SU from the ready set for this boundary.
1050void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1051 if (Available.isInQueue(SU))
1052 Available.remove(Available.find(SU));
1053 else {
1054 assert(Pending.isInQueue(SU) && "bad ready count");
1055 Pending.remove(Pending.find(SU));
1056 }
1057}
1058
1059/// If this queue only has one ready candidate, return it. As a side effect,
1060/// advance the cycle until at least one node is ready. If multiple instructions
1061/// are ready, return NULL.
1062SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1063 if (CheckPending)
1064 releasePending();
1065
1066 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001067 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1068 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001069 bumpCycle();
1070 releasePending();
1071 }
1072 if (Available.size() == 1)
1073 return *Available.begin();
1074 return NULL;
1075}
1076
Andrew Trick28ebc892012-05-10 21:06:19 +00001077#ifndef NDEBUG
Andrew Trickf3234242012-05-24 22:11:12 +00001078void ConvergingScheduler::traceCandidate(const char *Label, const ReadyQueue &Q,
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001079 SUnit *SU, PressureElement P) {
Andrew Trickf3234242012-05-24 22:11:12 +00001080 dbgs() << Label << " " << Q.getName() << " ";
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001081 if (P.isValid())
1082 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1083 << " ";
Andrew Trick28ebc892012-05-10 21:06:19 +00001084 else
1085 dbgs() << " ";
1086 SU->dump(DAG);
1087}
1088#endif
1089
Andrew Trick5429a6b2012-05-17 22:37:09 +00001090/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1091/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001092static bool compareRPDelta(const RegPressureDelta &LHS,
1093 const RegPressureDelta &RHS) {
1094 // Compare each component of pressure in decreasing order of importance
1095 // without checking if any are valid. Invalid PressureElements are assumed to
1096 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001097
1098 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001099 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease)
1100 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1101
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001102 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001103 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease)
1104 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1105
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001106 // Avoid increasing the max pressure of the entire region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001107 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease)
1108 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1109
1110 return false;
1111}
1112
Andrew Trick7196a8f2012-05-10 21:06:16 +00001113/// Pick the best candidate from the top queue.
1114///
1115/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1116/// DAG building. To adjust for the current scheduling location we need to
1117/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001118ConvergingScheduler::CandResult ConvergingScheduler::
Andrew Trick8c2d9212012-05-24 22:11:03 +00001119pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001120 SchedCandidate &Candidate) {
Andrew Trickf3234242012-05-24 22:11:12 +00001121 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001122
Andrew Trick7196a8f2012-05-10 21:06:16 +00001123 // getMaxPressureDelta temporarily modifies the tracker.
1124 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1125
1126 // BestSU remains NULL if no top candidates beat the best existing candidate.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001127 CandResult FoundCandidate = NoCand;
Andrew Trick8c2d9212012-05-24 22:11:03 +00001128 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001129 RegPressureDelta RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001130 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
1131 DAG->getRegionCriticalPSets(),
1132 DAG->getRegPressure().MaxSetPressure);
Andrew Trick7196a8f2012-05-10 21:06:16 +00001133
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001134 // Initialize the candidate if needed.
1135 if (!Candidate.SU) {
1136 Candidate.SU = *I;
1137 Candidate.RPDelta = RPDelta;
1138 FoundCandidate = NodeOrder;
1139 continue;
1140 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001141 // Avoid exceeding the target's limit.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001142 if (RPDelta.Excess.UnitIncrease < Candidate.RPDelta.Excess.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001143 DEBUG(traceCandidate("ECAND", Q, *I, RPDelta.Excess));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001144 Candidate.SU = *I;
1145 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001146 FoundCandidate = SingleExcess;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001147 continue;
1148 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001149 if (RPDelta.Excess.UnitIncrease > Candidate.RPDelta.Excess.UnitIncrease)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001150 continue;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001151 if (FoundCandidate == SingleExcess)
1152 FoundCandidate = MultiPressure;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001153
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001154 // Avoid increasing the max critical pressure in the scheduled region.
1155 if (RPDelta.CriticalMax.UnitIncrease
1156 < Candidate.RPDelta.CriticalMax.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001157 DEBUG(traceCandidate("PCAND", Q, *I, RPDelta.CriticalMax));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001158 Candidate.SU = *I;
1159 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001160 FoundCandidate = SingleCritical;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001161 continue;
1162 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001163 if (RPDelta.CriticalMax.UnitIncrease
1164 > Candidate.RPDelta.CriticalMax.UnitIncrease)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001165 continue;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001166 if (FoundCandidate == SingleCritical)
1167 FoundCandidate = MultiPressure;
1168
1169 // Avoid increasing the max pressure of the entire region.
1170 if (RPDelta.CurrentMax.UnitIncrease
1171 < Candidate.RPDelta.CurrentMax.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001172 DEBUG(traceCandidate("MCAND", Q, *I, RPDelta.CurrentMax));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001173 Candidate.SU = *I;
1174 Candidate.RPDelta = RPDelta;
1175 FoundCandidate = SingleMax;
1176 continue;
1177 }
1178 if (RPDelta.CurrentMax.UnitIncrease
1179 > Candidate.RPDelta.CurrentMax.UnitIncrease)
1180 continue;
1181 if (FoundCandidate == SingleMax)
1182 FoundCandidate = MultiPressure;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001183
1184 // Fall through to original instruction order.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001185 // Only consider node order if Candidate was chosen from this Q.
1186 if (FoundCandidate == NoCand)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001187 continue;
1188
Andrew Trickf3234242012-05-24 22:11:12 +00001189 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
1190 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
1191 DEBUG(traceCandidate("NCAND", Q, *I));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001192 Candidate.SU = *I;
1193 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001194 FoundCandidate = NodeOrder;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001195 }
1196 }
1197 return FoundCandidate;
1198}
1199
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001200/// Pick the best candidate node from either the top or bottom queue.
1201SUnit *ConvergingScheduler::pickNodeBidrectional(bool &IsTopNode) {
1202 // Schedule as far as possible in the direction of no choice. This is most
1203 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001204 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001205 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001206 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001207 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001208 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001209 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001210 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001211 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001212 SchedCandidate BotCand;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001213 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001214 CandResult BotResult = pickNodeFromQueue(Bot.Available,
1215 DAG->getBotRPTracker(), BotCand);
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001216 assert(BotResult != NoCand && "failed to find the first candidate");
1217
1218 // If either Q has a single candidate that provides the least increase in
1219 // Excess pressure, we can immediately schedule from that Q.
1220 //
1221 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1222 // affects picking from either Q. If scheduling in one direction must
1223 // increase pressure for one of the excess PSets, then schedule in that
1224 // direction first to provide more freedom in the other direction.
1225 if (BotResult == SingleExcess || BotResult == SingleCritical) {
1226 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001227 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001228 }
1229 // Check if the top Q has a better candidate.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001230 SchedCandidate TopCand;
1231 CandResult TopResult = pickNodeFromQueue(Top.Available,
1232 DAG->getTopRPTracker(), TopCand);
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001233 assert(TopResult != NoCand && "failed to find the first candidate");
1234
1235 if (TopResult == SingleExcess || TopResult == SingleCritical) {
1236 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001237 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001238 }
1239 // If either Q has a single candidate that minimizes pressure above the
1240 // original region's pressure pick it.
1241 if (BotResult == SingleMax) {
1242 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001243 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001244 }
1245 if (TopResult == SingleMax) {
1246 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001247 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001248 }
1249 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001250 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001251 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001252 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001253 }
1254 // Otherwise prefer the bottom candidate in node order.
1255 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001256 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001257}
1258
1259/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00001260SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1261 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001262 assert(Top.Available.empty() && Top.Pending.empty() &&
1263 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00001264 return NULL;
1265 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001266 SUnit *SU;
1267 if (ForceTopDown) {
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001268 SU = Top.pickOnlyChoice();
1269 if (!SU) {
1270 SchedCandidate TopCand;
1271 CandResult TopResult =
1272 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
1273 assert(TopResult != NoCand && "failed to find the first candidate");
Kaelyn Uhrain5402efa2012-05-24 23:37:49 +00001274 (void)TopResult;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001275 SU = TopCand.SU;
1276 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001277 IsTopNode = true;
1278 }
1279 else if (ForceBottomUp) {
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001280 SU = Bot.pickOnlyChoice();
1281 if (!SU) {
1282 SchedCandidate BotCand;
1283 CandResult BotResult =
1284 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
1285 assert(BotResult != NoCand && "failed to find the first candidate");
Kaelyn Uhrain5402efa2012-05-24 23:37:49 +00001286 (void)BotResult;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001287 SU = BotCand.SU;
1288 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001289 IsTopNode = false;
1290 }
1291 else {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001292 SU = pickNodeBidrectional(IsTopNode);
Andrew Trick7196a8f2012-05-10 21:06:16 +00001293 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001294 if (SU->isTopReady())
1295 Top.removeReady(SU);
1296 if (SU->isBottomReady())
1297 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00001298
1299 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1300 << " Scheduling Instruction in cycle "
1301 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1302 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001303 return SU;
1304}
1305
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001306/// Update the scheduler's state after scheduling a node. This is the same node
1307/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00001308/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001309void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001310 if (IsTopNode) {
1311 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001312 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001313 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001314 else {
1315 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001316 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001317 }
1318}
1319
Andrew Trick17d35e52012-03-14 04:00:41 +00001320/// Create the standard converging machine scheduler. This will be used as the
1321/// default scheduler if the target does not set a default.
1322static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001323 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001324 "-misched-topdown incompatible with -misched-bottomup");
1325 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +00001326}
1327static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00001328ConvergingSchedRegistry("converge", "Standard converging scheduler.",
1329 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00001330
1331//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00001332// Machine Instruction Shuffler for Correctness Testing
1333//===----------------------------------------------------------------------===//
1334
Andrew Trick96f678f2012-01-13 06:30:30 +00001335#ifndef NDEBUG
1336namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00001337/// Apply a less-than relation on the node order, which corresponds to the
1338/// instruction order prior to scheduling. IsReverse implements greater-than.
1339template<bool IsReverse>
1340struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001341 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00001342 if (IsReverse)
1343 return A->NodeNum > B->NodeNum;
1344 else
1345 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001346 }
1347};
1348
Andrew Trick96f678f2012-01-13 06:30:30 +00001349/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00001350class InstructionShuffler : public MachineSchedStrategy {
1351 bool IsAlternating;
1352 bool IsTopDown;
1353
1354 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
1355 // gives nodes with a higher number higher priority causing the latest
1356 // instructions to be scheduled first.
1357 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
1358 TopQ;
1359 // When scheduling bottom-up, use greater-than as the queue priority.
1360 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
1361 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00001362public:
Andrew Trick17d35e52012-03-14 04:00:41 +00001363 InstructionShuffler(bool alternate, bool topdown)
1364 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00001365
Andrew Trick17d35e52012-03-14 04:00:41 +00001366 virtual void initialize(ScheduleDAGMI *) {
1367 TopQ.clear();
1368 BottomQ.clear();
1369 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001370
Andrew Trick17d35e52012-03-14 04:00:41 +00001371 /// Implement MachineSchedStrategy interface.
1372 /// -----------------------------------------
1373
1374 virtual SUnit *pickNode(bool &IsTopNode) {
1375 SUnit *SU;
1376 if (IsTopDown) {
1377 do {
1378 if (TopQ.empty()) return NULL;
1379 SU = TopQ.top();
1380 TopQ.pop();
1381 } while (SU->isScheduled);
1382 IsTopNode = true;
1383 }
1384 else {
1385 do {
1386 if (BottomQ.empty()) return NULL;
1387 SU = BottomQ.top();
1388 BottomQ.pop();
1389 } while (SU->isScheduled);
1390 IsTopNode = false;
1391 }
1392 if (IsAlternating)
1393 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001394 return SU;
1395 }
1396
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001397 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
1398
Andrew Trick17d35e52012-03-14 04:00:41 +00001399 virtual void releaseTopNode(SUnit *SU) {
1400 TopQ.push(SU);
1401 }
1402 virtual void releaseBottomNode(SUnit *SU) {
1403 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00001404 }
1405};
1406} // namespace
1407
Andrew Trickc174eaf2012-03-08 01:41:12 +00001408static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00001409 bool Alternate = !ForceTopDown && !ForceBottomUp;
1410 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001411 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001412 "-misched-topdown incompatible with -misched-bottomup");
1413 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00001414}
Andrew Trick17d35e52012-03-14 04:00:41 +00001415static MachineSchedRegistry ShufflerRegistry(
1416 "shuffle", "Shuffle machine instructions alternating directions",
1417 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00001418#endif // !NDEBUG