blob: a1dc9481c639da361171e2246e14b94a53a3d499 [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
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000215 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000216 // 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 {
Andrew Trick2661b412012-07-07 04:00:00 +0000406 return (InstrItins && InstrItins->SchedModel)
407 ? InstrItins->SchedModel->IssueWidth : 1;
Andrew Trickb7e02892012-06-05 21:11:27 +0000408 }
409
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000410 /// getNumMicroOps - Return the number of issue slots required for this MI.
411 unsigned getNumMicroOps(MachineInstr *MI) const {
Andrew Trick3d4ed082012-07-02 21:55:12 +0000412 if (!InstrItins) return 1;
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000413 int UOps = InstrItins->getNumMicroOps(MI->getDesc().getSchedClass());
414 return (UOps >= 0) ? UOps : TII->getNumMicroOps(InstrItins, MI);
415 }
416
Andrew Trickc174eaf2012-03-08 01:41:12 +0000417protected:
Andrew Trick7f8ab782012-05-10 21:06:10 +0000418 void initRegPressure();
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000419 void updateScheduledPressure(std::vector<unsigned> NewMaxPressure);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000420
Andrew Trick17d35e52012-03-14 04:00:41 +0000421 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
Andrew Trick0b0d8992012-03-21 04:12:07 +0000422 bool checkSchedLimit();
Andrew Trick17d35e52012-03-14 04:00:41 +0000423
Andrew Trick2aa689d2012-05-24 22:11:05 +0000424 void releaseRoots();
425
Andrew Trickc174eaf2012-03-08 01:41:12 +0000426 void releaseSucc(SUnit *SU, SDep *SuccEdge);
427 void releaseSuccessors(SUnit *SU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000428 void releasePred(SUnit *SU, SDep *PredEdge);
429 void releasePredecessors(SUnit *SU);
Andrew Trick000b2502012-04-24 18:04:37 +0000430
431 void placeDebugValues();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000432};
433} // namespace
434
435/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
436/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000437///
438/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000439void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000440 SUnit *SuccSU = SuccEdge->getSUnit();
441
442#ifndef NDEBUG
443 if (SuccSU->NumPredsLeft == 0) {
444 dbgs() << "*** Scheduling failed! ***\n";
445 SuccSU->dump(this);
446 dbgs() << " has been released too many times!\n";
447 llvm_unreachable(0);
448 }
449#endif
450 --SuccSU->NumPredsLeft;
451 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000452 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000453}
454
455/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000456void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000457 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
458 I != E; ++I) {
459 releaseSucc(SU, &*I);
460 }
461}
462
Andrew Trick17d35e52012-03-14 04:00:41 +0000463/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
464/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000465///
466/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000467void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
468 SUnit *PredSU = PredEdge->getSUnit();
469
470#ifndef NDEBUG
471 if (PredSU->NumSuccsLeft == 0) {
472 dbgs() << "*** Scheduling failed! ***\n";
473 PredSU->dump(this);
474 dbgs() << " has been released too many times!\n";
475 llvm_unreachable(0);
476 }
477#endif
478 --PredSU->NumSuccsLeft;
479 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
480 SchedImpl->releaseBottomNode(PredSU);
481}
482
483/// releasePredecessors - Call releasePred on each of SU's predecessors.
484void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
485 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
486 I != E; ++I) {
487 releasePred(SU, &*I);
488 }
489}
490
491void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
492 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000493 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000494 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000495 ++RegionBegin;
496
497 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000498 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000499
500 // Update LiveIntervals
Andrew Trick17d35e52012-03-14 04:00:41 +0000501 LIS->handleMove(MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000502
503 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000504 if (RegionBegin == InsertPos)
505 RegionBegin = MI;
506}
507
Andrew Trick0b0d8992012-03-21 04:12:07 +0000508bool ScheduleDAGMI::checkSchedLimit() {
509#ifndef NDEBUG
510 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
511 CurrentTop = CurrentBottom;
512 return false;
513 }
514 ++NumInstrsScheduled;
515#endif
516 return true;
517}
518
Andrew Trick006e1ab2012-04-24 17:56:43 +0000519/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
520/// crossing a scheduling boundary. [begin, end) includes all instructions in
521/// the region, including the boundary itself and single-instruction regions
522/// that don't get scheduled.
523void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
524 MachineBasicBlock::iterator begin,
525 MachineBasicBlock::iterator end,
526 unsigned endcount)
527{
528 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000529
530 // For convenience remember the end of the liveness region.
531 LiveRegionEnd =
532 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
533}
534
535// Setup the register pressure trackers for the top scheduled top and bottom
536// scheduled regions.
537void ScheduleDAGMI::initRegPressure() {
538 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
539 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
540
541 // Close the RPTracker to finalize live ins.
542 RPTracker.closeRegion();
543
Andrew Trickbb0a2422012-05-24 22:11:14 +0000544 DEBUG(RPTracker.getPressure().dump(TRI));
545
Andrew Trick7f8ab782012-05-10 21:06:10 +0000546 // Initialize the live ins and live outs.
547 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
548 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
549
550 // Close one end of the tracker so we can call
551 // getMaxUpward/DownwardPressureDelta before advancing across any
552 // instructions. This converts currently live regs into live ins/outs.
553 TopRPTracker.closeTop();
554 BotRPTracker.closeBottom();
555
556 // Account for liveness generated by the region boundary.
557 if (LiveRegionEnd != RegionEnd)
558 BotRPTracker.recede();
559
560 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000561
562 // Cache the list of excess pressure sets in this region. This will also track
563 // the max pressure in the scheduled code for these sets.
564 RegionCriticalPSets.clear();
565 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
566 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
567 unsigned Limit = TRI->getRegPressureSetLimit(i);
568 if (RegionPressure[i] > Limit)
569 RegionCriticalPSets.push_back(PressureElement(i, 0));
570 }
571 DEBUG(dbgs() << "Excess PSets: ";
572 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
573 dbgs() << TRI->getRegPressureSetName(
574 RegionCriticalPSets[i].PSetID) << " ";
575 dbgs() << "\n");
576}
577
578// FIXME: When the pressure tracker deals in pressure differences then we won't
579// iterate over all RegionCriticalPSets[i].
580void ScheduleDAGMI::
581updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
582 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
583 unsigned ID = RegionCriticalPSets[i].PSetID;
584 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
585 if ((int)NewMaxPressure[ID] > MaxUnits)
586 MaxUnits = NewMaxPressure[ID];
587 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000588}
589
Andrew Trick2aa689d2012-05-24 22:11:05 +0000590// Release all DAG roots for scheduling.
591void ScheduleDAGMI::releaseRoots() {
592 SmallVector<SUnit*, 16> BotRoots;
593
594 for (std::vector<SUnit>::iterator
595 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
596 // A SUnit is ready to top schedule if it has no predecessors.
597 if (I->Preds.empty())
598 SchedImpl->releaseTopNode(&(*I));
599 // A SUnit is ready to bottom schedule if it has no successors.
600 if (I->Succs.empty())
601 BotRoots.push_back(&(*I));
602 }
603 // Release bottom roots in reverse order so the higher priority nodes appear
604 // first. This is more natural and slightly more efficient.
605 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
606 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
607 SchedImpl->releaseBottomNode(*I);
608}
609
Andrew Trick17d35e52012-03-14 04:00:41 +0000610/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000611/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
612/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick17d35e52012-03-14 04:00:41 +0000613void ScheduleDAGMI::schedule() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000614 // Initialize the register pressure tracker used by buildSchedGraph.
615 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000616
Andrew Trick7f8ab782012-05-10 21:06:10 +0000617 // Account for liveness generate by the region boundary.
618 if (LiveRegionEnd != RegionEnd)
619 RPTracker.recede();
620
621 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000622 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000623
Andrew Trick7f8ab782012-05-10 21:06:10 +0000624 // Initialize top/bottom trackers after computing region pressure.
625 initRegPressure();
626
Andrew Trickc174eaf2012-03-08 01:41:12 +0000627 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
628 SUnits[su].dumpAll(this));
629
630 if (ViewMISchedDAGs) viewGraph();
631
Andrew Trick17d35e52012-03-14 04:00:41 +0000632 SchedImpl->initialize(this);
633
634 // Release edges from the special Entry node or to the special Exit node.
Andrew Trickc174eaf2012-03-08 01:41:12 +0000635 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000636 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000637
638 // Release all DAG roots for scheduling.
Andrew Trick2aa689d2012-05-24 22:11:05 +0000639 releaseRoots();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000640
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000641 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick17d35e52012-03-14 04:00:41 +0000642 CurrentBottom = RegionEnd;
643 bool IsTopNode = false;
644 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick0b0d8992012-03-21 04:12:07 +0000645 if (!checkSchedLimit())
646 break;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000647
648 // Move the instruction to its new location in the instruction stream.
649 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000650
Andrew Trick17d35e52012-03-14 04:00:41 +0000651 if (IsTopNode) {
652 assert(SU->isTopReady() && "node still has unscheduled dependencies");
653 if (&*CurrentTop == MI)
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000654 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick811d92682012-05-17 18:35:03 +0000655 else {
Andrew Trick17d35e52012-03-14 04:00:41 +0000656 moveInstruction(MI, CurrentTop);
Andrew Trick811d92682012-05-17 18:35:03 +0000657 TopRPTracker.setPos(MI);
658 }
Andrew Trick7f8ab782012-05-10 21:06:10 +0000659
660 // Update top scheduled pressure.
661 TopRPTracker.advance();
662 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000663 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000664
Andrew Trick17d35e52012-03-14 04:00:41 +0000665 // Release dependent instructions for scheduling.
666 releaseSuccessors(SU);
667 }
668 else {
669 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000670 MachineBasicBlock::iterator priorII =
671 priorNonDebug(CurrentBottom, CurrentTop);
672 if (&*priorII == MI)
673 CurrentBottom = priorII;
Andrew Trick17d35e52012-03-14 04:00:41 +0000674 else {
Andrew Trick811d92682012-05-17 18:35:03 +0000675 if (&*CurrentTop == MI) {
676 CurrentTop = nextIfDebug(++CurrentTop, priorII);
677 TopRPTracker.setPos(CurrentTop);
678 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000679 moveInstruction(MI, CurrentBottom);
680 CurrentBottom = MI;
681 }
Andrew Trick7f8ab782012-05-10 21:06:10 +0000682 // Update bottom scheduled pressure.
683 BotRPTracker.recede();
684 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000685 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000686
Andrew Trick17d35e52012-03-14 04:00:41 +0000687 // Release dependent instructions for scheduling.
688 releasePredecessors(SU);
689 }
690 SU->isScheduled = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000691 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000692 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000693 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
Andrew Trick000b2502012-04-24 18:04:37 +0000694
695 placeDebugValues();
696}
697
698/// Reinsert any remaining debug_values, just like the PostRA scheduler.
699void ScheduleDAGMI::placeDebugValues() {
700 // If first instruction was a DBG_VALUE then put it back.
701 if (FirstDbgValue) {
702 BB->splice(RegionBegin, BB, FirstDbgValue);
703 RegionBegin = FirstDbgValue;
704 }
705
706 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
707 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
708 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
709 MachineInstr *DbgValue = P.first;
710 MachineBasicBlock::iterator OrigPrevMI = P.second;
711 BB->splice(++OrigPrevMI, BB, DbgValue);
712 if (OrigPrevMI == llvm::prior(RegionEnd))
713 RegionEnd = DbgValue;
714 }
715 DbgValues.clear();
716 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000717}
718
719//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000720// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000721//===----------------------------------------------------------------------===//
722
723namespace {
Andrew Trick76e9e832012-06-05 03:44:26 +0000724/// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
725/// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
726/// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
Andrew Trickf3234242012-05-24 22:11:12 +0000727class ReadyQueue {
Andrew Trickd38f87e2012-05-10 21:06:12 +0000728 unsigned ID;
Andrew Trickf3234242012-05-24 22:11:12 +0000729 std::string Name;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000730 std::vector<SUnit*> Queue;
731
Andrew Trickf3234242012-05-24 22:11:12 +0000732public:
733 ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
Andrew Trickd38f87e2012-05-10 21:06:12 +0000734
Andrew Trickf3234242012-05-24 22:11:12 +0000735 unsigned getID() const { return ID; }
736
737 StringRef getName() const { return Name; }
738
739 // SU is in this queue if it's NodeQueueID is a superset of this ID.
740 bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
Andrew Trickd38f87e2012-05-10 21:06:12 +0000741
742 bool empty() const { return Queue.empty(); }
743
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000744 unsigned size() const { return Queue.size(); }
745
Andrew Trickf3234242012-05-24 22:11:12 +0000746 typedef std::vector<SUnit*>::iterator iterator;
747
Andrew Trick16716c72012-05-10 21:06:14 +0000748 iterator begin() { return Queue.begin(); }
749
750 iterator end() { return Queue.end(); }
751
Andrew Trickd38f87e2012-05-10 21:06:12 +0000752 iterator find(SUnit *SU) {
753 return std::find(Queue.begin(), Queue.end(), SU);
754 }
755
756 void push(SUnit *SU) {
757 Queue.push_back(SU);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000758 SU->NodeQueueId |= ID;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000759 }
760
761 void remove(iterator I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000762 (*I)->NodeQueueId &= ~ID;
Andrew Trickd38f87e2012-05-10 21:06:12 +0000763 *I = Queue.back();
764 Queue.pop_back();
765 }
Andrew Trick81f1be32012-05-17 18:35:13 +0000766
Andrew Trickf3234242012-05-24 22:11:12 +0000767 void dump() {
Andrew Trick81f1be32012-05-17 18:35:13 +0000768 dbgs() << Name << ": ";
769 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
770 dbgs() << Queue[i]->NodeNum << " ";
771 dbgs() << "\n";
772 }
Andrew Trickd38f87e2012-05-10 21:06:12 +0000773};
774
Andrew Trick17d35e52012-03-14 04:00:41 +0000775/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
776/// the schedule.
777class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick7196a8f2012-05-10 21:06:16 +0000778
779 /// Store the state used by ConvergingScheduler heuristics, required for the
780 /// lifetime of one invocation of pickNode().
781 struct SchedCandidate {
782 // The best SUnit candidate.
783 SUnit *SU;
784
785 // Register pressure values for the best candidate.
786 RegPressureDelta RPDelta;
787
788 SchedCandidate(): SU(NULL) {}
789 };
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000790 /// Represent the type of SchedCandidate found within a single queue.
791 enum CandResult {
792 NoCand, NodeOrder, SingleExcess, SingleCritical, SingleMax, MultiPressure };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000793
Andrew Trickf3234242012-05-24 22:11:12 +0000794 /// Each Scheduling boundary is associated with ready queues. It tracks the
795 /// current cycle in whichever direction at has moved, and maintains the state
796 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000797 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000798 ScheduleDAGMI *DAG;
799
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000800 ReadyQueue Available;
801 ReadyQueue Pending;
802 bool CheckPending;
803
804 ScheduleHazardRecognizer *HazardRec;
805
806 unsigned CurrCycle;
807 unsigned IssueCount;
808
809 /// MinReadyCycle - Cycle of the soonest available instruction.
810 unsigned MinReadyCycle;
811
Andrew Trickb7e02892012-06-05 21:11:27 +0000812 // Remember the greatest min operand latency.
813 unsigned MaxMinLatency;
814
Andrew Trickf3234242012-05-24 22:11:12 +0000815 /// Pending queues extend the ready queues with the same ID and the
816 /// PendingFlag set.
817 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000818 DAG(0), Available(ID, Name+".A"),
Andrew Trickf3234242012-05-24 22:11:12 +0000819 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
820 CheckPending(false), HazardRec(0), CurrCycle(0), IssueCount(0),
Andrew Trickb7e02892012-06-05 21:11:27 +0000821 MinReadyCycle(UINT_MAX), MaxMinLatency(0) {}
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000822
823 ~SchedBoundary() { delete HazardRec; }
824
Andrew Trickf3234242012-05-24 22:11:12 +0000825 bool isTop() const {
826 return Available.getID() == ConvergingScheduler::TopQID;
827 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000828
Andrew Trick5559ffa2012-06-29 03:23:24 +0000829 bool checkHazard(SUnit *SU);
830
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000831 void releaseNode(SUnit *SU, unsigned ReadyCycle);
832
833 void bumpCycle();
834
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000835 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +0000836
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000837 void releasePending();
838
839 void removeReady(SUnit *SU);
840
841 SUnit *pickOnlyChoice();
842 };
843
Andrew Trick17d35e52012-03-14 04:00:41 +0000844 ScheduleDAGMI *DAG;
Andrew Trick7196a8f2012-05-10 21:06:16 +0000845 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +0000846
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000847 // State of the top and bottom scheduled instruction boundaries.
848 SchedBoundary Top;
849 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +0000850
851public:
Andrew Trickf3234242012-05-24 22:11:12 +0000852 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +0000853 enum {
854 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +0000855 BotQID = 2,
856 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +0000857 };
858
Andrew Trickf3234242012-05-24 22:11:12 +0000859 ConvergingScheduler():
860 DAG(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +0000861
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000862 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +0000863
Andrew Trick7196a8f2012-05-10 21:06:16 +0000864 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +0000865
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000866 virtual void schedNode(SUnit *SU, bool IsTopNode);
867
868 virtual void releaseTopNode(SUnit *SU);
869
870 virtual void releaseBottomNode(SUnit *SU);
871
Andrew Trick7196a8f2012-05-10 21:06:16 +0000872protected:
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000873 SUnit *pickNodeBidrectional(bool &IsTopNode);
874
Andrew Trick8c2d9212012-05-24 22:11:03 +0000875 CandResult pickNodeFromQueue(ReadyQueue &Q,
876 const RegPressureTracker &RPTracker,
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000877 SchedCandidate &Candidate);
Andrew Trick28ebc892012-05-10 21:06:19 +0000878#ifndef NDEBUG
Andrew Trickf3234242012-05-24 22:11:12 +0000879 void traceCandidate(const char *Label, const ReadyQueue &Q, SUnit *SU,
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000880 PressureElement P = PressureElement());
Andrew Trick28ebc892012-05-10 21:06:19 +0000881#endif
Andrew Trick42b7a712012-01-17 06:55:03 +0000882};
883} // namespace
884
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000885void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
886 DAG = dag;
887 TRI = DAG->TRI;
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000888 Top.DAG = dag;
889 Bot.DAG = dag;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000890
891 // Initialize the HazardRecognizers.
892 const TargetMachine &TM = DAG->MF.getTarget();
893 const InstrItineraryData *Itin = TM.getInstrItineraryData();
894 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
895 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
896
897 assert((!ForceTopDown || !ForceBottomUp) &&
898 "-misched-topdown incompatible with -misched-bottomup");
899}
900
901void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000902 if (SU->isScheduled)
903 return;
904
905 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
906 I != E; ++I) {
907 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
908 unsigned Latency =
909 DAG->computeOperandLatency(I->getSUnit(), SU, *I, /*FindMin=*/true);
910#ifndef NDEBUG
911 Top.MaxMinLatency = std::max(Latency, Top.MaxMinLatency);
912#endif
913 if (SU->TopReadyCycle < PredReadyCycle + Latency)
914 SU->TopReadyCycle = PredReadyCycle + Latency;
915 }
916 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000917}
918
919void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000920 if (SU->isScheduled)
921 return;
922
923 assert(SU->getInstr() && "Scheduled SUnit must have instr");
924
925 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
926 I != E; ++I) {
927 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
928 unsigned Latency =
929 DAG->computeOperandLatency(SU, I->getSUnit(), *I, /*FindMin=*/true);
930#ifndef NDEBUG
931 Bot.MaxMinLatency = std::max(Latency, Bot.MaxMinLatency);
932#endif
933 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
934 SU->BotReadyCycle = SuccReadyCycle + Latency;
935 }
936 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000937}
938
Andrew Trick5559ffa2012-06-29 03:23:24 +0000939/// Does this SU have a hazard within the current instruction group.
940///
941/// The scheduler supports two modes of hazard recognition. The first is the
942/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
943/// supports highly complicated in-order reservation tables
944/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
945///
946/// The second is a streamlined mechanism that checks for hazards based on
947/// simple counters that the scheduler itself maintains. It explicitly checks
948/// for instruction dispatch limitations, including the number of micro-ops that
949/// can dispatch per cycle.
950///
951/// TODO: Also check whether the SU must start a new group.
952bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
953 if (HazardRec->isEnabled())
954 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
955
956 if (IssueCount + DAG->getNumMicroOps(SU->getInstr()) > DAG->getIssueWidth())
957 return true;
958
959 return false;
960}
961
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000962void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
963 unsigned ReadyCycle) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000964 if (ReadyCycle < MinReadyCycle)
965 MinReadyCycle = ReadyCycle;
966
967 // Check for interlocks first. For the purpose of other heuristics, an
968 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +0000969 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000970 Pending.push(SU);
971 else
972 Available.push(SU);
973}
974
975/// Move the boundary of scheduled code by one cycle.
976void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000977 unsigned Width = DAG->getIssueWidth();
978 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000979
980 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
981 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
982
983 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000984 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000985 CurrCycle = NextCycle;
986 }
987 else {
Andrew Trickb7e02892012-06-05 21:11:27 +0000988 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000989 for (; CurrCycle != NextCycle; ++CurrCycle) {
990 if (isTop())
991 HazardRec->AdvanceCycle();
992 else
993 HazardRec->RecedeCycle();
994 }
995 }
996 CheckPending = true;
997
Andrew Trickf3234242012-05-24 22:11:12 +0000998 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000999 << CurrCycle << '\n');
1000}
1001
Andrew Trickb7e02892012-06-05 21:11:27 +00001002/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001003void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001004 // Update the reservation table.
1005 if (HazardRec->isEnabled()) {
1006 if (!isTop() && SU->isCall) {
1007 // Calls are scheduled with their preceding instructions. For bottom-up
1008 // scheduling, clear the pipeline state before emitting.
1009 HazardRec->Reset();
1010 }
1011 HazardRec->EmitInstruction(SU);
1012 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001013 // Check the instruction group dispatch limit.
1014 // TODO: Check if this SU must end a dispatch group.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001015 IssueCount += DAG->getNumMicroOps(SU->getInstr());
1016 if (IssueCount >= DAG->getIssueWidth()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001017 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
1018 bumpCycle();
1019 }
1020}
1021
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001022/// Release pending ready nodes in to the available queue. This makes them
1023/// visible to heuristics.
1024void ConvergingScheduler::SchedBoundary::releasePending() {
1025 // If the available queue is empty, it is safe to reset MinReadyCycle.
1026 if (Available.empty())
1027 MinReadyCycle = UINT_MAX;
1028
1029 // Check to see if any of the pending instructions are ready to issue. If
1030 // so, add them to the available queue.
1031 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1032 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001033 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001034
1035 if (ReadyCycle < MinReadyCycle)
1036 MinReadyCycle = ReadyCycle;
1037
1038 if (ReadyCycle > CurrCycle)
1039 continue;
1040
Andrew Trick5559ffa2012-06-29 03:23:24 +00001041 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001042 continue;
1043
1044 Available.push(SU);
1045 Pending.remove(Pending.begin()+i);
1046 --i; --e;
1047 }
1048 CheckPending = false;
1049}
1050
1051/// Remove SU from the ready set for this boundary.
1052void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1053 if (Available.isInQueue(SU))
1054 Available.remove(Available.find(SU));
1055 else {
1056 assert(Pending.isInQueue(SU) && "bad ready count");
1057 Pending.remove(Pending.find(SU));
1058 }
1059}
1060
1061/// If this queue only has one ready candidate, return it. As a side effect,
1062/// advance the cycle until at least one node is ready. If multiple instructions
1063/// are ready, return NULL.
1064SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1065 if (CheckPending)
1066 releasePending();
1067
1068 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001069 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1070 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001071 bumpCycle();
1072 releasePending();
1073 }
1074 if (Available.size() == 1)
1075 return *Available.begin();
1076 return NULL;
1077}
1078
Andrew Trick28ebc892012-05-10 21:06:19 +00001079#ifndef NDEBUG
Andrew Trickf3234242012-05-24 22:11:12 +00001080void ConvergingScheduler::traceCandidate(const char *Label, const ReadyQueue &Q,
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001081 SUnit *SU, PressureElement P) {
Andrew Trickf3234242012-05-24 22:11:12 +00001082 dbgs() << Label << " " << Q.getName() << " ";
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001083 if (P.isValid())
1084 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1085 << " ";
Andrew Trick28ebc892012-05-10 21:06:19 +00001086 else
1087 dbgs() << " ";
1088 SU->dump(DAG);
1089}
1090#endif
1091
Andrew Trick5429a6b2012-05-17 22:37:09 +00001092/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1093/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001094static bool compareRPDelta(const RegPressureDelta &LHS,
1095 const RegPressureDelta &RHS) {
1096 // Compare each component of pressure in decreasing order of importance
1097 // without checking if any are valid. Invalid PressureElements are assumed to
1098 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001099
1100 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001101 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease)
1102 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1103
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001104 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001105 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease)
1106 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1107
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001108 // Avoid increasing the max pressure of the entire region.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001109 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease)
1110 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1111
1112 return false;
1113}
1114
Andrew Trick7196a8f2012-05-10 21:06:16 +00001115/// Pick the best candidate from the top queue.
1116///
1117/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1118/// DAG building. To adjust for the current scheduling location we need to
1119/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001120ConvergingScheduler::CandResult ConvergingScheduler::
Andrew Trick8c2d9212012-05-24 22:11:03 +00001121pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001122 SchedCandidate &Candidate) {
Andrew Trickf3234242012-05-24 22:11:12 +00001123 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001124
Andrew Trick7196a8f2012-05-10 21:06:16 +00001125 // getMaxPressureDelta temporarily modifies the tracker.
1126 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1127
1128 // BestSU remains NULL if no top candidates beat the best existing candidate.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001129 CandResult FoundCandidate = NoCand;
Andrew Trick8c2d9212012-05-24 22:11:03 +00001130 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001131 RegPressureDelta RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001132 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
1133 DAG->getRegionCriticalPSets(),
1134 DAG->getRegPressure().MaxSetPressure);
Andrew Trick7196a8f2012-05-10 21:06:16 +00001135
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001136 // Initialize the candidate if needed.
1137 if (!Candidate.SU) {
1138 Candidate.SU = *I;
1139 Candidate.RPDelta = RPDelta;
1140 FoundCandidate = NodeOrder;
1141 continue;
1142 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001143 // Avoid exceeding the target's limit.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001144 if (RPDelta.Excess.UnitIncrease < Candidate.RPDelta.Excess.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001145 DEBUG(traceCandidate("ECAND", Q, *I, RPDelta.Excess));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001146 Candidate.SU = *I;
1147 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001148 FoundCandidate = SingleExcess;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001149 continue;
1150 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001151 if (RPDelta.Excess.UnitIncrease > Candidate.RPDelta.Excess.UnitIncrease)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001152 continue;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001153 if (FoundCandidate == SingleExcess)
1154 FoundCandidate = MultiPressure;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001155
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001156 // Avoid increasing the max critical pressure in the scheduled region.
1157 if (RPDelta.CriticalMax.UnitIncrease
1158 < Candidate.RPDelta.CriticalMax.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001159 DEBUG(traceCandidate("PCAND", Q, *I, RPDelta.CriticalMax));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001160 Candidate.SU = *I;
1161 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001162 FoundCandidate = SingleCritical;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001163 continue;
1164 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001165 if (RPDelta.CriticalMax.UnitIncrease
1166 > Candidate.RPDelta.CriticalMax.UnitIncrease)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001167 continue;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001168 if (FoundCandidate == SingleCritical)
1169 FoundCandidate = MultiPressure;
1170
1171 // Avoid increasing the max pressure of the entire region.
1172 if (RPDelta.CurrentMax.UnitIncrease
1173 < Candidate.RPDelta.CurrentMax.UnitIncrease) {
Andrew Trickf3234242012-05-24 22:11:12 +00001174 DEBUG(traceCandidate("MCAND", Q, *I, RPDelta.CurrentMax));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001175 Candidate.SU = *I;
1176 Candidate.RPDelta = RPDelta;
1177 FoundCandidate = SingleMax;
1178 continue;
1179 }
1180 if (RPDelta.CurrentMax.UnitIncrease
1181 > Candidate.RPDelta.CurrentMax.UnitIncrease)
1182 continue;
1183 if (FoundCandidate == SingleMax)
1184 FoundCandidate = MultiPressure;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001185
1186 // Fall through to original instruction order.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001187 // Only consider node order if Candidate was chosen from this Q.
1188 if (FoundCandidate == NoCand)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001189 continue;
1190
Andrew Trickf3234242012-05-24 22:11:12 +00001191 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
1192 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
1193 DEBUG(traceCandidate("NCAND", Q, *I));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001194 Candidate.SU = *I;
1195 Candidate.RPDelta = RPDelta;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001196 FoundCandidate = NodeOrder;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001197 }
1198 }
1199 return FoundCandidate;
1200}
1201
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001202/// Pick the best candidate node from either the top or bottom queue.
1203SUnit *ConvergingScheduler::pickNodeBidrectional(bool &IsTopNode) {
1204 // Schedule as far as possible in the direction of no choice. This is most
1205 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001206 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001207 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001208 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001209 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001210 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001211 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001212 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001213 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001214 SchedCandidate BotCand;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001215 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001216 CandResult BotResult = pickNodeFromQueue(Bot.Available,
1217 DAG->getBotRPTracker(), BotCand);
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001218 assert(BotResult != NoCand && "failed to find the first candidate");
1219
1220 // If either Q has a single candidate that provides the least increase in
1221 // Excess pressure, we can immediately schedule from that Q.
1222 //
1223 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1224 // affects picking from either Q. If scheduling in one direction must
1225 // increase pressure for one of the excess PSets, then schedule in that
1226 // direction first to provide more freedom in the other direction.
1227 if (BotResult == SingleExcess || BotResult == SingleCritical) {
1228 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001229 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001230 }
1231 // Check if the top Q has a better candidate.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001232 SchedCandidate TopCand;
1233 CandResult TopResult = pickNodeFromQueue(Top.Available,
1234 DAG->getTopRPTracker(), TopCand);
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001235 assert(TopResult != NoCand && "failed to find the first candidate");
1236
1237 if (TopResult == SingleExcess || TopResult == SingleCritical) {
1238 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001239 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001240 }
1241 // If either Q has a single candidate that minimizes pressure above the
1242 // original region's pressure pick it.
1243 if (BotResult == SingleMax) {
1244 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001245 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001246 }
1247 if (TopResult == SingleMax) {
1248 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001249 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001250 }
1251 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001252 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001253 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001254 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001255 }
1256 // Otherwise prefer the bottom candidate in node order.
1257 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001258 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001259}
1260
1261/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00001262SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1263 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001264 assert(Top.Available.empty() && Top.Pending.empty() &&
1265 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00001266 return NULL;
1267 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001268 SUnit *SU;
1269 if (ForceTopDown) {
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001270 SU = Top.pickOnlyChoice();
1271 if (!SU) {
1272 SchedCandidate TopCand;
1273 CandResult TopResult =
1274 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
1275 assert(TopResult != NoCand && "failed to find the first candidate");
Kaelyn Uhrain5402efa2012-05-24 23:37:49 +00001276 (void)TopResult;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001277 SU = TopCand.SU;
1278 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001279 IsTopNode = true;
1280 }
1281 else if (ForceBottomUp) {
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001282 SU = Bot.pickOnlyChoice();
1283 if (!SU) {
1284 SchedCandidate BotCand;
1285 CandResult BotResult =
1286 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
1287 assert(BotResult != NoCand && "failed to find the first candidate");
Kaelyn Uhrain5402efa2012-05-24 23:37:49 +00001288 (void)BotResult;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001289 SU = BotCand.SU;
1290 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001291 IsTopNode = false;
1292 }
1293 else {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001294 SU = pickNodeBidrectional(IsTopNode);
Andrew Trick7196a8f2012-05-10 21:06:16 +00001295 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001296 if (SU->isTopReady())
1297 Top.removeReady(SU);
1298 if (SU->isBottomReady())
1299 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00001300
1301 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1302 << " Scheduling Instruction in cycle "
1303 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1304 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00001305 return SU;
1306}
1307
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001308/// Update the scheduler's state after scheduling a node. This is the same node
1309/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00001310/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001311void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001312 if (IsTopNode) {
1313 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001314 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001315 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001316 else {
1317 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001318 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001319 }
1320}
1321
Andrew Trick17d35e52012-03-14 04:00:41 +00001322/// Create the standard converging machine scheduler. This will be used as the
1323/// default scheduler if the target does not set a default.
1324static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001325 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001326 "-misched-topdown incompatible with -misched-bottomup");
1327 return new ScheduleDAGMI(C, new ConvergingScheduler());
Andrew Trick42b7a712012-01-17 06:55:03 +00001328}
1329static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00001330ConvergingSchedRegistry("converge", "Standard converging scheduler.",
1331 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00001332
1333//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00001334// Machine Instruction Shuffler for Correctness Testing
1335//===----------------------------------------------------------------------===//
1336
Andrew Trick96f678f2012-01-13 06:30:30 +00001337#ifndef NDEBUG
1338namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00001339/// Apply a less-than relation on the node order, which corresponds to the
1340/// instruction order prior to scheduling. IsReverse implements greater-than.
1341template<bool IsReverse>
1342struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001343 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00001344 if (IsReverse)
1345 return A->NodeNum > B->NodeNum;
1346 else
1347 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001348 }
1349};
1350
Andrew Trick96f678f2012-01-13 06:30:30 +00001351/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00001352class InstructionShuffler : public MachineSchedStrategy {
1353 bool IsAlternating;
1354 bool IsTopDown;
1355
1356 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
1357 // gives nodes with a higher number higher priority causing the latest
1358 // instructions to be scheduled first.
1359 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
1360 TopQ;
1361 // When scheduling bottom-up, use greater-than as the queue priority.
1362 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
1363 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00001364public:
Andrew Trick17d35e52012-03-14 04:00:41 +00001365 InstructionShuffler(bool alternate, bool topdown)
1366 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00001367
Andrew Trick17d35e52012-03-14 04:00:41 +00001368 virtual void initialize(ScheduleDAGMI *) {
1369 TopQ.clear();
1370 BottomQ.clear();
1371 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001372
Andrew Trick17d35e52012-03-14 04:00:41 +00001373 /// Implement MachineSchedStrategy interface.
1374 /// -----------------------------------------
1375
1376 virtual SUnit *pickNode(bool &IsTopNode) {
1377 SUnit *SU;
1378 if (IsTopDown) {
1379 do {
1380 if (TopQ.empty()) return NULL;
1381 SU = TopQ.top();
1382 TopQ.pop();
1383 } while (SU->isScheduled);
1384 IsTopNode = true;
1385 }
1386 else {
1387 do {
1388 if (BottomQ.empty()) return NULL;
1389 SU = BottomQ.top();
1390 BottomQ.pop();
1391 } while (SU->isScheduled);
1392 IsTopNode = false;
1393 }
1394 if (IsAlternating)
1395 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00001396 return SU;
1397 }
1398
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001399 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
1400
Andrew Trick17d35e52012-03-14 04:00:41 +00001401 virtual void releaseTopNode(SUnit *SU) {
1402 TopQ.push(SU);
1403 }
1404 virtual void releaseBottomNode(SUnit *SU) {
1405 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00001406 }
1407};
1408} // namespace
1409
Andrew Trickc174eaf2012-03-08 01:41:12 +00001410static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00001411 bool Alternate = !ForceTopDown && !ForceBottomUp;
1412 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00001413 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00001414 "-misched-topdown incompatible with -misched-bottomup");
1415 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00001416}
Andrew Trick17d35e52012-03-14 04:00:41 +00001417static MachineSchedRegistry ShufflerRegistry(
1418 "shuffle", "Shuffle machine instructions alternating directions",
1419 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00001420#endif // !NDEBUG